From 49a0ef0f9b64f8c832694273b88346049e57edfb Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 14:16:40 -0500 Subject: [PATCH 01/14] ci: sync the Antigravity reviewer with the hardened template Re-sync scripts/agy-review.sh, _agy_print.sh, _agy_comment_body.sh and agy-review-selftest.sh byte for byte from the antigravity-pr-review template at 1451f73, refresh .github/AGY-REVIEWER.md where present, and rebuild the workflow from the template. Security (template d77b07c .. 1451f73): - agy runs in a bubblewrap jail (AGY_ISOLATION=bwrap, default): an empty private HOME (no MCP servers, skills, hooks, dotfiles or other repositories), read-only /usr and /etc, only the review sandbox writable, and a D-Bus that is an xdg-dbus-proxy allowing only agy's own Secret Service item. agy's own --sandbox was verified NOT to confine reads, and agy otherwise loads the host's MCP servers (REA, Blender) where a prompt-injected diff could drive them. - agy's output is scanned for credential shapes before posting; on a match nothing is posted (fail closed). Patterns are anchored so ordinary identifiers never match. - agy now runs from a private mktemp sandbox under RUNNER_TEMP, never from the checkout; the large-diff handoff file lives there and only the sandbox is passed to --add-dir. agy runs with --dangerously-skip-permissions on an untrusted diff, so a prompt injection could previously write .git/hooks or .git/config that a later token-bearing git call would execute. - agy gets an allowlisted environment (env -i plus the session variables its keyring-held Google login needs). No job token (GH_TOKEN, ACTIONS_RUNTIME_TOKEN, OIDC) or workflow env value reaches it, whatever its name. - Post-agy git calls ignore hooks and fsmonitor. - The workflow skips with a visible warning instead of failing red when the default branch has no reviewer. - AGY_ENV_PASSTHROUGH accepts only valid identifiers and never glob-expands; the sandbox path is canonical; an inline dry run no longer leaks it (template 2262811, from the reviews of the first re-sync PRs). Also carried: the base print timeout is 10m (was 5m; backported from three repositories that pinned 10-15m after timeouts), the cumulative dropped-round count and en-US spelling (template c9ded19, f492f3e), and every template fix since this copy was taken. The first-install bootstrap steps are omitted (the reviewer is already on the default branch; they trip CodeQL actions/untrusted-checkout), unless this repository vendors the workflow byte for byte. Verification: scripts/agy-review-selftest.sh "all checks passed" (including the new sandbox, allowlist and hook checks and the workflow timeout/lock budget); actionlint clean. Co-Authored-By: Claude Opus 5.5 --- .github/AGY-REVIEWER.md | 105 +++-- .github/workflows/antigravity-review.yml | 48 ++- scripts/_agy_comment_body.sh | 20 +- scripts/agy-review-selftest.sh | 258 +++++++++++- scripts/agy-review.sh | 495 +++++++++++++++++------ 5 files changed, 749 insertions(+), 177 deletions(-) diff --git a/.github/AGY-REVIEWER.md b/.github/AGY-REVIEWER.md index b556eb18..77373cd7 100644 --- a/.github/AGY-REVIEWER.md +++ b/.github/AGY-REVIEWER.md @@ -34,7 +34,7 @@ is why this uses a self-hosted runner rather than GitHub's cloud runners. ## How it works -``` +```text GitHub PR event ──▶ self-hosted runner (YOUR machine, systemd --user) │ gh pr diff ─▶ build adversarial-reviewer prompt (+ style guide) │ agy --print (PTY-wrapped, OAuth/Ultra) ─▶ review text @@ -61,8 +61,8 @@ Files in this template: > **Copy into a target repo** (what `install-into-repo.sh` does): the workflow, the four > scripts `agy-review.sh`, `_agy_print.sh`, `_agy_comment_body.sh` and > `agy-review-selftest.sh`, this README as `.github/AGY-REVIEWER.md`, -> `.github/actionlint.yaml` when the target has none, optionally `.github/agy-review.md`, -> and one appended `.gitignore` line (`/.agy-review-work/`). Everything else +> `.github/actionlint.yaml` when the target has none, and optionally `.github/agy-review.md`. +> The target's `.gitignore` is not touched. Everything else > (`systemd/`, the provision/deprovision scripts, this repo's `.gitignore`, `*.example`, > `gitignore.snippet`) stays here. @@ -78,9 +78,15 @@ agy -p "reply with the single word: ok" # should print: ok # Tools the reviewer uses (all already present here): # gh jq sqlite3 col script + unbuffer (from `expect`) -pacman -Q github-cli jq sqlite expect util-linux >/dev/null # verify; install any missing with paru/pacman +# bwrap xdg-dbus-proxy gdbus (the agy jail; AGY_ISOLATION=bwrap, the default) +# iconv (glibc) for UTF-8 scrubbing; python3 is an optional fallback used only without iconv +pacman -Q github-cli jq sqlite expect util-linux bubblewrap xdg-dbus-proxy glib2 >/dev/null # verify; install any missing with paru/pacman ``` +`unbuffer` is preferred. Without it, the reviewer falls back to `script(1)` and strips the +`Script started on` and `Script done on` records that util-linux writes into the capture even +with `-q`. + If `agy -p` prints nothing, fix auth first (run `agy` interactively once to complete the Google sign-in) — the reviewer can't work until that one-liner does. @@ -153,26 +159,15 @@ the `git add/commit/push` to finish. Then jump to **Triggering it** below. That's it — no repository secrets. The job uses the built-in `GITHUB_TOKEN` to post comments and your local `agy` session for the model. -### About `.gitignore` (append, don't overwrite) - -The reviewer works in temporary directories (`mktemp` / `$RUNNER_TEMP`) for -everything **except** one case: when a PR's diff is too large to inline in the -argv prompt, it writes the diff to a gitignored working-tree scratch dir, -`.agy-review-work/`, so agy can read it in full with its file tools instead of -the review being truncated to the execve arg-size ceiling. The file and the -(now-empty) dir are removed by the script's `EXIT` trap. Because that path is in -the working tree, a target repo **does** need `/.agy-review-work/` in its -`.gitignore` — otherwise the transient `.patch` shows as untracked pollution on -large-diff PRs. Still **never** copy this template's own `.gitignore` over a -project's. +### About `.gitignore` -**Append** the ignore entries idempotently: - -```fish -# from the target repo root -grep -qxF '/.agy-review-work/' .gitignore 2>/dev/null - or cat $TPL/gitignore.snippet >> .gitignore # TPL: your checkout of this template -``` +The reviewer writes nothing into the working tree. All its files, including the +large-diff handoff file agy reads when a diff is too large to inline, live in a +private `mktemp -d` sandbox under `$RUNNER_TEMP` that the `EXIT` trap removes, so a +target repo needs no ignore entry. (Earlier versions wrote the handoff file to +`.agy-review-work/` in the checkout and required `/.agy-review-work/` in +`.gitignore`; that line is now unused and harmless where it already exists.) +**Never** copy this template's own `.gitignore` over a project's. --- @@ -200,7 +195,7 @@ consecutive rounds each raised a blocking issue and only the second survived — clean comment list is not evidence that nothing was raised. The script no longer issues a `DELETE` at all; `agy-review-selftest.sh` asserts -that, so the behaviour cannot come back unnoticed. The archive is bounded by +that, so the behavior cannot come back unnoticed. The archive is bounded by `MAX_BODY_BYTES` (default 60000, under GitHub's 65536 limit); when rounds must be dropped to fit, the oldest go first **and the body says how many were dropped**, because a silent truncation would look exactly like a PR reviewed only once. @@ -211,7 +206,7 @@ because a silent truncation would look exactly like a PR reviewed only once. > immediately. > > The same rule governs the **scripts**: the workflow checks out the default branch -> to run them, so a change to `agy-review.sh` (the archive behaviour above included) +> to run them, so a change to `agy-review.sh` (the archive behavior above included) > has **no effect on any PR until it is merged**, not even on the PR that makes it. --- @@ -246,13 +241,49 @@ yours to accept: `scripts/agy-review.sh`, which asks the permissions API for the commenter and fails closed; the script also re-checks that the PR is not from a fork, because the `issue_comment` payload has no head-repo field for the `if:` to gate on. -- **First-install bootstrap:** the checked-in workflow has no bootstrap steps. On a - repository whose default branch has no reviewer yet, add the guarded bootstrap - steps first. They run the PR head's scripts once, only for a same-repo branch - whose author has write access *at run time*. Remove them once the reviewer is on - the default branch (they also trip CodeQL's `actions/untrusted-checkout`). +- **First-install bootstrap:** as shipped, on a repository whose default branch has + no reviewer yet, the workflow runs the PR head's scripts once, only for a + same-repo branch whose author has write access *at run time*. Remove the + bootstrap steps once the reviewer is on the default branch (they also trip + CodeQL's `actions/untrusted-checkout`); most repositories carrying this reviewer + have done so. Without them, a PR opened while the default branch has no + reviewer gets a `::warning::` and a skipped review step (the "Check the + reviewer is present" step), not a red check. - **Least surface in the job:** review-only prompt, `--sandbox`, no repo secrets (built-in `GITHUB_TOKEN` only), temp files cleaned via an `EXIT` trap. +- **agy runs in a bubblewrap jail (`AGY_ISOLATION=bwrap`, the default):** agy's + own `--sandbox` does **not** confine reads (verified: it read a canary file in + `$HOME`), and agy loads the user's whole configuration, including MCP servers + (REA, Blender, ...), skills and hooks. So the script starts it in a `bwrap` jail + with an empty private `HOME`, read-only `/usr` and `/etc`, the review sandbox, + and no other part of the host filesystem. Its D-Bus is an `xdg-dbus-proxy` with + `--filter` that allows only the Secret Service calls agy makes, and `GetSecret` + only on agy's own keyring item. The script resolves that item outside the jail + from `AGY_KEYRING_ATTRS`. Verified: inside the jail agy logs in and reviews, has + no MCP tools, cannot read `~/.config/gh` or any repository, and fetching another + keyring item (the `gh` token), the bulk `GetSecrets` call or any other session + service is `AccessDenied`. A host without `bwrap`, `xdg-dbus-proxy` or `gdbus` + fails closed. `AGY_ISOLATION=none` opts out, which is not recommended. +- **agy never sees the checkout:** agy runs with `--dangerously-skip-permissions` + and reads an untrusted diff, so a prompt injection could try to write files. + It is started from a private, empty `mktemp -d` sandbox under `$RUNNER_TEMP` + (the script refuses to run if that path is inside the checkout), the large-diff + handoff file is written there, and only that directory is passed to + `--add-dir`. A planted `.git/hooks` or `.git/config` in the checkout, which a + later token-bearing `git` call would execute, is therefore out of reach; the + script's own post-agy `git` calls also run with `core.hooksPath=/dev/null` and + `core.fsmonitor=false`. +- **agy gets no credentials:** agy is started with an **allowlisted** environment + (`env -i` plus `HOME`, `PATH`, `USER`, `LOGNAME`, `SHELL`, the locale, `TERM`, + `TMPDIR`, `TZ`, the `XDG_*` directories, `DBUS_SESSION_BUS_ADDRESS`, `DISPLAY`, + `WAYLAND_DISPLAY`, `XAUTHORITY`). Nothing else from the job reaches it: no + `GH_TOKEN`/`GITHUB_TOKEN`, no `ACTIONS_RUNTIME_TOKEN` or OIDC request token, and no + workflow `env:` value, including secrets under ordinary names that a + name-pattern denylist would miss. The session variables are what agy needs to + reach the desktop keyring holding its Google OAuth session, which was verified on + the runner host. `AGY_ENV_PASSTHROUGH` (space-separated names) adds a variable + if a host needs one. `unbuffer` keeps its own environment and runs `env -i ... agy`, + so only agy is reduced. `agy-review-selftest.sh` asserts all of the above. To reduce the remaining exposure, run each job on a **clean, disposable host** (a VM or container image recreated per job). Re-registering a runner on the same host is not enough, @@ -268,19 +299,31 @@ runner, so disable fork workflows there or gate them the same way. |----------|---------|---------| | `AGY_MODEL` | *(agy default)* | e.g. `gemini-3-pro`; run `agy models` to see IDs | | `AGY_EFFORT` | `high` | reasoning effort: `low` / `medium` / `high` | -| `AGY_PRINT_TIMEOUT` | `5m` | base wait for a single `agy --print`; raised for a large diff (next row). Setting it pins it and turns the raise off | +| `AGY_PRINT_TIMEOUT` | `10m` | base wait for a single `agy --print`; raised for a large diff (next row). Setting it pins it and turns the raise off. Was `5m`: mid-size inlined diffs at `high` effort timed out at that base | | `AGY_TIMEOUT_SECONDS_PER_MIB` | `900` | extra seconds per MiB of diff. A diff handed over as a file costs agy 6-8 minutes almost whatever its size, so this is deliberately steep (240 left a 426 KB diff at 397 s, too little) | | `AGY_PRINT_TIMEOUT_MAX_SECONDS` | `1800` (workflow: `900`) | ceiling on one attempt after the raise | | `AGY_RETRIES` | `3` (workflow: `2`) | attempts; a retry is for a transient backend error, so more of them at the same budget only repeat a timeout | +| `AGY_LOCK_WAIT` | `600` (workflow: `1860`) | seconds to wait for the host-wide agy lock before giving up. Every repository's review on the host shares it (agy is one singleton per user), and a review holds it across all its attempts and the pauses between them, so the wait must outlast another review's whole hold: 1860 s covers one review at two 900 s attempts plus the 15 s pause, so it is sized for ONE review ahead in the queue: with two or more large reviews already waiting from other repositories, a third can still time out (re-run it). It counts toward the job's worst case, so raising it means raising `timeout-minutes` (the selftest checks the sum) | | `AGY_DIFF_MODE` | `auto` | how the diff reaches agy: `inline` (in the `--print` prompt), `file` (written to a file agy reads with its tools), or `auto` (inline if it fits the arg-size budget, else file — so **large PRs are never truncated**) | | `MAX_DIFF_BYTES` | `5000000` | sanity cap on a pathological diff (5 MB). Not the arg-size limit — a large diff goes to agy as a file, not an argv value | | `MAX_PROMPT_BYTES` | `120000` | the inline/file threshold in `auto` mode, and a hard backstop on the **inlined** prompt. agy takes an inlined prompt as a `--print` argv value, and a single `execve` argument cannot exceed `MAX_ARG_STRLEN` (128 KiB); over it `execve` fails with E2BIG before agy starts. Clamped below 128 KiB | | `STYLE_GUIDE` | `.github/agy-review.md` | repo-relative style guide, loaded if present | +| `AGY_ISOLATION` | `bwrap` | `bwrap` runs agy in the jail described under the security model; `none` runs it unjailed (not recommended) | +| `AGY_KEYRING_ATTRS` | `username=antigravity service=gemini` | Secret Service attributes of agy's own login item; the jail's D-Bus proxy allows `GetSecret` on the matching item(s) only | +| `AGY_ENV_PASSTHROUGH` | *(empty)* | extra environment variable NAMES (space-separated) to pass to agy on top of the session allowlist; everything else is withheld | --- ## Troubleshooting +- **"agy lock timed out after Ns" and a red job with no review:** another + review on the same host held the agy lock longer than `AGY_LOCK_WAIT`. The + lock is shared by every repository's review there, so two PRs opened at once + in different repositories queue behind each other; with a wait shorter than + one review (the old 300 s), the second gives up. Re-run the job once the other + review finishes, and keep `AGY_LOCK_WAIT` above another review's worst-case + hold (`AGY_RETRIES` x the per-attempt cap, plus the pauses). The lock fails + closed: a timeout exits rather than running two agy processes at once. - **Review comment never appears / job succeeds but empty:** the classic Antigravity **issue #76** — `agy -p` drops stdout when it isn't attached to a TTY. This template runs `agy` under a PTY (`unbuffer`, or `scripts/_agy_print.sh` diff --git a/.github/workflows/antigravity-review.yml b/.github/workflows/antigravity-review.yml index c4d94d7a..3ea1c53b 100644 --- a/.github/workflows/antigravity-review.yml +++ b/.github/workflows/antigravity-review.yml @@ -69,10 +69,11 @@ jobs: # for a large one handed over as a file. The cap must still exceed the # script's own worst case -- lock wait + every retry at its maximum timeout + # backoff -- or the job is killed mid-retry and posts nothing. With the - # settings below that is 300 + 2 x 900 + 15 = 2115 s, under 45 minutes with + # settings below that is 1860 + 2 x 900 + 15 = 3675 s, under 80 minutes with # room for checkout and the diff fetch; the selftest checks this sum against - # this value. - timeout-minutes: 45 + # this value. (Until 2026-11-15: 300 + 2 x 900 + 15 = 2115 s under 45 + # minutes; see AGY_LOCK_WAIT for why the wait grew.) + timeout-minutes: 80 steps: # Check out the DEFAULT BRANCH, never the PR head. This job runs the checked-out # `scripts/agy-review.sh` on a self-hosted runner with a token in the environment, @@ -96,17 +97,30 @@ jobs: # needs on demand, so a full history clone would be paid on every run for a path # most runs never take. fetch-depth: 1 - # No checkout should persist credentials: agy executes with the repo as its - # workspace, so a token left in .git/config would be reachable by anything the - # review runs. The large-diff fallback still performs an authenticated fetch, but + # No checkout should persist credentials: a token left in .git/config would be + # readable by anything that can read the checkout. (agy itself now runs from a + # private sandbox outside it, with no job credentials in its environment.) The large-diff fallback still performs an authenticated fetch, but # supplies the token per command via `http.extraheader` rather than persisting it. persist-credentials: false - # The template's first-install BOOTSTRAP steps are deliberately omitted here: the reviewer - # is already on this repository's default branch, so they could never fire, and their - # PR-head checkout trips CodeQL's actions/untrusted-checkout (high) on every scan. - # Re-add them only for a repository that has never had the reviewer on its default branch. + # The template's first-install BOOTSTRAP steps are deliberately omitted: the reviewer is + # already on this repository's default branch, so they could never fire, and their + # PR-head checkout trips CodeQL's actions/untrusted-checkout (high). Re-add them only for + # a repository that has never had the reviewer on its default branch. + # If the default branch has no reviewer (it was removed, or a fresh install), report it as a visible + # warning and skip, rather than a red check that only means "not installed yet". Only the + # absence of the script is tolerated; any failure inside it is not. + - name: Check the reviewer is present + id: reviewer + run: | + if [ -f scripts/agy-review.sh ]; then + echo "present=true" >> "$GITHUB_OUTPUT" + else + echo "::warning title=Antigravity review skipped::scripts/agy-review.sh is not on the default branch yet, so this PR cannot be reviewed. Reviews run once the reviewer is merged." + echo "present=false" >> "$GITHUB_OUTPUT" + fi - name: Run Antigravity review + if: steps.reviewer.outputs.present == 'true' env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} # --- optional overrides (uncomment to change) --- @@ -115,7 +129,7 @@ jobs: # A large diff goes to agy as a file, and reading it at high effort costs 6-8 # minutes almost whatever its size (1.15 MB: 465 s; 426 KB timed out three times at # 397 s under the old 240 s/MiB scaling). The scaling is now 900 s/MiB (the - # script's AGY_TIMEOUT_SECONDS_PER_MIB), so 900 s here is reached from ~650 KB. + # script's AGY_TIMEOUT_SECONDS_PER_MIB), so with the 10m base 900 s here is reached from ~340 KB. AGY_PRINT_TIMEOUT_MAX_SECONDS: "900" # per-attempt cap (default 1800) # Also set here, not only as the script's default: a pull_request run takes # this file from the PR branch but the script from the default branch, so a @@ -125,7 +139,17 @@ jobs: # Two attempts, not three: a retry is for a transient backend error; a third # attempt at the same budget only repeats a timeout. AGY_RETRIES: "2" - AGY_LOCK_WAIT: "300" # wait for another review's lock (default 600) + # The lock is shared by EVERY repository's review on this host, not only this + # one's (agy is one singleton per user). 300 s was shorter than one review + # elsewhere: on 2026-11-15 RustyNES_MiSTer's PR #79 and RustyNES's PR #664 + # opened together, #664's review of a large diff held the lock, and #79's job + # gave up after 300 s ("agy lock timed out") and went red with no review. + # 1860 s outlasts another review's whole hold: the lock is held across both of its + # attempts at the 15-minute cap AND the 15 s pause between them (2 x 900 + 15 = + # 1815 s), plus a margin for process start-up; this is what moved + # timeout-minutes to 80. The runner is self-hosted, so the longer wait + # bills nothing; the wait is a queue, not a fail-open. + AGY_LOCK_WAIT: "1860" # wait for another review's lock (default 600) # AGY_DIFF_MODE: auto # auto|inline|file — how the diff reaches agy. `auto` # # (default) inlines a small diff and hands a large one to # # agy as a file, so PR size never truncates the review. diff --git a/scripts/_agy_comment_body.sh b/scripts/_agy_comment_body.sh index 83d5b302..20cbd187 100755 --- a/scripts/_agy_comment_body.sh +++ b/scripts/_agy_comment_body.sh @@ -90,6 +90,24 @@ agy_body_archive() { }' || true } +# How many rounds earlier runs dropped to fit GitHub's comment limit, from the +# "N earlier round(s) dropped" note; 0 when there is none. +# +# The note sits between the SECTION and START sentinels, outside both regions the next run reads +# back (agy_body_head stops at the section, agy_body_archive starts after START), and the caller's +# count restarted at 0 every run -- so a later round that dropped nothing erased the disclosure +# (agy review of Rusty2600 #53). Only that one region is searched, so a note quoted inside a +# round's review text is never mistaken for the real one. +agy_body_dropped_count() { + awk -v sec="$AGY_ARCHIVE_SECTION" -v s="$AGY_ARCHIVE_START" ' + $0 == sec { between = 1; next } + $0 == s { exit } + between && match($0, /^[0-9]+ earlier round\(s\) dropped/) { + n = substr($0, 6); sub(/[^0-9].*$/, "", n); print n + 0; found = 1; exit + } + END { if (!found) print 0 }' +} + # Prefix of the hidden line that records when a review was posted. The comment head carries # it so that, when the round is archived on the next run, the summary can say when it was # REVIEWED; the time of archiving says nothing useful. @@ -99,7 +117,7 @@ AGY_REVIEWED_AT_PREFIX='\nBODY' "$AGY_REVIEWED_AT_PREFIX")" "" "LATER" \ | grep -c -F 'Round reviewed at 2026-10-06 12:34 UTC')" -check "a head without the line is labelled archived-at" "1" \ +check "a head without the line is labeled archived-at" "1" \ "$(agy_assemble_archive "BODY" "" "LATER" | grep -c -F 'Round archived at LATER')" if grep -q 'AGY_REVIEWED_AT_PREFIX' "$SCRIPT_DIR/agy-review.sh"; then echo " ok the posted head records its reviewed-at time" @@ -569,9 +683,46 @@ case "$verdict" in exceeds*) echo " FAIL worst case ${verdict#exceeds } does not fit the job timeout"; fails=$((fails + 1)) ;; *) echo " FAIL could not read the timeout budget from $wf"; fails=$((fails + 1)) ;; esac +# lock_verdict: "covers" when AGY_LOCK_WAIT outlasts ONE other review's whole hold of the +# host-wide agy lock (every attempt at the per-attempt budget plus the pauses between them), +# else "short"; empty when unreadable. The sum above can fit the job timeout while the wait +# itself is shorter than another review's hold, and then a review queued behind a busy +# repository's still times out red (AGY_LOCK_WAIT 300 against a ~15-minute review, RustyNES +# #664 / RustyNES_MiSTer #79, 2026-11-15; Antigravity on RustyNES #665). +lock_verdict() { + local max_s lock_s retries delay pin per hold + max_s="$(wf_val AGY_PRINT_TIMEOUT_MAX_SECONDS)"; [ -n "$max_s" ] || max_s="$(sh_default AGY_PRINT_TIMEOUT_MAX_SECONDS)" + lock_s="$(wf_val AGY_LOCK_WAIT)"; [ -n "$lock_s" ] || lock_s="$(sh_default AGY_LOCK_WAIT)" + retries="$(wf_val AGY_RETRIES)"; [ -n "$retries" ] || retries="$(sh_default AGY_RETRIES)" + delay="$(wf_val AGY_RETRY_DELAY)"; [ -n "$delay" ] || delay="$(sh_default AGY_RETRY_DELAY)" + pin="$(wf_pin)" + per="$max_s" + if [ -n "$pin" ]; then per="$(duration_to_seconds "$pin")" || return 0; fi + [ -n "$per" ] && [ -n "$lock_s" ] && [ -n "$retries" ] && [ -n "$delay" ] || return 0 + hold=$(( retries * per + delay * retries * (retries - 1) / 2 )) + if [ "$lock_s" -gt "$hold" ]; then echo "covers ${lock_s}s ${hold}s"; else echo "short ${lock_s}s ${hold}s"; fi +} +lv="$(lock_verdict)" +case "$lv" in + covers*) read -r lw lh <<<"${lv#covers }"; echo " ok AGY_LOCK_WAIT $lw outlasts one other review's whole hold of the agy lock ($lh)" ;; + short*) read -r lw lh <<<"${lv#short }"; echo " FAIL AGY_LOCK_WAIT $lw is shorter than one other review's hold of the agy lock ($lh)"; fails=$((fails + 1)) ;; + *) echo " FAIL could not read the lock-wait budget from $wf"; fails=$((fails + 1)) ;; +esac +# And it must be able to fail: the old 300 s wait against the same workflow is short. +real_wf="$wf" +sed 's/^\([[:space:]]*AGY_LOCK_WAIT:[[:space:]]*\)"\{0,1\}[0-9]*"\{0,1\}/\1"300"/' "$real_wf" > "$TMPD/lock300.yml" +wf="$TMPD/lock300.yml" +check "a 300 s AGY_LOCK_WAIT is reported shorter than one review's hold" "short" "$(lock_verdict | cut -d' ' -f1)" +wf="$real_wf" # The pin must count: the same workflow with a 50-minute pin has to be reported as exceeding. real_wf="$wf" -sed 's/^\([[:space:]]*\)AGY_EFFORT:.*/&\n\1AGY_PRINT_TIMEOUT: 50m/' "$real_wf" > "$TMPD/pinned.yml" +# Drop any pin the real workflow already carries first, so the synthetic file has exactly one +# AGY_PRINT_TIMEOUT key whatever this repository pins (a duplicate key only "worked" because the +# reader stops at the first match). +sed -e '/^[[:space:]]*AGY_PRINT_TIMEOUT:/d' \ + -e 's/^\([[:space:]]*\)AGY_EFFORT:.*/&\n\1AGY_PRINT_TIMEOUT: 50m/' "$real_wf" > "$TMPD/pinned.yml" +check "the synthetic pinned workflow has exactly one AGY_PRINT_TIMEOUT key" "1" \ + "$(grep -c '^[[:space:]]*AGY_PRINT_TIMEOUT:' "$TMPD/pinned.yml")" wf="$TMPD/pinned.yml" check "a pinned AGY_PRINT_TIMEOUT counts in the timeout budget" "exceeds" "$(budget_verdict | cut -d' ' -f1)" wf="$real_wf" @@ -604,6 +755,85 @@ else echo " ok no \`exec\` redirects to /dev/null" fi +# agy runs under --dangerously-skip-permissions and reads an untrusted diff, so the repository +# checkout must never be in its workspace: a planted .git/hooks or .git/config would execute in a +# later token-bearing git call. The large-diff handoff once used `--add-dir "$PWD"`. +check "agy is never given the checkout via --add-dir" "0" \ + "$(grep -cE -- '--add-dir[[:space:]]+"?\$(PWD|\{PWD\})' "$SCRIPT_DIR/agy-review.sh")" +check "agy runs from its private sandbox directory (both PTY paths)" "2" \ + "$(grep -cE '\( cd "\$agy_sandbox" && ' "$SCRIPT_DIR/agy-review.sh")" +check "both PTY paths start inside the allowlisted environment (env -i before unbuffer/script)" "2" \ + "$(grep -cE '\( cd "\$agy_sandbox" && "\$\{agy_env\[@\]\}" (unbuffer|AGY_BIN=)' "$SCRIPT_DIR/agy-review.sh")" +# bubblewrap isolation (AGY_ISOLATION=bwrap): agy's --sandbox does not confine reads and agy loads +# the user's MCP servers/skills/hooks, so the jail is the real boundary. Statically pin its shape. +SCRIPT="$SCRIPT_DIR/agy-review.sh" +check "isolation defaults to bwrap" "1" \ + "$(grep -c '^AGY_ISOLATION="\${AGY_ISOLATION:-bwrap}"' "$SCRIPT")" +check "both PTY paths launch agy through the jail" "2" \ + "$(grep -cE 'unbuffer "\$\{agy_jail\[@\]\}" "\$AGY_BIN"|printf .%q . "\$\{agy_jail\[@\]\}" "\$here/_agy_print.sh"' "$SCRIPT")" +check "the jail gives agy an empty private HOME (tmpfs /home + private bind)" "1" \ + "$(grep -c -- '--tmpfs /home --bind "\$agy_jail_home" "\$HOME"' "$SCRIPT")" +check "Item.GetSecret is granted only on the resolved keyring item(s)" "1" \ + "$(grep -c 'Secret.Item.GetSecret@' "$SCRIPT")" +check "the GetSecret grant uses the resolved item variable, never a wildcard" "1" \ + "$(grep -c 'Secret.Item.GetSecret@\${_it}' "$SCRIPT")" +check "the bulk Service.GetSecrets call is never granted" "0" \ + "$(grep -c 'Secret.Service.GetSecrets' "$SCRIPT")" +check "a missing bwrap/xdg-dbus-proxy/gdbus fails closed" "1" \ + "$(grep -c "refusing to run agy unjailed (set AGY_ISOLATION=none" "$SCRIPT")" +check "the proxy runs with --filter (deny by default)" "1" \ + "$(grep -c 'xdg-dbus-proxy "\$DBUS_SESSION_BUS_ADDRESS" "\$agy_jail_rt/bus" --filter' "$SCRIPT")" +# Credential scan: every shape is caught, ordinary review text is not. +cred_tmp="$TMPD/cred.txt" +# Samples are assembled at runtime from split pieces, so this file never contains a literal that a +# repository secret scanner (gitleaks) would flag. +s_jwt="eyJ""hbGciOiJIUzI1NiJ9.""eyJ""zdWIiOiIxMjM0NTY3ODkwIn0.abcdefghijklmnop" +s_aws="AKI""AABCDEFGHIJKLMNOP" +s_key="-----BEGIN OPENSSH ""PRIVATE KEY-----" +for sample in "token ya2""9.$(printf 'a%.0s' {1..30})" "refresh 1/""/0$(printf 'b%.0s' {1..30})" \ + "gh""p_$(printf 'c%.0s' {1..36})" "github""_pat_$(printf 'd%.0s' {1..50})" \ + "$s_key" "$s_jwt" "key $s_aws." "sk-a""nt-$(printf 'e%.0s' {1..40})" \ + "sk-pro""j-$(printf 'f%.0s' {1..40})" "xox""b-1234567890-abcdef"; do + printf '## Review\n\nfound %s here\n' "$sample" > "$cred_tmp" + check "credential scan catches: ${sample:0:14}..." "yes" \ + "$(credential_kind_present "$cred_tmp" >/dev/null && echo yes || echo no)" +done +# No false positives on ordinary identifiers that merely CONTAIN a token prefix. +for benign in "task-$(printf 'g%.0s' {1..40})" "disk-$(printf 'h%.0s' {1..40})" \ + "risk-assessment-of-the-new-staging-pipeline-in-detail" \ + "xghp_$(printf 'i%.0s' {1..36})" "myxoxb-thing" "BAKIA$(printf 'J%.0s' {1..16})Z"; do + printf '## Review\n\nsee %s for details\n' "$benign" > "$cred_tmp" + check "credential scan ignores: ${benign:0:14}..." "no" \ + "$(credential_kind_present "$cred_tmp" >/dev/null && echo yes || echo no)" +done +printf '## Review\n\nNo blocking issues. GH_TOKEN is stripped; see ya29 docs and the BEGIN marker.\n' > "$cred_tmp" +check "credential scan passes ordinary review text" "no" \ + "$(credential_kind_present "$cred_tmp" >/dev/null && echo yes || echo no)" +check "post-agy git calls disable hooks and fsmonitor" "2" \ + "$(grep -cE 'git -c core\.hooksPath=/dev/null -c core\.fsmonitor=false update-ref' "$SCRIPT_DIR/agy-review.sh")" + +# The allowlisted environment: run the real function against a fake job environment. Anything not +# on the allowlist is dropped, including credentials under ordinary-looking names. +env_fn="$(sed -n '/^agy_allowlisted_env_args() {/,/^}/p' "$SCRIPT_DIR/agy-review.sh")" +check "the allowlist function was found in agy-review.sh" "yes" "$([ -n "$env_fn" ] && echo yes || echo no)" +env_out="$( + export GH_TOKEN=x GITHUB_TOKEN=x ACTIONS_RUNTIME_TOKEN=x ACTIONS_ID_TOKEN_REQUEST_TOKEN=x \ + RUNNER_TEMP=/t NPM_TOKEN=x DATABASE_URL='postgres://u:pw@h/db' SOME_SETTING=x \ + HOME=/home/u PATH=/usr/bin DBUS_SESSION_BUS_ADDRESS=unix:path=/b XDG_RUNTIME_DIR=/run/u \ + EXTRA_OK=1 AGY_ENV_PASSTHROUGH='BAD=NAME 1 1FOO * ../x EXTRA_OK' + eval "$env_fn" + args=( env ) + while IFS= read -r -d '' a; do args+=( "$a" ); done < <(agy_allowlisted_env_args) + "${args[@]}" env +)" +check "agy's environment drops everything off the allowlist (tokens, ordinary-named secrets)" "0" \ + "$(grep -cE '^(GH_TOKEN|GITHUB_TOKEN|ACTIONS_RUNTIME_TOKEN|ACTIONS_ID_TOKEN_REQUEST_TOKEN|RUNNER_TEMP|NPM_TOKEN|DATABASE_URL|SOME_SETTING|AGY_ENV_PASSTHROUGH|BAD)=' <<<"$env_out" || true)" +# Invalid passthrough entries (an assignment, a bare digit that would read $1, `1FOO` that used +# to abort with "bad substitution", a glob, a path) are skipped without aborting, so EXTRA_OK, +# listed last, must still arrive. +check "agy's environment keeps the session variables it needs, plus AGY_ENV_PASSTHROUGH names" "5" \ + "$(grep -cE '^(HOME|PATH|DBUS_SESSION_BUS_ADDRESS|XDG_RUNTIME_DIR|EXTRA_OK)=' <<<"$env_out" || true)" + if [ "$fails" -ne 0 ]; then echo "$fails check(s) failed" >&2 exit 1 diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index 6a1dd631..bd17b4ac 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -151,17 +151,60 @@ OAUTH_URL_RE='https?://accounts\.google\.com/o/oauth2' # URL is always present in a real login flow, so it alone is both necessary and sufficient; a # lapse is detected AND a leak is blocked by the same unconditional check. oauth_url_present() { [ -s "$1" ] && grep -qiE "$OAUTH_URL_RE" "$1"; } + +# Credential shapes that must never reach a public PR comment. Every pattern is anchored on a +# leading non-identifier boundary, so an ordinary identifier (`task-...`, `disk-...`, a word ending +# in `ghp`) cannot match and wrongly block a review. agy's --sandbox does NOT confine +# reads (verified 2026-11-22: from the sandbox it read a canary file in $HOME with both its file +# tool and a shell `cat`), so a prompt-injected diff could make it print a token from the runner +# host. Fail closed on any match in agy's output. The log names only the KIND that matched, never +# the value, since Actions logs of a public repository are public too. +credential_kind_present() { + [ -s "$1" ] || return 1 + local kind re + while IFS='|' read -r kind re; do + if grep -qE -- "$re" "$1"; then printf '%s' "$kind"; return 0; fi + done <<'CREDS' +google-oauth-access-token|(^|[^A-Za-z0-9_-])ya29\.[0-9A-Za-z_-]{20,} +google-oauth-refresh-token|(^|[^A-Za-z0-9_/-])1//0[0-9A-Za-z_-]{20,} +github-token|(^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{30,} +github-fine-grained-pat|(^|[^A-Za-z0-9_])github_pat_[A-Za-z0-9_]{40,} +private-key-block|-----BEGIN [A-Z ]*PRIVATE KEY----- +jwt|(^|[^A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,} +aws-access-key-id|(^|[^A-Za-z0-9])(AKIA|ASIA)[0-9A-Z]{16}([^A-Za-z0-9]|$) +anthropic-key|(^|[^A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{32,} +openai-key|(^|[^A-Za-z0-9_-])sk-(proj-)?[A-Za-z0-9]{32,}([^A-Za-z0-9_-]|$) +slack-token|(^|[^A-Za-z0-9_-])xox[abprs]-[A-Za-z0-9-]{10,} +CREDS + return 1 +} # <<< SELFTEST-EXTRACT # --- configuration (all env-overridable from the workflow) --------------------- AGY_BIN="${AGY_BIN:-agy}" command -v "$AGY_BIN" >/dev/null 2>&1 || AGY_BIN="$HOME/.local/bin/agy" +# Absolute paths before anything is created or a subshell changes directory: agy runs in a +# subshell that first changes into the sandbox, so a relative TMPDIR (which every later mktemp honors), a relative +# RUNNER_TEMP or a relative AGY_BIN would otherwise resolve against the sandbox. +AGY_BIN="$(command -v "$AGY_BIN" 2>/dev/null || printf '%s' "$AGY_BIN")" +case "$AGY_BIN" in /*) ;; *) AGY_BIN="$PWD/$AGY_BIN" ;; esac +for _v in TMPDIR RUNNER_TEMP; do + case "${!_v:-}" in + ''|/*) ;; + *) if _abs="$(cd "${!_v}" 2>/dev/null && pwd -P)"; then export "$_v=$_abs"; else unset "$_v"; fi ;; + esac +done +unset _v _abs AGY_MODEL="${AGY_MODEL:-}" # empty = agy's configured default (Gemini 3.x Pro) AGY_EFFORT="${AGY_EFFORT:-high}" # low|medium|high # Base timeout for a normal review. Scaled up for a large diff further down -- see # `scale_timeout_for_diff`. Set AGY_PRINT_TIMEOUT explicitly to pin it and skip the scaling. AGY_PRINT_TIMEOUT_EXPLICIT="${AGY_PRINT_TIMEOUT:+set}" -AGY_PRINT_TIMEOUT="${AGY_PRINT_TIMEOUT:-5m}" +# Base 10m (was 5m). Backported from three repositories that each pinned 10-15m after reviews +# timed out at the old base: Infinity-Context PR #31 saw a 79 KB INLINED diff at high effort time +# out twice at the scaled 367 s, and GH-ListRollup / RustyNES_MiSTer pinned 10m / 15m for the same +# reason. The scaling below adds to this base for large diffs; the per-attempt cap still bounds it. +AGY_PRINT_TIMEOUT="${AGY_PRINT_TIMEOUT:-10m}" # Seconds of budget per MiB of diff handed to agy, on top of the base. Reading a 1.6 MB patch and # reasoning over it is not work a five-minute budget can absorb, and the failure is indistinguishable # from a backend outage: `Error: timeout waiting for response`, three times, with no review. @@ -175,7 +218,7 @@ AGY_PRINT_TIMEOUT_MAX_SECONDS="${AGY_PRINT_TIMEOUT_MAX_SECONDS:-1800}" # Both of the above reach `$(( ... ))`, so both are validated before they get there. # >>> SELFTEST-EXTRACT: numeric env validation -# Validate and canonicalise a numeric setting that will reach an arithmetic expansion. +# Validate and canonicalize a numeric setting that will reach an arithmetic expansion. # # @param $1 name of the variable to validate, assigned in place. # @param $2 default to fall back to when the value is not a non-negative decimal integer. @@ -188,19 +231,19 @@ AGY_PRINT_TIMEOUT_MAX_SECONDS="${AGY_PRINT_TIMEOUT_MAX_SECONDS:-1800}" # bash 5.3 (measured here): they reach the parser as a literal and are refused with # "arithmetic syntax error: operand expected". This was reported in review as a CWE-78, and an # earlier version of this comment asserted the execution -- WRONGLY, from a nested-quoting -# artefact in the test that ran it. It does not reproduce. What is left is still worth +# artifact in the test that ran it. It does not reproduce. What is left is still worth # refusing: a value naming another variable silently means something other than what it says. # 2. Digits-only is not sufficient on its own. `09` is all digits, and bash reads the leading # zero as OCTAL: # $(( 1000000 * 09 / 1048576 )) -> value too great for base # So a *valid* setting takes the script down under `set -e`. That one is demonstrated, not -# theoretical, and is the reason this function exists. Canonicalising to base 10 here, once, +# theoretical, and is the reason this function exists. Canonicalizing to base 10 here, once, # means no downstream `$(( ))` has to remember `10#`. # The locals are `_nne_`-prefixed because this function assigns THROUGH A NAME the caller supplies. # Plain `name`/`val` locals shadow a caller variable of the same name, and the failure is silent -- -# `normalise_numeric_env val 240` reads and writes the local, leaving the caller's `val` untouched. -# Verified: with unprefixed locals, `val=07; normalise_numeric_env val 240` leaves val as `07`. -normalise_numeric_env() { +# `normalize_numeric_env val 240` reads and writes the local, leaving the caller's `val` untouched. +# Verified: with unprefixed locals, `val=07; normalize_numeric_env val 240` leaves val as `07`. +normalize_numeric_env() { local _nne_name="$1" _nne_default="$2" _nne_val="${!1}" case "$_nne_val" in ""|*[!0-9]*) @@ -210,8 +253,29 @@ normalise_numeric_env() { esac } # <<< SELFTEST-EXTRACT -normalise_numeric_env AGY_TIMEOUT_SECONDS_PER_MIB 900 -normalise_numeric_env AGY_PRINT_TIMEOUT_MAX_SECONDS 1800 +normalize_numeric_env AGY_TIMEOUT_SECONDS_PER_MIB 900 +normalize_numeric_env AGY_PRINT_TIMEOUT_MAX_SECONDS 1800 +# >>> SELFTEST-EXTRACT: error cap validation +# AGY_ERROR_MAX_BYTES is set above, inside the service-error block (which cannot call +# normalize_numeric_env: it is defined later). A non-numeric value (GH-ListRollup PR #6) or 0 +# (PR #7) made service_error_present's `-le` test always fail, silently disabling the +# backend-error guard. A function, so the selftest can run it with bad values (PR #7, round 2). +agy_validate_error_cap() { + normalize_numeric_env AGY_ERROR_MAX_BYTES 2000 + [ "$AGY_ERROR_MAX_BYTES" -gt 0 ] || { log "AGY_ERROR_MAX_BYTES=0 would disable the backend-error guard; using the default (2000)"; AGY_ERROR_MAX_BYTES=2000; } +} +# <<< SELFTEST-EXTRACT +agy_validate_error_cap +# OS-level isolation of agy (bubblewrap). agy's own --sandbox does NOT confine reads, and agy loads +# the user's whole config (MCP servers, skills, hooks), so a prompt-injected diff could read host +# files or drive powerful local tools. With `bwrap` (the default) agy runs in a jail with an empty +# private HOME, read-only /usr and /etc, the review sandbox, and a D-Bus that is an xdg-dbus-proxy +# exposing only agy's own Secret Service item. `none` runs agy unjailed (not recommended). A host +# missing bwrap/xdg-dbus-proxy/gdbus fails closed rather than silently running unjailed. +AGY_ISOLATION="${AGY_ISOLATION:-bwrap}" +case "$AGY_ISOLATION" in bwrap|none) ;; *) echo "AGY_ISOLATION must be bwrap or none, got '$AGY_ISOLATION'" >&2; exit 1 ;; esac +# Attributes agy uses to look up its keyring item (observed on the Secret Service bus). +AGY_KEYRING_ATTRS="${AGY_KEYRING_ATTRS:-username=antigravity service=gemini}" AGY_DIFF_MODE="${AGY_DIFF_MODE:-auto}" # auto|inline|file. A diff is passed to agy either inlined # in the --print prompt, or written to a FILE agy reads with # its own tools. `auto` inlines a diff that fits under the @@ -220,6 +284,10 @@ AGY_DIFF_MODE="${AGY_DIFF_MODE:-auto}" # auto|inline|file. A diff is passed MAX_DIFF_BYTES="${MAX_DIFF_BYTES:-5000000}" # sanity cap on a pathological diff (5 MB). No longer the # arg-size limit -- a large diff goes to agy as a file, not # as an argv value -- just a guard against a runaway diff. +# Same validation as the other numerics (agy review, GH-ListRollup PR #4): a non-numeric value such +# as `5MB` failed agy_cut_file's `-gt 0` test and SILENTLY disabled the cap, and `0` does the same. +normalize_numeric_env MAX_DIFF_BYTES 5000000 +[ "$MAX_DIFF_BYTES" -gt 0 ] || { log "MAX_DIFF_BYTES=0 would disable the sanity cap; using the default (5000000)"; MAX_DIFF_BYTES=5000000; } MAX_PROMPT_BYTES="${MAX_PROMPT_BYTES:-120000}" # hard ceiling on the INLINED prompt: agy takes it as a # --print VALUE (not stdin), and a single execve argument # cannot exceed MAX_ARG_STRLEN (PAGE_SIZE*32 = 128 KiB on @@ -240,6 +308,12 @@ ARG_SIZE_CEILING=120000 # hard cap: a configured MAX_PROMPT_ # so without it the clamp is skipped and the `head -c "$MAX_PROMPT_BYTES"` prompt cap below runs # as GNU `head -c -1` (print all-but-last-byte) — silently defeating the E2BIG backstop. A # non-numeric value trips the `2>/dev/null` and is clamped too. +# +# normalize_numeric_env first (agy review, GH-ListRollup PR #4): `[ ]` reads `080000` as decimal and +# lets it through, but the `$(( MAX_PROMPT_BYTES - ... ))` arithmetic below parses a leading zero as +# octal and aborts the run under `set -e` ("value too great for base"). Normalizing strips the +# leading zero and maps anything non-numeric (including a negative) to the default. +normalize_numeric_env MAX_PROMPT_BYTES 120000 if ! { [ "$MAX_PROMPT_BYTES" -gt 0 ] && [ "$MAX_PROMPT_BYTES" -le "$ARG_SIZE_CEILING" ]; } 2>/dev/null; then log "MAX_PROMPT_BYTES='${MAX_PROMPT_BYTES}' invalid, non-positive, or above the ${ARG_SIZE_CEILING}-byte ceiling; clamping" MAX_PROMPT_BYTES="$ARG_SIZE_CEILING" @@ -253,13 +327,13 @@ STYLE_GUIDE="${STYLE_GUIDE:-.github/agy-review.md}" # repo-relative; loaded if LOG="${RUNNER_TEMP:-/tmp}/agy-review-${GITHUB_RUN_ID:-$$}.log" AGY_LOCK="${AGY_LOCK:-$HOME/.gemini/antigravity-cli/.agy-review.lock}" AGY_LOCK_WAIT="${AGY_LOCK_WAIT:-600}" # seconds to wait for the agy lock before proceeding -normalise_numeric_env AGY_LOCK_WAIT 600 # flock -w rejects a non-numeric value and aborts +normalize_numeric_env AGY_LOCK_WAIT 600 # flock -w rejects a non-numeric value and aborts AGY_RETRIES="${AGY_RETRIES:-3}" # attempts to get a usable agy response AGY_RETRY_DELAY="${AGY_RETRY_DELAY:-15}" # base backoff seconds between retries (grows per attempt) # Both reach (( )) arithmetic: `08` would abort on an octal parse and `0` retries would skip every # attempt and report "no review output after 0 attempt(s)". Same validation as the other numerics. -normalise_numeric_env AGY_RETRIES 3 -normalise_numeric_env AGY_RETRY_DELAY 15 +normalize_numeric_env AGY_RETRIES 3 +normalize_numeric_env AGY_RETRY_DELAY 15 [ "$AGY_RETRIES" -ge 1 ] || AGY_RETRIES=1 MARKER="" @@ -270,6 +344,10 @@ MARKER="" . "$(dirname -- "${BASH_SOURCE[0]}")/_agy_comment_body.sh" MAX_BODY_BYTES="${MAX_BODY_BYTES:-60000}" +# Reaches `$(( MAX_BODY_BYTES - 4096 ))`: `60k` or `060000` would abort the run there (agy review, +# GH-ListRollup PR #4). It must also leave room for that 4096-byte reserve. +normalize_numeric_env MAX_BODY_BYTES 60000 +[ "$MAX_BODY_BYTES" -gt 8192 ] || { log "MAX_BODY_BYTES=${MAX_BODY_BYTES} leaves no room for a review; using the default (60000)"; MAX_BODY_BYTES=60000; } # The jq program that finds THIS bot's existing review comment on the PR, so it can be edited # rather than replaced. Named, and exercised directly by `scripts/agy-review-selftest.sh`, @@ -290,7 +368,7 @@ MAX_BODY_BYTES="${MAX_BODY_BYTES:-60000}" # # Do not "fix" that in advance by dropping the login and matching on `.user.type == "Bot"` plus the # marker. Under a PAT the comment's type is `"User"`, not `"Bot"`, so that clause fails in the same -# scenario; and the marker is an HTML comment, so any bot that quotes or summarises a PR comment +# scenario; and the marker is an HTML comment, so any bot that quotes or summarizes a PR comment # carries it along, which would let this script PATCH over ANOTHER bot's comment. Losing a review # that way is worse than posting a duplicate. Change this filter when the auth changes, not before, # and match on whatever identity the new credential actually presents. @@ -305,6 +383,86 @@ readonly SELECT_OURS_JQ REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY not set}" +# The EXIT trap is installed HERE, before the first mktemp anywhere in the script (the first +# is in agy_has_write_access, called from the event dispatch below). Installed later, an abort +# during the permission lookup leaked its temp file, and the pre-declarations then reset +# _perm_err so cleanup() could never see it (agy review, GH-ListRollup PR #6). +# Remove every temp file on exit. Pre-declared so the trap is safe under `set -u` even if the +# script exits before a given file is created. +diff_file= diff_err= meta_file= prompt_file= out_file= raw= body_file= agy_diff_file= agy_sandbox= agy_jail_home= agy_jail_rt= agy_proxy_pid= jq_err= prior_body_file= archived_file= api_err= +# Also created mid-flight (permission lookup, compare-API merge base, archive trimming); a signal +# or abort while one of those commands runs would otherwise leak the file in /tmp. +_perm_err='' compare_err='' trimmed='' +# Set to 1 if agy printed its interactive OAuth login flow instead of a review (lapsed session); +# gates the no-post abort below. Pre-declared so `${auth_failed:-0}` is set-u-safe on every path. +auth_failed=0 +# Counts backend-error captures across attempts; see `service_error_present`. Pre-declared so +# `${service_errors:-0}` is set-u-safe even on paths that never enter the retry loop. +service_errors=0 +# Set when the large-diff fallback below creates refs/agy/* so the trap can remove them. +agy_refs_created= +# Set by the AGY_DRY_RUN block so cleanup KEEPS the two artifacts dry-run exists to expose. The +# whole point of dry run is "let me look at the assembled prompt", and the EXIT trap fires on the +# `exit 0` at the end of that block -- so it deleted the prompt on the way out, every time. +# Everything else is still removed; only these two are spared, and their paths are printed. +keep_artifacts= +cleanup() { + # Built as an argv ARRAY rather than as `rm -f ${v:+"$v"} ...`. + # + # The problem being solved is the EMPTY operand: `rm -f ""` is silent and exits 0 on GNU + # coreutils -- which is why an unconditional `rm -f "$unset_var"` never surfaced on the Linux + # runner -- but BSD/macOS `rm` writes "No such file or directory" to stderr for it. + # + # A note for the next reader, because this was raised in review and the intuition is wrong: + # `rm -f ${v:+"$v"}` does NOT word-split. Bash honors the quotes inside the `:+` alternate + # word, so a path with a space or a glob character survives as one operand. Verified: + # + # v='a*b'; rm -f ${v:+"$v"} -> + rm -f 'a*b' (siblings axxb, ayb untouched) + # v='a file'; rm -f ${v:+"$v"} -> one operand (siblings a, file untouched) + # + # The array is used anyway, for a reason the expansion form genuinely does not cover: it lets + # `--` terminate option parsing, so a temp path that begins with `-` is treated as a path + # rather than as flags. An array element is also one word by construction, which does not + # depend on knowing that `:+` quoting rule. + local keep_set="${keep_artifacts:-}" + local -a doomed=() + local f + # `${v:-}` on every name, even though all of them are pre-declared at the top of the script and + # cannot be unset here. Belt-and-braces on purpose: this is an EXIT trap, so if a future edit + # ever moves the trap above the pre-declarations, the failure would be an `unbound variable` + # abort DURING cleanup -- temp files left behind, and a confusing error masking the real exit + # cause. The pre-declaration stays and is still the actual guarantee; this is the cheap second + # line for a function that only ever runs while something else is going wrong. + for f in "${diff_file:-}" "${diff_err:-}" "${meta_file:-}" "${out_file:-}" "${raw:-}" "${body_file:-}" \ + "${jq_err:-}" "${prior_body_file:-}" "${archived_file:-}" "${api_err:-}" \ + "${_perm_err:-}" "${compare_err:-}" "${trimmed:-}"; do + [ -n "$f" ] && doomed+=("$f") + done + if [ -z "$keep_set" ]; then + for f in "${prompt_file:-}" "${agy_diff_file:-}"; do + [ -n "$f" ] && doomed+=("$f") + done + fi + [ ${#doomed[@]} -gt 0 ] && rm -f -- "${doomed[@]}" + # agy's private working directory (see `agy_sandbox` below). It is this run's own `mktemp -d`, + # outside the checkout, so removing it whole cannot touch anything else. Kept on dry run (it holds + # the handed-off diff that dry run exists to expose). + if [ -n "${agy_sandbox:-}" ] && [ -d "$agy_sandbox" ] \ + && { [ -z "$keep_set" ] || [ -z "${agy_diff_file:-}" ]; }; then + rm -rf -- "$agy_sandbox" # an inline dry run has nothing in it to keep + fi + [ -n "${agy_proxy_pid:-}" ] && kill "$agy_proxy_pid" 2>/dev/null + [ -n "${agy_jail_home:-}" ] && [ -d "$agy_jail_home" ] && rm -rf -- "$agy_jail_home" + [ -n "${agy_jail_rt:-}" ] && [ -d "$agy_jail_rt" ] && rm -rf -- "$agy_jail_rt" + if [ -n "${agy_refs_created:-}" ] && [ -n "${PR:-}" ]; then + # Hooks and fsmonitor disabled: these git calls run after agy, with the job token in the + # environment, so they must not execute anything a compromised checkout could have planted. + git -c core.hooksPath=/dev/null -c core.fsmonitor=false update-ref -d "refs/agy/pr-${PR}" 2>/dev/null || true + git -c core.hooksPath=/dev/null -c core.fsmonitor=false update-ref -d "refs/agy/base-${PR}" 2>/dev/null || true + fi +} +trap cleanup EXIT + # Does $1 actually hold write access to this repository? # # `author_association` is NOT a permission check, which is the trap this replaces. It is a @@ -314,7 +472,7 @@ REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY not set}" # person schedule execution here" has to be answered by the permissions API, not inferred # from a label that was never meant to answer it. # -# Fails CLOSED: any API error, missing token, or unrecognised role denies. A reviewer that +# Fails CLOSED: any API error, missing token, or unrecognized role denies. A reviewer that # stops running is a visible annoyance; one that runs for the wrong person is not. # # But fail-closed makes the error TEXT load-bearing, which is why stderr is captured and logged @@ -325,6 +483,9 @@ REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY not set}" # an outage wearing a decision's clothes, and it would sit undiagnosed until someone noticed # reviews had quietly stopped. agy_has_write_access() { + # `local` like the other helpers -- except _perm_err, which stays global ON PURPOSE: the EXIT + # trap's cleanup() must see it to remove the temp file if the run aborts mid-lookup. + local _login _login_enc _perm _login="${1:-}" [ -n "$_login" ] || { log "no login to check for write access"; return 1; } _perm_err="$(mktemp)" @@ -394,70 +555,6 @@ case "$PR" in esac log "reviewing ${REPO}#${PR}" -# Remove every temp file on exit. Pre-declared so the trap is safe under `set -u` even if the -# script exits before a given file is created. -diff_file= diff_err= meta_file= prompt_file= out_file= raw= body_file= agy_diff_file= agy_work_dir= jq_err= prior_body_file= archived_file= api_err= -# Set to 1 if agy printed its interactive OAuth login flow instead of a review (lapsed session); -# gates the no-post abort below. Pre-declared so `${auth_failed:-0}` is set-u-safe on every path. -auth_failed=0 -# Counts backend-error captures across attempts; see `service_error_present`. Pre-declared so -# `${service_errors:-0}` is set-u-safe even on paths that never enter the retry loop. -service_errors=0 -# Set when the large-diff fallback below creates refs/agy/* so the trap can remove them. -agy_refs_created= -# Set by the AGY_DRY_RUN block so cleanup KEEPS the two artefacts dry-run exists to expose. The -# whole point of dry run is "let me look at the assembled prompt", and the EXIT trap fires on the -# `exit 0` at the end of that block -- so it deleted the prompt on the way out, every time. -# Everything else is still removed; only these two are spared, and their paths are printed. -keep_artifacts= -cleanup() { - # Built as an argv ARRAY rather than as `rm -f ${v:+"$v"} ...`. - # - # The problem being solved is the EMPTY operand: `rm -f ""` is silent and exits 0 on GNU - # coreutils -- which is why an unconditional `rm -f "$unset_var"` never surfaced on the Linux - # runner -- but BSD/macOS `rm` writes "No such file or directory" to stderr for it. - # - # A note for the next reader, because this was raised in review and the intuition is wrong: - # `rm -f ${v:+"$v"}` does NOT word-split. Bash honours the quotes inside the `:+` alternate - # word, so a path with a space or a glob character survives as one operand. Verified: - # - # v='a*b'; rm -f ${v:+"$v"} -> + rm -f 'a*b' (siblings axxb, ayb untouched) - # v='a file'; rm -f ${v:+"$v"} -> one operand (siblings a, file untouched) - # - # The array is used anyway, for a reason the expansion form genuinely does not cover: it lets - # `--` terminate option parsing, so a temp path that begins with `-` is treated as a path - # rather than as flags. An array element is also one word by construction, which does not - # depend on knowing that `:+` quoting rule. - local keep_set="${keep_artifacts:-}" - local -a doomed=() - local f - # `${v:-}` on every name, even though all of them are pre-declared at the top of the script and - # cannot be unset here. Belt-and-braces on purpose: this is an EXIT trap, so if a future edit - # ever moves the trap above the pre-declarations, the failure would be an `unbound variable` - # abort DURING cleanup -- temp files left behind, and a confusing error masking the real exit - # cause. The pre-declaration stays and is still the actual guarantee; this is the cheap second - # line for a function that only ever runs while something else is going wrong. - for f in "${diff_file:-}" "${diff_err:-}" "${meta_file:-}" "${out_file:-}" "${raw:-}" "${body_file:-}" \ - "${jq_err:-}" "${prior_body_file:-}" "${archived_file:-}" "${api_err:-}"; do - [ -n "$f" ] && doomed+=("$f") - done - if [ -z "$keep_set" ]; then - for f in "${prompt_file:-}" "${agy_diff_file:-}"; do - [ -n "$f" ] && doomed+=("$f") - done - fi - [ ${#doomed[@]} -gt 0 ] && rm -f -- "${doomed[@]}" - # Remove the gitignored diff-handoff scratch dir once its file is gone. `rmdir` only unlinks an - # empty dir, so a concurrent run's file (a different $$) is never clobbered; a non-empty dir is - # gitignored and harmless if left behind. - [ -n "${agy_work_dir:-}" ] && [ -z "$keep_set" ] && rmdir "${agy_work_dir}" 2>/dev/null || true - if [ -n "${agy_refs_created:-}" ] && [ -n "${PR:-}" ]; then - git update-ref -d "refs/agy/pr-${PR}" 2>/dev/null || true - git update-ref -d "refs/agy/base-${PR}" 2>/dev/null || true - fi -} -trap cleanup EXIT - # --- fetch metadata first, because the fork gate + the large-diff fallback depend on it --- # FAIL-CLOSED. A `{}` fallback was harmless when the only field read was the title, # but is NOT harmless now that isCrossRepository gates whether an untrusted diff @@ -648,7 +745,7 @@ truncated="" # overlooked: the UTF-8 scrub further down (`iconv -c`, python3 fallback) removes any partial # sequence before the prompt reaches agy, so the split never escapes this file. # -# A line-aware cut would avoid creating the split, but cannot honour a byte ceiling — and the +# A line-aware cut would avoid creating the split, but cannot honor a byte ceiling — and the # ceiling is the actual constraint, since this bounds what is handed to a model with a hard context # limit. One minified-asset line in a diff can exceed the whole budget by itself, so "cut at a line # boundary" degenerates to either overshooting the cap or emitting nothing. Exact where the limit is @@ -706,9 +803,18 @@ agy_cap_round() { # output, otherwise keep the original. A failed mv is fatal under `set -e`; the function returns # 0 when no sanitizer succeeded, so a host with neither tool proceeds with the original bytes. agy_scrub_utf8() { - if command -v iconv >/dev/null 2>&1 \ - && iconv -c -f UTF-8 -t UTF-8 "$1" > "$1.utf8" 2>/dev/null && [ -s "$1.utf8" ]; then - mv "$1.utf8" "$1"; return + # iconv's exit status is NOT the success test. With -c, GNU iconv exits 1 precisely when it + # dropped invalid bytes -- after writing every valid byte -- so 0 and 1 both mean "usable + # output". Treating 1 as failure made python3 a silent hard requirement (it was the only path + # that ever succeeded on byte-cut input), although it is documented as a fallback. Any higher + # status, or empty output, still falls through to python3. + local iconv_rc + if command -v iconv >/dev/null 2>&1; then + iconv_rc=0 + iconv -c -f UTF-8 -t UTF-8 "$1" > "$1.utf8" 2>/dev/null || iconv_rc=$? + if [ "$iconv_rc" -le 1 ] && [ -s "$1.utf8" ]; then + mv "$1.utf8" "$1"; return + fi fi rm -f "$1.utf8" if command -v python3 >/dev/null 2>&1 \ @@ -720,6 +826,40 @@ agy_scrub_utf8() { } # <<< SELFTEST-EXTRACT +# >>> SELFTEST-EXTRACT: script capture filter +# Filter (stdin -> stdout) for the script(1) fallback capture. util-linux `script` writes a +# "Script started on ..." record as the first line of the typescript and a "Script done on ..." +# record as the last, and `-q` does NOT suppress them in the file (measured: util-linux 2.42.4; +# -q only silences the terminal messages). Left in, they make an EMPTY or failed agy run look +# like non-empty output, and they push a backend error off the first line where +# service_error_present looks for it -- so the retry loop could accept, and post, session +# metadata or a failure as a review. Only those two framing records are removed: the first line +# if it is a start record, and the last non-blank line if it is a done record. A review that +# merely mentions such text elsewhere is left intact. +# +# Locale-independent (agy review, GH-ListRollup PR #6): util-linux translates the "Script started +# on" / "Script done on" prose through gettext, but NOT the key=value fields it appends, so a +# record is recognized by `[COMMAND="` (start; we always run `script -c`) or a trailing +# `[COMMAND_EXIT_CODE="N"]` (done) as well as by the English prefix. Forcing LC_ALL=C on script +# was rejected: it would also change agy's own locale, and with it its UTF-8 handling. +agy_strip_script_records() { + awk ' + NR == 1 && (/^Script started on / || /\[COMMAND="/) { next } + { lines[++n] = $0 } + END { + last = n + while (last > 0 && lines[last] ~ /^[[:space:]]*$/) last-- + if (last > 0 && (lines[last] ~ /^Script done on / || lines[last] ~ /\[COMMAND_EXIT_CODE="[0-9]+"\][[:space:]]*$/)) { + last-- + while (last > 0 && lines[last] ~ /^[[:space:]]*$/) last-- + } else { + last = n + } + for (i = 1; i <= last; i++) print lines[i] + }' +} +# <<< SELFTEST-EXTRACT + diff_truncated= if agy_cut_file "$diff_file" "$MAX_DIFF_BYTES"; then diff_truncated=1 @@ -773,6 +913,23 @@ head_bytes="$(wc -c < "$prompt_file")" diff_bytes="$(wc -c < "$diff_file")" inline_budget=$(( MAX_PROMPT_BYTES - head_bytes - 512 )) # margin covers the diff header + file notice [ "$inline_budget" -lt 0 ] && inline_budget=0 # a huge STYLE_GUIDE can exceed it: file the diff +# agy's private working directory. agy runs under --dangerously-skip-permissions and ingests an +# untrusted diff (a prompt-injection surface), so it must never have the repository checkout in its +# workspace: a write to .git/hooks or .git/config there would later execute in a git command that +# holds the job token. agy is therefore started FROM this empty directory (its workspace root), +# the large-diff handoff file is written INTO it, and only it is passed to --add-dir. It lives in +# RUNNER_TEMP (outside the checkout, wiped between jobs) and the EXIT trap removes it. +agy_sandbox="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/agy-sandbox.XXXXXX")" +# Stored canonical: a relative RUNNER_TEMP/TMPDIR would otherwise put a relative path in the prompt +# (agy's file tool needs an absolute one) and make `--add-dir` resolve against the sandbox itself +# after the `cd "$agy_sandbox"` below. +agy_sandbox="$(cd "$agy_sandbox" && pwd -P)" +case "$agy_sandbox/" in + "$(pwd -P)"/*) + log "agy sandbox ${agy_sandbox} is inside the checkout; refusing to expose the repository to agy" + exit 1 ;; +esac + use_file=0 case "$AGY_DIFF_MODE" in file) use_file=1 ;; @@ -781,22 +938,12 @@ case "$AGY_DIFF_MODE" in esac if [ "$use_file" = "1" ]; then - # agy's CWD is the repo checkout, so a file written under it is readable by its file tool. Write it - # into a dedicated, gitignored scratch dir (`.agy-review-work/`, listed in .gitignore) rather than - # `.git/` (a sandbox may deny tool access to the hidden `.git` dir) or the repo root (an untracked - # `.patch` there pollutes `git status` if agy inspects repo state). Being gitignored, the dir never - # shows as working-tree pollution; the EXIT trap removes the file and the (now-empty) dir. - # - # The prompt hands agy an ABSOLUTE path, and the run below adds "$PWD" to agy's workspace via - # --add-dir. Both are load-bearing and were proven on the live runner: agy's sandboxed file tool - # does NOT resolve a relative path against the shell CWD (it uses its own workspace root), so a - # relative `.agy-review-work/...` comes back "does not exist on the filesystem" — the exact - # large-diff review failure this fixes. An absolute path resolves on its own, and --add-dir makes - # the checkout part of the sandbox workspace; using both is belt-and-suspenders. - agy_work_dir="$PWD/.agy-review-work" - mkdir -p "$agy_work_dir" - diff_name=".agy-review-work/agy-review-diff.$$.patch" - agy_diff_file="$PWD/$diff_name" + # The diff goes into agy's private sandbox directory (see `agy_sandbox` above), never into the + # checkout. The prompt hands agy an ABSOLUTE path, and the run below adds the sandbox (only) to + # agy's workspace via --add-dir. Both are load-bearing and were proven on the live runner: agy's + # sandboxed file tool does NOT resolve a relative path against the shell CWD (it uses its own + # workspace root), so a relative path comes back "does not exist on the filesystem". + agy_diff_file="$agy_sandbox/agy-review-diff.patch" cp "$diff_file" "$agy_diff_file" { printf '\n--- UNIFIED DIFF (in a file) ---\n' @@ -918,7 +1065,7 @@ scale_timeout_for_diff() { # against. Then the same guard the settings get, so a non-numeric value falls back rather than # becoming a syntax error in the expansion below. bytes="${bytes//[[:space:]]/}" - normalise_numeric_env bytes 0 + normalize_numeric_env bytes 0 [ -z "$AGY_PRINT_TIMEOUT_EXPLICIT" ] || { log "AGY_PRINT_TIMEOUT set explicitly ($AGY_PRINT_TIMEOUT); not scaling"; return 0; } # Computed from BYTES, not from truncated whole MiB: `mib = bytes / 1048576` in integer @@ -929,7 +1076,7 @@ scale_timeout_for_diff() { local base_s if ! base_s="$(duration_to_seconds "$AGY_PRINT_TIMEOUT")"; then - log "AGY_PRINT_TIMEOUT ('$AGY_PRINT_TIMEOUT') is not a recognised duration; leaving it alone" + log "AGY_PRINT_TIMEOUT ('$AGY_PRINT_TIMEOUT') is not a recognized duration; leaving it alone" return 0 fi @@ -947,17 +1094,100 @@ scale_timeout_for_diff "$diff_bytes" # stdout when stdout is not a TTY, e.g. piped/redirected/subprocess) --------- flags=( --print-timeout "$AGY_PRINT_TIMEOUT" --sandbox --dangerously-skip-permissions ) # In file-handoff mode agy must read the on-disk diff, and --sandbox otherwise confines its file -# tool to its own workspace root (NOT the shell CWD) — so add the checkout to the workspace. Only in -# file mode: an inline review reads nothing from disk, so it keeps zero filesystem access (narrower -# prompt-injection surface for the common path). Proven necessary on the live runner: without this -# (and the absolute path above) the large-diff handoff file reads back as "does not exist". -[ "${use_file:-0}" = "1" ] && flags+=( --add-dir "$PWD" ) - -# Strip the repo tokens from agy's own environment. agy runs under -# --dangerously-skip-permissions and ingests an untrusted diff (prompt-injection -# surface); `gh` and the large-diff fetch run in THIS script, before and after, and -# agy has no use for GH_TOKEN / GITHUB_TOKEN — so it should not inherit them. -agy_env=( env -u GH_TOKEN -u GITHUB_TOKEN ) +# tool to its own workspace root (NOT the shell CWD) — so add the sandbox directory that holds it. +# Never the checkout (see `agy_sandbox`). Proven necessary on the live runner: without this (and the +# absolute path above) the large-diff handoff file reads back as "does not exist". +[ "${use_file:-0}" = "1" ] && flags+=( --add-dir "$agy_sandbox" ) + +# agy gets an ALLOWLISTED environment (`env -i` plus the variables below), never the job's. +# agy runs under --dangerously-skip-permissions and ingests an untrusted diff (prompt-injection +# surface); `gh` and the large-diff fetch run in THIS script, before and after, and agy needs none +# of the job's credentials: not GH_TOKEN/GITHUB_TOKEN, not ACTIONS_RUNTIME_TOKEN (cache/artifact +# API), not ACTIONS_ID_TOKEN_* (OIDC), and not whatever a workflow puts in `env:` under an +# ordinary-looking name (a DATABASE_URL with a password in it, say), which a name-pattern denylist +# would miss. What agy does need is its user session: HOME for its config and conversation store, +# PATH, the locale, and XDG_RUNTIME_DIR + DBUS_SESSION_BUS_ADDRESS to reach the desktop keyring that +# holds its Google OAuth session. Verified on the runner host with no other agy running: agy +# authenticates and answers under exactly this environment. (An earlier test that "hung" had +# collided with a concurrent review: agy is one singleton per user, which is why the flock below +# exists.) AGY_ENV_PASSTHROUGH may name extra variables, space-separated, for a host that needs one. +agy_allowlisted_env_args() { + local name + local -a extra=() + # `read -a` splits on whitespace without pathname expansion, so a glob character in the + # passthrough list can never expand against the checkout. + # -d '' reads across newlines too, so a multi-line YAML block (`AGY_ENV_PASSTHROUGH: |`) keeps + # every entry; read returns 1 at end of input, which is expected. + IFS=$' \t\n' read -r -d '' -a extra <<<"${AGY_ENV_PASSTHROUGH:-}" || true + printf '%s\0' "-i" + for name in HOME PATH USER LOGNAME SHELL LANG LANGUAGE LC_ALL LC_CTYPE LC_MESSAGES TERM TMPDIR TZ \ + XDG_RUNTIME_DIR XDG_CONFIG_HOME XDG_DATA_HOME XDG_CACHE_HOME XDG_STATE_HOME \ + DBUS_SESSION_BUS_ADDRESS DISPLAY WAYLAND_DISPLAY XAUTHORITY "${extra[@]}"; do + # A valid identifier only: never an assignment, and never a leading digit (`1` would read the + # positional parameter $1, and `1FOO` aborts with "bad substitution"). + [[ "$name" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue + [ -n "${!name+x}" ] && printf '%s\0' "${name}=${!name}" + done + return 0 +} +agy_env=( env ) +while IFS= read -r -d '' arg; do agy_env+=( "$arg" ); done < <(agy_allowlisted_env_args) + +# --- the bubblewrap jail (AGY_ISOLATION=bwrap) -------------------------------------------------- +# Verified 2026-11-22: inside this jail agy authenticates and reviews, sees only an empty HOME, has +# no MCP servers/skills/hooks, cannot read any host file outside the jail, and over D-Bus can fetch +# only its own keyring item (another item's GetSecret, the bulk Service.GetSecrets and every other +# session service are AccessDenied by the proxy). +agy_jail=() +if [ "$AGY_ISOLATION" = bwrap ]; then + for _t in bwrap xdg-dbus-proxy gdbus; do + command -v "$_t" >/dev/null 2>&1 || { log "AGY_ISOLATION=bwrap needs '$_t' on the runner host; refusing to run agy unjailed (set AGY_ISOLATION=none to override, not recommended)"; exit 1; } + done + [ -n "${XDG_RUNTIME_DIR:-}" ] && [ -n "${DBUS_SESSION_BUS_ADDRESS:-}" ] \ + || { log "AGY_ISOLATION=bwrap needs XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS (a user session)"; exit 1; } + # agy's own keyring item(s), resolved OUTSIDE the jail: object paths only, never secrets. + _dict="" + for _kv in $AGY_KEYRING_ATTRS; do + [[ "$_kv" =~ ^[A-Za-z0-9_.-]+=[A-Za-z0-9_.:@-]+$ ]] || { log "invalid AGY_KEYRING_ATTRS entry '$_kv'"; exit 1; } + _dict="${_dict:+$_dict, }'${_kv%%=*}': '${_kv#*=}'" + done + mapfile -t _items < <(gdbus call --session --dest org.freedesktop.secrets \ + --object-path /org/freedesktop/secrets/aliases/default \ + --method org.freedesktop.Secret.Collection.SearchItems "{${_dict}}" 2>/dev/null \ + | grep -oE '/org/freedesktop/secrets/collection/[A-Za-z0-9_]+/[A-Za-z0-9_]+') + [ "${#_items[@]}" -ge 1 ] || { log "no keyring item matches AGY_KEYRING_ATTRS ($AGY_KEYRING_ATTRS); is agy logged in on this host?"; exit 1; } + _rules=( + "--call=org.freedesktop.secrets=org.freedesktop.Secret.Service.OpenSession@/org/freedesktop/secrets" + "--call=org.freedesktop.secrets=org.freedesktop.Secret.Service.Unlock@/org/freedesktop/secrets" + "--call=org.freedesktop.secrets=org.freedesktop.DBus.Properties.Get@/org/freedesktop/secrets" + "--call=org.freedesktop.secrets=org.freedesktop.Secret.Collection.SearchItems@/org/freedesktop/secrets/aliases/default" + "--call=org.freedesktop.secrets=org.freedesktop.Secret.Session.Close@/org/freedesktop/secrets/session/*" + ) + for _it in "${_items[@]}"; do _rules+=( "--call=org.freedesktop.secrets=org.freedesktop.Secret.Item.GetSecret@${_it}" ); done + agy_jail_rt="$(mktemp -d "$XDG_RUNTIME_DIR/agy-jail.XXXXXX")" + agy_jail_home="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/agy-home.XXXXXX")" + agy_jail_home="$(cd "$agy_jail_home" && pwd -P)" + xdg-dbus-proxy "$DBUS_SESSION_BUS_ADDRESS" "$agy_jail_rt/bus" --filter "${_rules[@]}" & + agy_proxy_pid=$! + for _ in $(seq 1 100); do [ -S "$agy_jail_rt/bus" ] && break; sleep 0.1; done + [ -S "$agy_jail_rt/bus" ] || { log "xdg-dbus-proxy did not start; refusing to run agy unjailed"; exit 1; } + _uid="$(id -u)" + agy_jail=( bwrap --unshare-all --share-net --die-with-parent --new-session + --ro-bind /usr /usr + --symlink usr/lib /lib --symlink usr/lib /lib64 --symlink usr/bin /bin --symlink usr/bin /sbin + --ro-bind /etc /etc --proc /proc --dev /dev --tmpfs /tmp + --ro-bind-try /run/systemd/resolve /run/systemd/resolve + --tmpfs /home --bind "$agy_jail_home" "$HOME" + --ro-bind "$(readlink -f "$AGY_BIN")" "$AGY_BIN" + --ro-bind "$(cd "$(dirname "$0")" && pwd)/_agy_print.sh" "$(cd "$(dirname "$0")" && pwd)/_agy_print.sh" + --ro-bind "$prompt_file" "$prompt_file" + --bind "$agy_sandbox" "$agy_sandbox" --chdir "$agy_sandbox" + --dir "/run/user/$_uid" --ro-bind "$agy_jail_rt/bus" "/run/user/$_uid/bus" ) + # Inside the jail, D-Bus is the filtered proxy (later env assignments override earlier ones). + agy_env+=( "XDG_RUNTIME_DIR=/run/user/$_uid" "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$_uid/bus" ) + log "agy isolation: bwrap jail, empty HOME, D-Bus limited to ${#_items[@]} keyring item(s)" + unset _t _dict _kv _items _rules _it _uid +fi [ -n "$AGY_MODEL" ] && flags+=( --model "$AGY_MODEL" ) [ -n "$AGY_EFFORT" ] && flags+=( --effort "$AGY_EFFORT" ) @@ -1001,7 +1231,11 @@ for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do if command -v unbuffer >/dev/null 2>&1; then log "running agy via unbuffer (allocates a PTY) [attempt ${attempt}/${AGY_RETRIES}]" - "${agy_env[@]}" unbuffer "$AGY_BIN" "${flags[@]}" --print "$(cat "$prompt_file")" > "$out_file" 2>>"$LOG" || true + # From the sandbox directory, so agy's workspace root is never the checkout. + # `env -i ...` starts unbuffer itself inside the allowlisted environment (verified to work in + # the runner's environment). Putting it the other way round made every NAME=VALUE an argv + # entry of the long-lived unbuffer process, world-readable in /proc//cmdline. + ( cd "$agy_sandbox" && "${agy_env[@]}" unbuffer "${agy_jail[@]}" "$AGY_BIN" "${flags[@]}" --print "$(cat "$prompt_file")" ) > "$out_file" 2>>"$LOG" || true else log "unbuffer not found; falling back to script(1) [attempt ${attempt}/${AGY_RETRIES}]" raw="$(mktemp)" @@ -1010,9 +1244,13 @@ for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do # (AGY_MODEL / AGY_EFFORT / AGY_PRINT_TIMEOUT) -- is shell-escaped for the inner shell. # A raw `${flags[*]}` here would let a shell metacharacter in any of those be evaluated # by `sh -c` (command injection); `%q` quotes each token exactly. - cmd="$(printf '%q ' "$here/_agy_print.sh" "$prompt_file" "${flags[@]}")" - "${agy_env[@]}" AGY_BIN="$AGY_BIN" script -qfec "$cmd" "$raw" >/dev/null 2>>"$LOG" || true - col -b < "$raw" > "$out_file" + # script(1) is a plain binary, so it (and the _agy_print.sh it runs) can start inside the + # allowlisted environment; agy inherits it from there. + cmd="$(printf '%q ' "${agy_jail[@]}" "$here/_agy_print.sh" "$prompt_file" "${flags[@]}")" + ( cd "$agy_sandbox" && "${agy_env[@]}" AGY_BIN="$AGY_BIN" script -qfec "$cmd" "$raw" ) >/dev/null 2>>"$LOG" || true + # Strip script(1)'s own start/done records so they cannot pass as agy output (see + # agy_strip_script_records). + col -b < "$raw" | agy_strip_script_records > "$out_file" rm -f "$raw" # each retry makes a fresh $raw; the EXIT trap only holds the last one fi @@ -1133,6 +1371,12 @@ body_file="$(mktemp)" printf '%s' "$truncated" printf '\n\nAutomated first-pass review by `agy` on a self-hosted runner -- not a human review.\n' } > "$body_file" +# Fail closed before ANY post path (edit-in-place or new comment) if agy's output carries a +# credential shape; see credential_kind_present. +if cred_kind="$(credential_kind_present "$out_file")"; then + log "refusing to post: agy's output contains a credential-shaped string (${cred_kind}). Nothing was posted. Inspect the runner host; the diff may carry a prompt injection." + exit 1 +fi # Final hard guard — the last line of defense, and UNCONDITIONAL, run BEFORE anything is # deleted or posted. Layer 1 (the retry loop) already rejects a lapsed-session capture, but @@ -1199,6 +1443,9 @@ if [ -n "$prior_id" ] && [ -s "$prior_body_file" ]; then # metacharacters, backslashes and HTML. prior_head="$(agy_body_head "$MARKER" < "$prior_body_file")" prior_archive="$(agy_body_archive < "$prior_body_file")" + # Rounds earlier runs already dropped: carried forward so the disclosure is cumulative and a + # later run that drops nothing does not erase it (agy review of Rusty2600 #53). + prior_dropped="$(agy_body_dropped_count < "$prior_body_file")" archived_file="$(mktemp)" agy_assemble_archive "$prior_head" "$prior_archive" "$(date -u +'%Y-%m-%d %H:%M UTC')" \ @@ -1223,14 +1470,24 @@ if [ -n "$prior_id" ] && [ -s "$prior_body_file" ]; then # start/end sentinels, so `agy_body_archive` extracts only the rounds themselves. With # the wrapper inside, every run re-captured it and nested another layer around it. printf '\n%s\n' "$AGY_ARCHIVE_SECTION" - if [ "$dropped" -gt 0 ]; then - printf '%d earlier round(s) dropped to stay under GitHub'"'"'s comment size limit.\n\n' "$dropped" + total_dropped=$(( dropped + prior_dropped )) + if [ "$total_dropped" -gt 0 ]; then + printf '%d earlier round(s) dropped to stay under GitHub'"'"'s comment size limit.\n\n' "$total_dropped" + fi + # The sentinels are always written (later runs locate the archive and its dropped count by + # them), but the visible `
` wrapper only when a round survived the trimming above -- + # otherwise it renders as an empty disclosure (agy review, GH-ListRollup PR #4). + # `if`, not `[ -s ] && printf`: as the group's last command, a false `&&` list would make the + # whole `{ } >> "$body_file"` group return 1 and abort the run under `set -e`. + if [ -s "$archived_file" ]; then + printf '
\nEarlier review rounds (newest first)\n\n' fi - printf '
\nEarlier review rounds (newest first)\n\n' printf '%s\n' "$AGY_ARCHIVE_START" cat "$archived_file" printf '%s\n' "$AGY_ARCHIVE_END" - printf '\n
\n' + if [ -s "$archived_file" ]; then + printf '\n
\n' + fi } >> "$body_file" rm -f "$archived_file" From 093b46d753cb0ba072a3abba3b452a2afb79bf07 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 15:44:05 -0500 Subject: [PATCH 02/14] ci: re-sync the reviewer to template fd64ab3 (egress filter, round 4-5) Re-syncs the vendored Antigravity reviewer scripts and .github/AGY-REVIEWER.md byte for byte from the antigravity-pr-review template at fd64ab3. Local workflow overrides are unchanged. New: the jail has no network of its own (AGY_EGRESS=filtered) - agy must be able to read its own Google login token, so the network was the remaining way to leak it. The jail now has only its own loopback. Its single route out is an allowlisting HTTPS CONNECT proxy outside the jail, reached through a bind-mounted Unix socket. - Exact host names only. `.googleapis.com` would include Cloud Storage, where anyone can own a writable bucket. - www.googleapis.com also serves the Cloud Storage API. That host is TLS-intercepted with a per-run CA whose key never enters the jail, and only a body-less GET /oauth2/v2/userinfo is forwarded, rebuilt by the proxy with its own Host header. Forwarding the client's Host would allow fronting to any Google service. - Verified from inside the jail. Refused: Cloud Storage upload and read (including path-traversal, encoded, HTTP/2, Host-fronting and smuggling variants), other hosts and ports, direct connections, raw TCP and DNS. A full review completes. - The job log prints egress verdict counts only. Denied host names go to a mode-600 log on the runner host, for diagnosing an agy update that needs a new host. Fixes from review round 4 on these re-sync PRs: - A jail that fails to start is no longer accepted as review output (Codex). - cleanup survives an already-exited proxy under set -e (Cursor). - Each capture is credential-scanned before any handler logs it (CodeRabbit). The public stderr tail is withheld if it carries a credential shape (Cursor). - An empty AGY_KEYRING_ATTRS (SearchItems {} matches every item) is refused (Cursor). - TMPDIR=/tmp inside the jail (Cursor). Top-level lib/bin links mirror the host layout, for Debian and Ubuntu (Codex). Verification: agy-review-selftest.sh all checks passed (now including offline TLS tests of the egress proxy); actionlint clean; gitleaks no leaks. Co-Authored-By: Claude Opus 5.5 --- .github/AGY-REVIEWER.md | 37 ++- scripts/agy-review-selftest.sh | 151 +++++++++++++ scripts/agy-review.sh | 397 +++++++++++++++++++++++++++++++-- 3 files changed, 571 insertions(+), 14 deletions(-) diff --git a/.github/AGY-REVIEWER.md b/.github/AGY-REVIEWER.md index 77373cd7..f3f5e715 100644 --- a/.github/AGY-REVIEWER.md +++ b/.github/AGY-REVIEWER.md @@ -79,8 +79,9 @@ agy -p "reply with the single word: ok" # should print: ok # Tools the reviewer uses (all already present here): # gh jq sqlite3 col script + unbuffer (from `expect`) # bwrap xdg-dbus-proxy gdbus (the agy jail; AGY_ISOLATION=bwrap, the default) +# socat python3 openssl (the jail's egress filter; AGY_EGRESS=filtered, the default) # iconv (glibc) for UTF-8 scrubbing; python3 is an optional fallback used only without iconv -pacman -Q github-cli jq sqlite expect util-linux bubblewrap xdg-dbus-proxy glib2 >/dev/null # verify; install any missing with paru/pacman +pacman -Q github-cli jq sqlite expect util-linux bubblewrap xdg-dbus-proxy glib2 socat python openssl >/dev/null # verify; install any missing with paru/pacman ``` `unbuffer` is preferred. Without it, the reviewer falls back to `script(1)` and strips the @@ -264,6 +265,36 @@ yours to accept: keyring item (the `gh` token), the bulk `GetSecrets` call or any other session service is `AccessDenied`. A host without `bwrap`, `xdg-dbus-proxy` or `gdbus` fails closed. `AGY_ISOLATION=none` opts out, which is not recommended. +- **The jail has no network of its own (`AGY_EGRESS=filtered`, the default):** agy + must be able to read its own Google login token, so the network is the remaining + way to leak it. The jail gets only its own loopback. Its single route out is an + HTTPS `CONNECT` proxy outside the jail, reached through a bind-mounted Unix socket, + which tunnels only to port 443 of hosts that **exactly** match `AGY_EGRESS_ALLOW`. + Wildcards are rejected, because `.googleapis.com` would include Cloud Storage, + where anyone can own a writable bucket. One host needs more than that: + `www.googleapis.com` serves both the userinfo call agy makes at startup and the + Cloud Storage JSON API. So the proxy terminates TLS for that host only, with a + per-run CA whose private key never enters the jail, and forwards only a body-less + `GET /oauth2/v2/userinfo` (exact path, no query), which it rebuilds itself. It + sets its own `Host` header, because Google's front end routes by `Host` and a + forwarded one could front to Cloud Storage. It also copies only a short header + allowlist, and refuses bare CR or LF, control bytes, obs-fold and duplicate or + foreign `Host` headers. Verified from inside the jail: Cloud Storage uploads and + reads through `www.googleapis.com` (including path-traversal, encoded-path and + HTTP/2 variants), `storage.googleapis.com`, any other host or port, direct + connections, raw TCP and DNS are all refused, while a full review completes. + The job log reports egress verdict **counts** only, because a denied host name or + path is attacker-chosen and could itself carry a secret into a public log. + Residual risk: the allowed Gemini backends and the token endpoint can still be + reached, but data sent there goes to Google under the reviewer's own account, not + to an attacker. + **If reviews start failing after an agy update**, the new version probably needs + a host that is not on the list. The job log shows the egress counts. Denied host + names never appear there; they go to + `~/.gemini/antigravity-cli/agy-egress-denied.log` on the runner host (mode 600, + beside agy's own state). Add a needed host to `AGY_EGRESS_ALLOW`, which takes + exact names only. If the host also serves storage or another API, path-filter it + through `AGY_EGRESS_INTERCEPT_HOST` and `AGY_EGRESS_INTERCEPT_PATH` instead. - **agy never sees the checkout:** agy runs with `--dangerously-skip-permissions` and reads an untrusted diff, so a prompt injection could try to write files. It is started from a private, empty `mktemp -d` sandbox under `$RUNNER_TEMP` @@ -309,6 +340,10 @@ runner, so disable fork workflows there or gate them the same way. | `MAX_PROMPT_BYTES` | `120000` | the inline/file threshold in `auto` mode, and a hard backstop on the **inlined** prompt. agy takes an inlined prompt as a `--print` argv value, and a single `execve` argument cannot exceed `MAX_ARG_STRLEN` (128 KiB); over it `execve` fails with E2BIG before agy starts. Clamped below 128 KiB | | `STYLE_GUIDE` | `.github/agy-review.md` | repo-relative style guide, loaded if present | | `AGY_ISOLATION` | `bwrap` | `bwrap` runs agy in the jail described under the security model; `none` runs it unjailed (not recommended) | +| `AGY_EGRESS` | `filtered` | `filtered` gives the jail no network except the allowlisting proxy; `open` keeps the host network (not recommended) | +| `AGY_EGRESS_ALLOW` | the 4 hosts agy needs | space-separated EXACT host names the proxy will tunnel to on port 443; wildcards and suffixes are rejected | +| `AGY_EGRESS_INTERCEPT_HOST` / `_PATH` | `www.googleapis.com` / `/oauth2/v2/userinfo` | the one host whose TLS is terminated so that only body-less GETs fully matching the path regex are forwarded | +| `AGY_EGRESS_DENIED_LOG` | `~/.gemini/antigravity-cli/agy-egress-denied.log` | host-private (mode 600) log of denied egress host names, for diagnosing an agy update; never printed to the job log | | `AGY_KEYRING_ATTRS` | `username=antigravity service=gemini` | Secret Service attributes of agy's own login item; the jail's D-Bus proxy allows `GetSecret` on the matching item(s) only | | `AGY_ENV_PASSTHROUGH` | *(empty)* | extra environment variable NAMES (space-separated) to pass to agy on top of the session allowlist; everything else is withheld | diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index 9cc3deab..004cf341 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -783,6 +783,157 @@ check "a missing bwrap/xdg-dbus-proxy/gdbus fails closed" "1" \ "$(grep -c "refusing to run agy unjailed (set AGY_ISOLATION=none" "$SCRIPT")" check "the proxy runs with --filter (deny by default)" "1" \ "$(grep -c 'xdg-dbus-proxy "\$DBUS_SESSION_BUS_ADDRESS" "\$agy_jail_rt/bus" --filter' "$SCRIPT")" +# Egress filtering (AGY_EGRESS=filtered): without it a prompt-injected diff could make agy send its +# own Google login token anywhere. Static shape first, then the embedded proxy exercised offline. +check "egress defaults to filtered" "1" \ + "$(grep -c '^AGY_EGRESS="\${AGY_EGRESS:-filtered}"' "$SCRIPT")" +check "the filtered jail drops --share-net (only its own loopback)" "1" \ + "$(grep -c '^ _net=() # --unshare-all without --share-net' "$SCRIPT")" +check "the default allowlist has no wildcard or suffix entry" "0" \ + "$(grep '^AGY_EGRESS_ALLOW=' "$SCRIPT" | grep -cE '[*]|[ "-]\.')" +check "storage.googleapis.com is never allowlisted" "0" \ + "$(grep '^AGY_EGRESS_ALLOW=' "$SCRIPT" | grep -c 'storage\.googleapis\.com')" +check "allowlist entries are validated as exact host names" "1" \ + "$(grep -c 'exact lowercase host names only, no wildcards' "$SCRIPT")" +check "the CA and leaf keys are never bound into the jail" "0" \ + "$(grep -E -- '--(ro-)?bind[^)]*(pki|ca\.key|leaf\.key)' "$SCRIPT" | grep -vc '^ *#')" +check "egress needs socat/python3/openssl or fails closed" "1" \ + "$(grep -c '\[ "\$AGY_EGRESS" = filtered \] && _need+=( socat python3 openssl )' "$SCRIPT")" +check "the job log prints egress verdict counts, never names" "1" \ + "$(grep -c "awk '{print \$1}' \"\$agy_jail_rt/egress.log\"" "$SCRIPT")" +proxy_py="$TMPD/egress.py" +sed -n "/^ cat <<'AGYPY'$/,/^AGYPY$/p" "$SCRIPT" | sed '1d;$d' > "$proxy_py" +check "the embedded egress proxy compiles" "0" \ + "$(python3 -I -m py_compile "$proxy_py" >/dev/null 2>&1; echo $?)" +if command -v python3 >/dev/null 2>&1 && command -v curl >/dev/null 2>&1; then + # Unix socket paths are capped at 108 bytes, so the sockets live in a short dir, not under TMPD. + sockd="$(mktemp -d "${XDG_RUNTIME_DIR:-/tmp}/agyst.XXXXXX")" + px_sock="$sockd/e.sock"; px_log="$TMPD/egress.log"; : > "$px_log" + python3 -I "$proxy_py" "$px_sock" "$px_log" "allowed.example" & + px_pid=$! + for _ in $(seq 1 50); do [ -S "$px_sock" ] && break; sleep 0.1; done + px() { curl -s -m 5 -o /dev/null -w '%{http_code}' --unix-socket "$px_sock" -X CONNECT \ + --request-target "$1" "http://proxy/" 2>/dev/null; } + check "proxy refuses an unlisted host" "403" "$(px 'secret-token-in-name.evil.example:443')" + check "proxy refuses a suffix of an allowed host" "403" "$(px 'x.allowed.example:443')" + check "proxy refuses an allowed host on another port" "403" "$(px 'allowed.example:80')" + check "proxy refuses plain-HTTP proxying" "405" \ + "$(curl -s -m 5 -o /dev/null -w '%{http_code}' --unix-socket "$px_sock" http://allowed.example/ 2>/dev/null)" + kill "$px_pid" 2>/dev/null; wait "$px_pid" 2>/dev/null || true # 143 from the kill is expected + check "proxy never logs a denied host name" "0" "$(grep -c 'evil' "$px_log")" + check "proxy logged all three denials" "3" "$(grep -c '^DENY' "$px_log")" + check "a denial names only an allowlisted host, if any" "0" \ + "$(grep '^DENY ' "$px_log" | grep -vcx 'DENY allowed.example')" +fi +# A jail launch diagnostic is never accepted as a review (Codex P2), and cleanup survives a dead proxy. +jf="$TMPD/jail-fail.txt" +printf '\n\nbwrap: Can'"'"'t find source path /x: No such file or directory\n' > "$jf" +check "a bwrap launch diagnostic is recognized as a jail failure" "yes" "$(agy_jail_failed "$jf" && echo yes || echo no)" +printf 'agy-jail: line 1: socat: command not found\n' > "$jf" +check "an in-jail wrapper diagnostic is recognized as a jail failure" "yes" "$(agy_jail_failed "$jf" && echo yes || echo no)" +printf '## Review\n\nThe bwrap: prefix appears only mid-review here.\nbwrap: not first\n' > "$jf" +check "a review that merely mentions bwrap is not a jail failure" "no" "$(agy_jail_failed "$jf" && echo yes || echo no)" +check "the capture loop refuses a jail failure before any retry or post" "1" \ + "$(grep -c '^ if agy_jail_failed "\$out_file"; then' "$SCRIPT")" +check "cleanup ignores a failed kill of either proxy (set -e safe)" "2" \ + "$(grep -cE '^ \[ -n "\$\{agy_(proxy|egress)_pid:-\}" \] && \{ kill "\$agy_(proxy|egress)_pid" 2>/dev/null \|\| true; \}$' "$SCRIPT")" +# Round-4 review fixes. +cred_line="$(grep -n '^ if cred_kind="\$(credential_kind_present "\$out_file")"; then' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +svc_line="$(grep -n '^ if service_error_present "\$out_file"; then' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +check "each capture is credential-scanned before any handler logs it" "yes" \ + "$([ -n "$cred_line" ] && [ -n "$svc_line" ] && [ "$cred_line" -lt "$svc_line" ] && echo yes || echo no)" +check "the public stderr tail is scanned from a regular file and withheld on a match" "1" \ + "$(grep -c '^ if log_cred="\$(credential_kind_present "\$log_tail")"; then' "$SCRIPT")" +check "an empty AGY_KEYRING_ATTRS is refused (SearchItems {} matches every item)" "1" \ + "$(grep -c 'AGY_KEYRING_ATTRS is empty; refusing to grant agy keyring access' "$SCRIPT")" +check "agy gets TMPDIR=/tmp inside the jail" "1" "$(grep -c '"TMPDIR=/tmp"' "$SCRIPT")" +check "top-level dirs mirror the host layout (no hard-coded lib64 link)" "0" \ + "$(grep -c -- '--symlink usr/lib /lib64' "$SCRIPT")" +check "denied egress names go to a host-private log, never the job log" "1" \ + "$(grep -c 'AGY_EGRESS_DENIED_LOG:-\$HOME/.gemini/antigravity-cli/agy-egress-denied.log' "$SCRIPT")" +lt="$TMPD/log-tail.txt"; printf 'boom\nghp_%s\n' "$(printf 'k%.0s' {1..36})" > "$lt" +check "a credential in agy stderr is detected from a file" "yes" \ + "$(credential_kind_present "$lt" >/dev/null && echo yes || echo no)" +# The host-private denied-host log: created on the FIRST run (no prior file), mode 600, appended +# on later runs, and bounded. +dsrc="$TMPD/denied.txt"; ddst="$TMPD/sub/agy-egress-denied.log"; mkdir -p "$TMPD/sub" +printf 'new-host.example:443\nnew-host.example:443\nother.example:443\n' > "$dsrc" +agy_record_denied "$dsrc" "$ddst" "o/r#1" +check "denied-host log is created on the first run" "2" "$(wc -l < "$ddst" 2>/dev/null || echo 0)" +check "denied-host log is mode 600" "600" "$(stat -c %a "$ddst" 2>/dev/null || echo none)" +agy_record_denied "$dsrc" "$ddst" "o/r#2" +check "denied-host log appends on a later run" "4" "$(wc -l < "$ddst" 2>/dev/null || echo 0)" +for _ in $(seq 1 300); do agy_record_denied "$dsrc" "$ddst" "o/r#n"; done +check "denied-host log stays bounded" "yes" "$([ "$(wc -l < "$ddst")" -le 500 ] && echo yes || echo no)" +# The intercepted host: the proxy must REBUILD the request (round 5, commit security review). +# Every case below is refused before any upstream connection, so this runs offline over real TLS. +if command -v python3 >/dev/null 2>&1 && command -v openssl >/dev/null 2>&1; then + ip="$TMPD/icpt"; mkdir -p "$ip" + if { openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 1 \ + -subj "/CN=selftest CA" -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,keyCertSign" -keyout "$ip/ca.key" -out "$ip/ca.pem" \ + && openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=allowed.example" \ + -keyout "$ip/leaf.key" -out "$ip/leaf.csr" \ + && openssl x509 -req -in "$ip/leaf.csr" -CA "$ip/ca.pem" -CAkey "$ip/ca.key" -days 1 \ + -extfile <(printf 'subjectAltName=DNS:allowed.example\nextendedKeyUsage=serverAuth\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n') \ + -out "$ip/leaf.pem"; } >/dev/null 2>&1; then + python3 -I "$proxy_py" "$sockd/i.sock" "$ip/log" "allowed.example" \ + "allowed.example" "/oauth2/v2/userinfo" "$ip/leaf.pem" "$ip/leaf.key" & + ip_pid=$! + for _ in $(seq 1 50); do [ -S "$sockd/i.sock" ] && break; sleep 0.1; done + cat > "$ip/client.py" <<'PYC' +import socket, ssl, sys +sock_path, ca, head = sys.argv[1], sys.argv[2], sys.argv[3].encode("latin-1").decode("unicode_escape").encode("latin-1") +s = socket.socket(socket.AF_UNIX); s.settimeout(10); s.connect(sock_path) +s.sendall(b"CONNECT allowed.example:443 HTTP/1.1\r\nHost: allowed.example:443\r\n\r\n") +if b" 200 " not in s.recv(4096): + print("no-tunnel"); sys.exit() +ctx = ssl.create_default_context(cafile=ca) +t = ctx.wrap_socket(s, server_hostname="allowed.example") +t.sendall(head) +try: + print(t.recv(4096).split(b"\r\n", 1)[0].split(b" ")[1].decode()) +except (OSError, IndexError): + print("closed") +PYC + ic() { python3 -I "$ip/client.py" "$sockd/i.sock" "$ip/ca.pem" "$1" 2>/dev/null || echo error; } + H='Host: allowed.example\r\n' + check "intercept refuses a foreign Host (fronting to another Google service)" "403" \ + "$(ic 'GET /oauth2/v2/userinfo HTTP/1.1\r\nHost: bucket.storage.googleapis.com\r\n\r\n')" + check "intercept refuses a duplicate Host" "403" \ + "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}Host: evil.example\\r\\n\\r\\n")" + check "intercept refuses a missing Host" "403" "$(ic 'GET /oauth2/v2/userinfo HTTP/1.1\r\n\r\n')" + check "intercept refuses a query string (a data channel)" "403" \ + "$(ic "GET /oauth2/v2/userinfo?x=secret HTTP/1.1\\r\\n${H}\\r\\n")" + check "intercept refuses another path" "403" "$(ic "GET /storage/v1/b/x HTTP/1.1\\r\\n${H}\\r\\n")" + check "intercept refuses an absolute-form target" "403" \ + "$(ic "GET https://storage.googleapis.com/oauth2/v2/userinfo HTTP/1.1\\r\\n${H}\\r\\n")" + check "intercept refuses a bare LF inside the head (smuggling)" "403" \ + "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}X-A: 1\\nHost: evil.example\\r\\n\\r\\n")" + check "intercept refuses obs-fold" "403" "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}X-A: 1\\r\\n folded\\r\\n\\r\\n")" + check "intercept refuses a control byte" "403" "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}X-A: a\\x01b\\r\\n\\r\\n")" + check "intercept refuses a request body" "403" \ + "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}Content-Length: 5\\r\\n\\r\\n")" + check "intercept refuses a non-GET method" "403" "$(ic "POST /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}\\r\\n")" + kill "$ip_pid" 2>/dev/null; wait "$ip_pid" 2>/dev/null || true # 143 from the kill is expected + fi +fi +[ -n "${sockd:-}" ] && rm -rf -- "$sockd" +# rebuild_request, unit level: the upstream head is built by the proxy, never copied. +rb="$(python3 -I - "$proxy_py" <<'PYR' 2>/dev/null +import importlib.util, sys +src = open(sys.argv[1]).read().split("\nasyncio.run(main())", 1)[0] +ns = {"__name__": "agy_egress_test"} +sys.argv = ["x", "/dev/null", "/dev/null", "", "www.googleapis.com", "/oauth2/v2/userinfo", "", ""] +code = src.replace(' server_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n server_ctx.load_cert_chain(sys.argv[6], sys.argv[7])\n', ' server_ctx = None\n') +exec(compile(code.replace(" server_ctx.set_alpn_protocols", " pass #"), "proxy", "exec"), ns) +head = b"GET /oauth2/v2/userinfo HTTP/1.1\r\nHost: www.googleapis.com\r\nAuthorization: Bearer t\r\nX-Exfil: data\r\nUser-Agent: agy\r\n\r\n" +out = ns["rebuild_request"](head, "www.googleapis.com").decode() +print("|".join(out.split("\r\n"))) +PYR +)" || rb="(rebuild_request missing or failed)" +check "the rebuilt request sets Host itself and drops unlisted headers" \ + "GET /oauth2/v2/userinfo HTTP/1.1|Host: www.googleapis.com|Authorization: Bearer t|User-Agent: agy|Connection: close||" "$rb" # Credential scan: every shape is caught, ordinary review text is not. cred_tmp="$TMPD/cred.txt" # Samples are assembled at runtime from split pieces, so this file never contains a literal that a diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index bd17b4ac..75a20084 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -152,6 +152,29 @@ OAUTH_URL_RE='https?://accounts\.google\.com/o/oauth2' # lapse is detected AND a leak is blocked by the same unconditional check. oauth_url_present() { [ -s "$1" ] && grep -qiE "$OAUTH_URL_RE" "$1"; } +# Append this run's denied egress targets (deduplicated, tagged, bounded to the newest 500 lines) +# to a host-private log created mode 600. Never called with a public destination. +agy_record_denied() { + local src="$1" dst="$2" tag="$3" stamp + [ -s "$src" ] || return 0 + stamp="$(date -u +%FT%TZ)" + ( + umask 077 + { + if [ -f "$dst" ]; then tail -n 400 "$dst"; fi + sort -u "$src" | cut -c1-253 | sed "s|^|${stamp} ${tag} |" + } > "$dst.new" || exit 1 + tail -n 500 "$dst.new" > "$dst.tmp" && mv -f "$dst.tmp" "$dst" && rm -f -- "$dst.new" + ) +} + +# True when the captured output is a jail launch diagnostic rather than agy's: its first +# non-blank line comes from bwrap itself or from the in-jail wrapper (argv0 `agy-jail`). +agy_jail_failed() { + [ -s "$1" ] || return 1 + grep -m1 -v '^[[:space:]]*$' "$1" | grep -qE '^(bwrap|agy-jail): ' +} + # Credential shapes that must never reach a public PR comment. Every pattern is anchored on a # leading non-identifier boundary, so an ordinary identifier (`task-...`, `disk-...`, a word ending # in `ghp`) cannot match and wrongly block a review. agy's --sandbox does NOT confine @@ -276,6 +299,25 @@ AGY_ISOLATION="${AGY_ISOLATION:-bwrap}" case "$AGY_ISOLATION" in bwrap|none) ;; *) echo "AGY_ISOLATION must be bwrap or none, got '$AGY_ISOLATION'" >&2; exit 1 ;; esac # Attributes agy uses to look up its keyring item (observed on the Secret Service bus). AGY_KEYRING_ATTRS="${AGY_KEYRING_ATTRS:-username=antigravity service=gemini}" +# Network egress from the jail. `filtered` (default) gives the jail NO network namespace access: +# its only route out is an allowlisting HTTPS CONNECT proxy outside the jail, reached through a +# bind-mounted Unix socket. Without this, a prompt-injected diff could make agy read its own +# Google login token (which it must be able to read) and send it anywhere. `open` keeps the host +# network (not recommended). Hosts are EXACT names, never wildcards: `.googleapis.com` would +# include Cloud Storage, where anyone can own a writable bucket. +AGY_EGRESS="${AGY_EGRESS:-filtered}" +case "$AGY_EGRESS" in filtered|open) ;; *) echo "AGY_EGRESS must be filtered or open, got '$AGY_EGRESS'" >&2; exit 1 ;; esac +# Observed 2026-11-22: the Gemini backends, the OAuth token endpoint, and www.googleapis.com for the +# userinfo eligibility check. Telemetry, the avatar host and the auto-updater are left out (agy +# works without them). +AGY_EGRESS_ALLOW="${AGY_EGRESS_ALLOW:-daily-cloudcode-pa.googleapis.com aicode.googleapis.com oauth2.googleapis.com www.googleapis.com}" +# www.googleapis.com ALSO serves the Cloud Storage JSON API (verified: an upload to a nonexistent +# bucket there answers "The specified bucket does not exist"), so that host is TLS-intercepted and +# only this path is forwarded, as a body-less GET that the proxy REBUILDS (its own Host header, a +# short header allowlist): forwarding the client's Host would let it front to any Google service. +AGY_EGRESS_INTERCEPT_HOST="${AGY_EGRESS_INTERCEPT_HOST:-www.googleapis.com}" +# Exact path, no query: agy sends none (verified), and a query string is a data channel. +AGY_EGRESS_INTERCEPT_PATH="${AGY_EGRESS_INTERCEPT_PATH:-/oauth2/v2/userinfo}" AGY_DIFF_MODE="${AGY_DIFF_MODE:-auto}" # auto|inline|file. A diff is passed to agy either inlined # in the --print prompt, or written to a FILE agy reads with # its own tools. `auto` inlines a diff that fits under the @@ -389,7 +431,7 @@ REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY not set}" # _perm_err so cleanup() could never see it (agy review, GH-ListRollup PR #6). # Remove every temp file on exit. Pre-declared so the trap is safe under `set -u` even if the # script exits before a given file is created. -diff_file= diff_err= meta_file= prompt_file= out_file= raw= body_file= agy_diff_file= agy_sandbox= agy_jail_home= agy_jail_rt= agy_proxy_pid= jq_err= prior_body_file= archived_file= api_err= +diff_file= diff_err= meta_file= prompt_file= out_file= raw= body_file= agy_diff_file= agy_sandbox= agy_jail_home= agy_jail_rt= agy_proxy_pid= agy_egress_pid= jq_err= log_tail= prior_body_file= archived_file= api_err= # Also created mid-flight (permission lookup, compare-API merge base, archive trimming); a signal # or abort while one of those commands runs would otherwise leak the file in /tmp. _perm_err='' compare_err='' trimmed='' @@ -434,7 +476,7 @@ cleanup() { # cause. The pre-declaration stays and is still the actual guarantee; this is the cheap second # line for a function that only ever runs while something else is going wrong. for f in "${diff_file:-}" "${diff_err:-}" "${meta_file:-}" "${out_file:-}" "${raw:-}" "${body_file:-}" \ - "${jq_err:-}" "${prior_body_file:-}" "${archived_file:-}" "${api_err:-}" \ + "${jq_err:-}" "${log_tail:-}" "${prior_body_file:-}" "${archived_file:-}" "${api_err:-}" \ "${_perm_err:-}" "${compare_err:-}" "${trimmed:-}"; do [ -n "$f" ] && doomed+=("$f") done @@ -451,7 +493,10 @@ cleanup() { && { [ -z "$keep_set" ] || [ -z "${agy_diff_file:-}" ]; }; then rm -rf -- "$agy_sandbox" # an inline dry run has nothing in it to keep fi - [ -n "${agy_proxy_pid:-}" ] && kill "$agy_proxy_pid" 2>/dev/null + # `|| true`: under set -e a failed kill (the proxy already exited) would otherwise end this trap + # before the jail home and runtime dirs below are removed. + [ -n "${agy_proxy_pid:-}" ] && { kill "$agy_proxy_pid" 2>/dev/null || true; } + [ -n "${agy_egress_pid:-}" ] && { kill "$agy_egress_pid" 2>/dev/null || true; } [ -n "${agy_jail_home:-}" ] && [ -d "$agy_jail_home" ] && rm -rf -- "$agy_jail_home" [ -n "${agy_jail_rt:-}" ] && [ -d "$agy_jail_rt" ] && rm -rf -- "$agy_jail_rt" if [ -n "${agy_refs_created:-}" ] && [ -n "${PR:-}" ]; then @@ -1133,6 +1178,232 @@ agy_allowlisted_env_args() { agy_env=( env ) while IFS= read -r -d '' arg; do agy_env+=( "$arg" ); done < <(agy_allowlisted_env_args) +# The egress proxy, run with the host's python3 OUTSIDE the jail (embedded, so the vendored file +# set stays the same in every repository). The self-test extracts and exercises it. +agy_egress_proxy_src() { + cat <<'AGYPY' +"""agy-review egress proxy: the jail's only route to the network (stdlib only). + +Serves HTTP CONNECT on a Unix socket that is bind-mounted into the jail. A tunnel is opened only +to port 443 of a host that EXACTLY equals an allowlist entry (no wildcards, no suffixes: a +wildcard such as .googleapis.com would include Cloud Storage, where anyone can own a bucket). +One host may be intercepted: TLS is terminated with a per-run leaf certificate the jail trusts +(the CA key never enters the jail) and only body-less HTTP/1.1 GETs whose path fully matches a +regex are forwarded, one request per connection. This exists because www.googleapis.com serves +both the userinfo call agy needs and the Cloud Storage JSON API. + +The log records verdicts and allowlisted host names only. A denied host name or any path is +attacker-chosen and could carry a secret, so neither is ever written anywhere. + +argv: SOCKET LOG ALLOW_CSV [INTERCEPT_HOST PATH_REGEX CERT KEY] +""" + +import asyncio +import contextlib +import os +import re +import ssl +import sys + +sock_path, log_path, allow_csv = sys.argv[1], sys.argv[2], sys.argv[3] +allow = {h for h in allow_csv.split(",") if h} +icpt_host = sys.argv[4] if len(sys.argv) > 4 else "" +icpt_path = re.compile(sys.argv[5]) if icpt_host else None +server_ctx = None +if icpt_host: + server_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) + server_ctx.load_cert_chain(sys.argv[6], sys.argv[7]) + server_ctx.set_alpn_protocols(["http/1.1"]) +upstream_ctx = ssl.create_default_context() +logf = open(log_path, "a", buffering=1) # noqa: SIM115 - lives as long as the process +# Private file OUTSIDE the jail for denied names (never the public job log). +denied_path = os.environ.get("AGY_EGRESS_DENIED_FILE", "") +deniedf = open(denied_path, "a", buffering=1) if denied_path else None # noqa: SIM115 + + +def log(verdict, host=""): + logf.write(f"{verdict} {host if host in allow else ''}\n".rstrip() + "\n") + + +def close(w): + with contextlib.suppress(OSError, RuntimeError): + w.close() + + +async def pipe(r, w): + try: + while data := await r.read(65536): + w.write(data) + await w.drain() + except (ConnectionError, OSError, asyncio.IncompleteReadError): + pass + finally: + close(w) + + +async def refuse(cw, status): + with contextlib.suppress(OSError, RuntimeError): + cw.write(status + b"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + await cw.drain() + close(cw) + + +async def read_head(cr): + return await asyncio.wait_for(cr.readuntil(b"\r\n\r\n"), 30) + + +async def handle(cr, cw): + try: + head = await read_head(cr) + except ( + TimeoutError, + OSError, + asyncio.IncompleteReadError, + asyncio.LimitOverrunError, + ): + close(cw) + return + parts = head.split(b"\r\n", 1)[0].decode("latin-1", "replace").split() + if len(parts) != 3 or parts[0] != "CONNECT": + log("REFUSE-NONCONNECT") + await refuse(cw, b"HTTP/1.1 405 Method Not Allowed") + return + host, _, port = parts[1].rpartition(":") + if port != "443" or host not in allow: + log("DENY", host) + if deniedf is not None: + deniedf.write(parts[1][:300].replace("\n", " ") + "\n") + await refuse(cw, b"HTTP/1.1 403 Forbidden") + return + if host == icpt_host: + await intercept(cr, cw, host) + return + try: + ur, uw = await asyncio.wait_for(asyncio.open_connection(host, 443), 30) + except (TimeoutError, OSError): + log("FAIL", host) + await refuse(cw, b"HTTP/1.1 502 Bad Gateway") + return + log("ALLOW", host) + cw.write(b"HTTP/1.1 200 Connection Established\r\n\r\n") + await cw.drain() + await asyncio.gather(pipe(cr, uw), pipe(ur, cw)) + + +TOKEN = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+") +# Only these client headers are forwarded; everything else (including the client's own Host, +# Content-Length and Transfer-Encoding) is dropped, and Host is set by the proxy. +FORWARD = ( + "authorization", + "user-agent", + "accept", + "accept-encoding", + "accept-language", +) + + +def rebuild_request(head, host): + """Return the upstream request bytes, or None to refuse. + + Nothing the client wrote is forwarded verbatim: the request line is rebuilt from the + validated path, Host is the intercepted host, and only FORWARD headers are copied. + """ + if not head.endswith(b"\r\n\r\n"): + return None + body = head[:-4] + # Every line must end in CRLF: no bare CR or LF anywhere, and no other control byte or DEL. + if b"\r" in body.replace(b"\r\n", b"") or b"\n" in body.replace(b"\r\n", b""): + return None + if any((c < 0x20 and c not in (0x0D, 0x0A)) or c == 0x7F for c in body): + return None + lines = body.decode("ascii", "strict").split("\r\n") if body.isascii() else None + if not lines: + return None + req = lines[0].split(" ") + if len(req) != 3 or req[0] != "GET" or req[2] != "HTTP/1.1": + return None + if icpt_path is None or icpt_path.fullmatch(req[1]) is None: + return None + hosts, keep = [], [] + for line in lines[1:]: + if not line or line[0] in " \t": + return None # empty line inside the head, or obs-fold continuation + name, sep, value = line.partition(":") + if not sep or TOKEN.fullmatch(name) is None: + return None + lname, value = name.lower(), value.strip(" \t") + if lname == "host": + hosts.append(value.lower()) + elif lname in ("content-length", "transfer-encoding"): + if lname == "transfer-encoding" or value != "0": + return None + elif lname in FORWARD: + keep.append(f"{name}: {value}") + if len(hosts) != 1 or hosts[0] not in (host, f"{host}:443"): + return None + out = [ + f"GET {req[1]} HTTP/1.1", + f"Host: {host}", + *keep, + "Connection: close", + "", + "", + ] + return "\r\n".join(out).encode("ascii") + + +async def intercept(cr, cw, host): + cw.write(b"HTTP/1.1 200 Connection Established\r\n\r\n") + await cw.drain() + try: + await cw.start_tls(server_ctx) + head = await read_head(cr) + except ( + TimeoutError, + ssl.SSLError, + OSError, + asyncio.IncompleteReadError, + asyncio.LimitOverrunError, + ): + log("FAIL-TLS", host) + close(cw) + return + out = rebuild_request(head, host) + if out is None: + log("DENY-PATH", host) + await refuse(cw, b"HTTP/1.1 403 Forbidden") + return + try: + ur, uw = await asyncio.wait_for( + asyncio.open_connection(host, 443, ssl=upstream_ctx, server_hostname=host), + 30, + ) + except (TimeoutError, OSError): + log("FAIL", host) + close(cw) + return + log("ALLOW-PATH", host) + uw.write(out) + await uw.drain() + await pipe( + ur, cw + ) # requests after the first one on this connection are never forwarded + close(uw) + + +async def main(): + with contextlib.suppress(FileNotFoundError): + os.unlink(sock_path) + srv = await asyncio.start_unix_server(handle, path=sock_path) + os.chmod(sock_path, 0o600) + async with srv: + await srv.serve_forever() + + +asyncio.run(main()) +AGYPY +} + # --- the bubblewrap jail (AGY_ISOLATION=bwrap) -------------------------------------------------- # Verified 2026-11-22: inside this jail agy authenticates and reviews, sees only an empty HOME, has # no MCP servers/skills/hooks, cannot read any host file outside the jail, and over D-Bus can fetch @@ -1140,7 +1411,9 @@ while IFS= read -r -d '' arg; do agy_env+=( "$arg" ); done < <(agy_allowlisted_e # session service are AccessDenied by the proxy). agy_jail=() if [ "$AGY_ISOLATION" = bwrap ]; then - for _t in bwrap xdg-dbus-proxy gdbus; do + _need=( bwrap xdg-dbus-proxy gdbus ) + [ "$AGY_EGRESS" = filtered ] && _need+=( socat python3 openssl ) + for _t in "${_need[@]}"; do command -v "$_t" >/dev/null 2>&1 || { log "AGY_ISOLATION=bwrap needs '$_t' on the runner host; refusing to run agy unjailed (set AGY_ISOLATION=none to override, not recommended)"; exit 1; } done [ -n "${XDG_RUNTIME_DIR:-}" ] && [ -n "${DBUS_SESSION_BUS_ADDRESS:-}" ] \ @@ -1151,6 +1424,9 @@ if [ "$AGY_ISOLATION" = bwrap ]; then [[ "$_kv" =~ ^[A-Za-z0-9_.-]+=[A-Za-z0-9_.:@-]+$ ]] || { log "invalid AGY_KEYRING_ATTRS entry '$_kv'"; exit 1; } _dict="${_dict:+$_dict, }'${_kv%%=*}': '${_kv#*=}'" done + # Secret Service treats an empty attribute set as match-all, which would grant GetSecret on + # every item (including the gh token). Refuse it outright. + [ -n "$_dict" ] || { log "AGY_KEYRING_ATTRS is empty; refusing to grant agy keyring access"; exit 1; } mapfile -t _items < <(gdbus call --session --dest org.freedesktop.secrets \ --object-path /org/freedesktop/secrets/aliases/default \ --method org.freedesktop.Secret.Collection.SearchItems "{${_dict}}" 2>/dev/null \ @@ -1172,21 +1448,74 @@ if [ "$AGY_ISOLATION" = bwrap ]; then for _ in $(seq 1 100); do [ -S "$agy_jail_rt/bus" ] && break; sleep 0.1; done [ -S "$agy_jail_rt/bus" ] || { log "xdg-dbus-proxy did not start; refusing to run agy unjailed"; exit 1; } _uid="$(id -u)" - agy_jail=( bwrap --unshare-all --share-net --die-with-parent --new-session - --ro-bind /usr /usr - --symlink usr/lib /lib --symlink usr/lib /lib64 --symlink usr/bin /bin --symlink usr/bin /sbin + _net=( --share-net --ro-bind-try /run/systemd/resolve /run/systemd/resolve ) + _egress_binds=() _egress_env=() _inner=() + if [ "$AGY_EGRESS" = filtered ]; then + _allow="" + for _h in $AGY_EGRESS_ALLOW; do + [[ "$_h" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$ ]] \ + || { log "invalid AGY_EGRESS_ALLOW entry '$_h' (exact lowercase host names only, no wildcards)"; exit 1; } + _allow="${_allow:+$_allow,}$_h" + done + _ca_sys="" + for _c in /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/cert.pem; do + [ -s "$_c" ] && { _ca_sys="$_c"; break; } + done + [ -n "$_ca_sys" ] || { log "AGY_EGRESS=filtered: no system CA bundle found; refusing to run agy"; exit 1; } + # Per-run CA + leaf for the intercepted host. Both keys stay in the private runtime dir, which + # is never mounted into the jail; the jail gets only a CA bundle (system roots + this CA). + _pki="$agy_jail_rt/pki"; mkdir -m 700 "$_pki" + if ! { openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 1 \ + -subj "/CN=agy-review egress CA" -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,keyCertSign" -keyout "$_pki/ca.key" -out "$_pki/ca.pem" \ + && openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \ + -subj "/CN=$AGY_EGRESS_INTERCEPT_HOST" -keyout "$_pki/leaf.key" -out "$_pki/leaf.csr" \ + && openssl x509 -req -in "$_pki/leaf.csr" -CA "$_pki/ca.pem" -CAkey "$_pki/ca.key" -days 1 \ + -extfile <(printf 'subjectAltName=DNS:%s\nextendedKeyUsage=serverAuth\nbasicConstraints=CA:FALSE\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n' "$AGY_EGRESS_INTERCEPT_HOST") \ + -out "$_pki/leaf.pem"; } >/dev/null 2>&1; then + log "AGY_EGRESS=filtered: could not create the per-run certificates; refusing to run agy"; exit 1 + fi + cat "$_ca_sys" "$_pki/ca.pem" > "$agy_jail_rt/ca-bundle.pem" + agy_egress_proxy_src > "$agy_jail_rt/egress.py" + : > "$agy_jail_rt/egress-denied.txt"; chmod 600 "$agy_jail_rt/egress-denied.txt" + AGY_EGRESS_DENIED_FILE="$agy_jail_rt/egress-denied.txt" \ + python3 -I "$agy_jail_rt/egress.py" "$agy_jail_rt/egress.sock" "$agy_jail_rt/egress.log" "$_allow" \ + "$AGY_EGRESS_INTERCEPT_HOST" "$AGY_EGRESS_INTERCEPT_PATH" "$_pki/leaf.pem" "$_pki/leaf.key" \ + 2>>"$LOG" & + agy_egress_pid=$! + for _ in $(seq 1 100); do [ -S "$agy_jail_rt/egress.sock" ] && break; sleep 0.1; done + [ -S "$agy_jail_rt/egress.sock" ] || { log "egress proxy did not start; refusing to run agy"; exit 1; } + _net=() # --unshare-all without --share-net: the jail has only its own loopback + _egress_binds=( --ro-bind "$agy_jail_rt/egress.sock" /run/agy-egress.sock + --ro-bind "$agy_jail_rt/ca-bundle.pem" /run/agy-ca-bundle.pem ) + _egress_env=( "HTTPS_PROXY=http://127.0.0.1:3128" "https_proxy=http://127.0.0.1:3128" + "HTTP_PROXY=http://127.0.0.1:3128" "http_proxy=http://127.0.0.1:3128" + "NO_PROXY=" "no_proxy=" "SSL_CERT_FILE=/run/agy-ca-bundle.pem" ) + # Inside the jail: bridge loopback 3128 to the proxy socket, wait for it, then exec the payload. + _inner=( /usr/bin/bash -c 'socat TCP-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:/run/agy-egress.sock 2>/dev/null & for _ in $(seq 1 100); do (exec 3<>/dev/tcp/127.0.0.1/3128) 2>/dev/null && break; sleep 0.1; done; exec "$@"' agy-jail ) + fi + # Mirror the host's real top-level layout: merged-/usr distributions differ (Arch links /lib64 + # to usr/lib, Debian and Ubuntu to usr/lib64), and the ELF interpreter must resolve the same way. + _toplevel=() + for _d in /bin /sbin /lib /lib32 /lib64 /libx32; do + if [ -L "$_d" ]; then _toplevel+=( --symlink "$(readlink "$_d")" "$_d" ) + elif [ -d "$_d" ]; then _toplevel+=( --ro-bind "$_d" "$_d" ) + fi + done + agy_jail=( bwrap --unshare-all "${_net[@]}" --die-with-parent --new-session + --ro-bind /usr /usr "${_toplevel[@]}" --ro-bind /etc /etc --proc /proc --dev /dev --tmpfs /tmp - --ro-bind-try /run/systemd/resolve /run/systemd/resolve --tmpfs /home --bind "$agy_jail_home" "$HOME" --ro-bind "$(readlink -f "$AGY_BIN")" "$AGY_BIN" --ro-bind "$(cd "$(dirname "$0")" && pwd)/_agy_print.sh" "$(cd "$(dirname "$0")" && pwd)/_agy_print.sh" --ro-bind "$prompt_file" "$prompt_file" --bind "$agy_sandbox" "$agy_sandbox" --chdir "$agy_sandbox" - --dir "/run/user/$_uid" --ro-bind "$agy_jail_rt/bus" "/run/user/$_uid/bus" ) + --dir "/run/user/$_uid" --ro-bind "$agy_jail_rt/bus" "/run/user/$_uid/bus" + "${_egress_binds[@]}" "${_inner[@]}" ) # Inside the jail, D-Bus is the filtered proxy (later env assignments override earlier ones). - agy_env+=( "XDG_RUNTIME_DIR=/run/user/$_uid" "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$_uid/bus" ) - log "agy isolation: bwrap jail, empty HOME, D-Bus limited to ${#_items[@]} keyring item(s)" - unset _t _dict _kv _items _rules _it _uid + agy_env+=( "XDG_RUNTIME_DIR=/run/user/$_uid" "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$_uid/bus" "TMPDIR=/tmp" "${_egress_env[@]}" ) + log "agy isolation: bwrap jail, empty HOME, D-Bus limited to ${#_items[@]} keyring item(s), egress ${AGY_EGRESS}" + unset _t _need _dict _kv _items _rules _it _uid _net _egress_binds _egress_env _inner _allow _h _ca_sys _c _pki _toplevel _d fi [ -n "$AGY_MODEL" ] && flags+=( --model "$AGY_MODEL" ) [ -n "$AGY_EFFORT" ] && flags+=( --effort "$AGY_EFFORT" ) @@ -1257,6 +1586,22 @@ for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do # normalize CRs without sed -i (avoid in-place edit footguns) tr -d '\r' < "$out_file" > "$out_file.clean" && mv "$out_file.clean" "$out_file" + # These two run on EVERY capture before any handler below logs or clears it: the backend-error + # handler prints a short capture's first line to the public job log, which must never carry a + # credential, and a jail diagnostic must never be retried or posted. + if cred_kind="$(credential_kind_present "$out_file")"; then + log "refusing to post: agy's output contains a credential-shaped string (${cred_kind}) (attempt ${attempt}/${AGY_RETRIES}). Nothing was posted or logged from it. Inspect the runner host; the diff may carry a prompt injection." + : > "$out_file" + exit 1 + fi + # A jail that never started (no user namespaces, a missing bind source, ...) prints its own + # diagnostic, which the PTY capture keeps while `|| true` drops the exit status. Never let that + # text be posted as a review, and do not retry: the next attempt would fail the same way. + if agy_jail_failed "$out_file"; then + log "the agy jail failed to start; nothing was posted. First line: $(grep -m1 -v '^[[:space:]]*$' "$out_file" | cut -c1-200)" + exit 1 + fi + # If the capture carries a live OAuth authorization URL, agy's cached Google session has lapsed # on this runner and there is NO review — just its interactive login flow (the OAuth URL + a # "paste the authorization code" prompt). That must never reach a public PR comment (noise, @@ -1308,6 +1653,22 @@ for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do sleep "$delay" fi done +# Egress summary: verdict COUNTS only. A denied host name or path is attacker-chosen and could +# carry a secret, and this log is public on a public repository, so names are never printed. +# Denied names go ONLY to a host-private log (mode 600, beside agy's own state), so a new host +# that an agy update starts using can be found and added to AGY_EGRESS_ALLOW. +if [ -s "${agy_jail_rt:-}/egress-denied.txt" ]; then + _dl="${AGY_EGRESS_DENIED_LOG:-$HOME/.gemini/antigravity-cli/agy-egress-denied.log}" + if agy_record_denied "$agy_jail_rt/egress-denied.txt" "$_dl" "${REPO:-?}#${PR:-?}"; then + log "egress: denied host names (if any are needed, add them to AGY_EGRESS_ALLOW) are in $_dl on the runner host" + else + log "egress: could not write the private denied-host log $_dl" + fi + unset _dl +fi +if [ -s "${agy_jail_rt:-}/egress.log" ]; then + log "egress: $(awk '{print $1}' "$agy_jail_rt/egress.log" | sort | uniq -c | awk '{printf "%s %s, ", $2, $1}' | sed 's/, $//')" +fi # Release the agy lock so the next queued job proceeds. NO redirection on this `exec`: a bare # `exec` applies its redirections to the rest of the SCRIPT, so the `2>/dev/null` that used to be # here sent every later `log` line (they write to stderr) to /dev/null -- "posted", "updated", @@ -1346,7 +1707,17 @@ if ! have_text "$out_file"; then # GITHUB_TOKEN) in logs, and this is agy's own diagnostic stream, but a bounded tail avoids # publishing an unbounded volume of stderr (which could echo prompt/diff content) into CI. log "----- captured agy stderr ($LOG), last ${AGY_LOG_TAIL_LINES:-60} lines (secrets auto-masked) -----" - tail -n "${AGY_LOG_TAIL_LINES:-60}" "$LOG" | sed 's/^/[agy] /' >&2 || true + # GitHub masks only REGISTERED secrets; agy's own Google token is not one. Withhold the whole + # tail if it carries any credential shape, naming only the kind. + # A regular file, not a pipe: the scan tests -s and reads its input once per pattern. + log_tail="$(mktemp)" + tail -n "${AGY_LOG_TAIL_LINES:-60}" "$LOG" > "$log_tail" || true + if log_cred="$(credential_kind_present "$log_tail")"; then + log "(withheld: agy's stderr contains a credential-shaped string (${log_cred}); inspect $LOG on the runner host)" + else + sed 's/^/[agy] /' "$log_tail" >&2 || true + fi + rm -f -- "$log_tail" log "----- end agy stderr -----" else log "(agy stderr log is empty -- agy likely failed before writing, e.g. execve E2BIG on an oversized prompt)" From aae5617b8ebe48c1726a7e0415cec7af4340a4d1 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 15:44:45 -0500 Subject: [PATCH 03/14] fix(deps): bump url 2.5.8 -> 2.5.9 for RUSTSEC-2026-0592 RUSTSEC-2026-0592 (stack overflow in Url::origin() on nested blob: URLs) entered the advisory database after main's last green run, so Dependency Audit and Cargo Deny Check are red on any new push. url reaches the tree only through webbrowser -> egui-winit in rustysnes-frontend. A lockfile-only patch bump. Verification: cargo audit reports no vulnerabilities; cargo deny check advisories: ok. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 08011c4e..027ff37c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1469,9 +1469,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -4990,9 +4990,9 @@ dependencies = [ [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", From ec430c6bd0c4dff8b2ae4a3fe53640ae90b6ab2a Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 16:04:50 -0500 Subject: [PATCH 04/14] docs(agy): re-sync AGY-REVIEWER.md to template adb45e8 The vendored reviewer README now passes markdownlint defaults (0 errors, down from 77: MD013 line-length and MD060 table style). Prose is rewrapped to 80 columns, long code lines are rewritten, table delimiters use the compact style, and tables are fenced against MD013. It also corrects the security-model note on unbuffer: env -i now starts unbuffer itself. Also re-syncs the self-test labels to en-US spelling (template fd64ab3). Documentation and labels only; no behavior change. Co-Authored-By: Claude Opus 5.5 --- .github/AGY-REVIEWER.md | 232 ++++++++++++++++++++++------------------ 1 file changed, 125 insertions(+), 107 deletions(-) diff --git a/.github/AGY-REVIEWER.md b/.github/AGY-REVIEWER.md index f3f5e715..c0376e41 100644 --- a/.github/AGY-REVIEWER.md +++ b/.github/AGY-REVIEWER.md @@ -4,19 +4,22 @@ A drop-in replacement for the retired **Gemini Code Assist for GitHub** consumer app, rebuilt to run on your **Google AI Ultra** subscription with **no paid, pay-as-you-go API usage**. -It auto-reviews pull requests (on open, on every push, and on an `/agy-review` comment) using -the **Antigravity CLI (`agy`)** running on a **self-hosted runner** on your own -machine. Because `agy` authenticates with your Google OAuth session, every -review draws on your Ultra rate limits instead of a metered Gemini API key. +It auto-reviews pull requests (on open, on every push, and on an `/agy-review` +comment) using the **Antigravity CLI (`agy`)** running on a **self-hosted +runner** on your own machine. Because `agy` authenticates with your Google OAuth +session, every review draws on your Ultra rate limits instead of a metered +Gemini API key. --- ## Why this is free under Ultra (the one idea that matters) + | Path | Auth | Cost | -|------|------|------| +| --- | --- | --- | | Gemini **API key** / `run-gemini-cli` / Antigravity **SDK** (`run-agy-sdk`) | API key | **metered, pay-as-you-go** | | Antigravity **CLI** (`agy`) | Google **OAuth** | **your Ultra rate limits** | + `agy` supports OAuth sign-in with "generous rate limits on Google AI Pro and Ultra plans." So the whole trick is to build the reviewer around the **`agy` @@ -36,15 +39,16 @@ is why this uses a self-hosted runner rather than GitHub's cloud runners. ```text GitHub PR event ──▶ self-hosted runner (YOUR machine, systemd --user) - │ gh pr diff ─▶ build adversarial-reviewer prompt (+ style guide) - │ agy --print (PTY-wrapped, OAuth/Ultra) ─▶ review text - └─ gh api ─▶ one comment per PR, edited in place (earlier rounds archived) + │ gh pr diff ─▶ adversarial-reviewer prompt (+ style guide) + │ agy --print in the jail (PTY, OAuth/Ultra) ─▶ review text + └─ gh api ─▶ one comment per PR, edited in place (rounds archived) ``` Files in this template: + | File | Goes where | Purpose | -|------|-----------|---------| +| --- | --- | --- | | `.github/workflows/antigravity-review.yml` | **copy → target repo** | trigger + job definition | | `scripts/agy-review.sh` | **copy → target repo** | the reviewer (diff → prompt → `agy` → comment) | | `scripts/_agy_print.sh` | **copy → target repo** | PTY fallback helper (only if `unbuffer` is absent) | @@ -57,14 +61,15 @@ Files in this template: | `systemd/github-agy-runner@.service` | `~/.config/systemd/user/` | runs each runner in your session (template-local) | | `gitignore.snippet` | *optional append* | precautionary ignores (see below) — never copied over an existing `.gitignore` | | `.gitignore` | template-local | this repo's own hygiene — **do not** copy into target repos | + -> **Copy into a target repo** (what `install-into-repo.sh` does): the workflow, the four -> scripts `agy-review.sh`, `_agy_print.sh`, `_agy_comment_body.sh` and +> **Copy into a target repo** (what `install-into-repo.sh` does): the workflow, +> the four scripts `agy-review.sh`, `_agy_print.sh`, `_agy_comment_body.sh` and > `agy-review-selftest.sh`, this README as `.github/AGY-REVIEWER.md`, -> `.github/actionlint.yaml` when the target has none, and optionally `.github/agy-review.md`. -> The target's `.gitignore` is not touched. Everything else -> (`systemd/`, the provision/deprovision scripts, this repo's `.gitignore`, `*.example`, -> `gitignore.snippet`) stays here. +> `.github/actionlint.yaml` when the target has none, and optionally +> `.github/agy-review.md`. The target's `.gitignore` is not touched. Everything +> else (`systemd/`, the provision/deprovision scripts, this repo's `.gitignore`, +> `*.example`, `gitignore.snippet`) stays here. --- @@ -77,16 +82,18 @@ Files in this template: agy -p "reply with the single word: ok" # should print: ok # Tools the reviewer uses (all already present here): -# gh jq sqlite3 col script + unbuffer (from `expect`) -# bwrap xdg-dbus-proxy gdbus (the agy jail; AGY_ISOLATION=bwrap, the default) -# socat python3 openssl (the jail's egress filter; AGY_EGRESS=filtered, the default) -# iconv (glibc) for UTF-8 scrubbing; python3 is an optional fallback used only without iconv -pacman -Q github-cli jq sqlite expect util-linux bubblewrap xdg-dbus-proxy glib2 socat python openssl >/dev/null # verify; install any missing with paru/pacman +# gh jq sqlite3 col script, plus unbuffer (from `expect`) +# bwrap xdg-dbus-proxy gdbus the agy jail (AGY_ISOLATION=bwrap) +# socat python3 openssl its egress filter (AGY_EGRESS=filtered) +# iconv (glibc) scrubs UTF-8; python3 is the fallback without iconv +# Verify; install any missing with paru/pacman: +pacman -Q github-cli jq sqlite expect util-linux bubblewrap \ + xdg-dbus-proxy glib2 socat python openssl >/dev/null ``` -`unbuffer` is preferred. Without it, the reviewer falls back to `script(1)` and strips the -`Script started on` and `Script done on` records that util-linux writes into the capture even -with `-q`. +`unbuffer` is preferred. Without it, the reviewer falls back to `script(1)` and +strips the `Script started on` and `Script done on` records that util-linux +writes into the capture even with `-q`. If `agy -p` prints nothing, fix auth first (run `agy` interactively once to complete the Google sign-in) — the reviewer can't work until that one-liner does. @@ -107,7 +114,8 @@ for pair in "RustySNES:rustysnes" "RustyN64:rustyn64" set repo (string split ":" $pair)[1]; set name (string split ":" $pair)[2] mkdir -p ~/actions-runner/$name tar xzf ~/Downloads/actions-runner-linux-x64-$VER.tar.gz -C ~/actions-runner/$name - set token (gh api -X POST repos/doublegate/$repo/actions/runners/registration-token --jq .token) + set token (gh api -X POST \ + repos/doublegate/$repo/actions/runners/registration-token --jq .token) cd ~/actions-runner/$name ./config.sh --url https://github.com/doublegate/$repo --token $token \ --labels agy --name (hostname)-$name --work _work --unattended --replace @@ -164,9 +172,9 @@ post comments and your local `agy` session for the model. The reviewer writes nothing into the working tree. All its files, including the large-diff handoff file agy reads when a diff is too large to inline, live in a -private `mktemp -d` sandbox under `$RUNNER_TEMP` that the `EXIT` trap removes, so a -target repo needs no ignore entry. (Earlier versions wrote the handoff file to -`.agy-review-work/` in the checkout and required `/.agy-review-work/` in +private `mktemp -d` sandbox under `$RUNNER_TEMP` that the `EXIT` trap removes, +so a target repo needs no ignore entry. (Earlier versions wrote the handoff file +to `.agy-review-work/` in the checkout and required `/.agy-review-work/` in `.gitignore`; that line is now unused and harmless where it already exists.) **Never** copy this template's own `.gitignore` over a project's. @@ -175,10 +183,10 @@ target repo needs no ignore entry. (Earlier versions wrote the handoff file to ## Triggering it - **Automatic:** open, reopen, or **push to** a PR → a review is posted within a - minute or two. This fires from the workflow on the **PR branch**, so the very PR - that adds the workflow is itself a live test, and every follow-up push re-reviews - (`synchronize`). Auto-runs only for PRs authored by a trusted user (see the - security model) so a fork's code never auto-executes on the runner. + minute or two. This fires from the workflow on the **PR branch**, so the very + PR that adds the workflow is itself a live test, and every follow-up push + re-reviews (`synchronize`). Auto-runs only for PRs authored by a trusted user + (see the security model) so a fork's code never auto-executes on the runner. - **On demand:** comment **`/agy-review`** on any PR to (re)run it. ### One comment per PR, appended to — never replaced @@ -206,9 +214,10 @@ because a silent truncation would look exactly like a PR reviewed only once. > the workflow is merged to `main`. The `opened` trigger works from the PR branch > immediately. > -> The same rule governs the **scripts**: the workflow checks out the default branch -> to run them, so a change to `agy-review.sh` (the archive behavior above included) -> has **no effect on any PR until it is merged**, not even on the PR that makes it. +> The same rule governs the **scripts**: the workflow checks out the default +> branch to run them, so a change to `agy-review.sh` (the archive behavior above +> included) has **no effect on any PR until it is merged**, not even on the PR +> that makes it. --- @@ -221,15 +230,17 @@ non-ephemeral, so untrusted code from a fork PR can persistently compromise the host. This template applies the standard mitigations, but the residual risk is yours to accept: -- **Required: approval for every outside contributor.** For a `pull_request` event - GitHub runs the workflow file **from the PR's own branch**, so a fork can edit or - delete any `if:` in it and point a job at your runner. Only GitHub's approval gate - stops that. Set **Settings → Actions → General → Fork pull request workflows → - Require approval for all outside collaborators** (API: - `gh api -X PUT repos/OWNER/REPO/actions/permissions/fork-pr-contributor-approval - -f approval_policy=all_external_contributors`). The default, - `first_time_contributors`, runs a returning contributor's fork PR without asking. - Never approve a fork PR's workflows unless you have read its `.github/` changes. +- **Required: approval for every outside contributor.** For a `pull_request` + event GitHub runs the workflow file **from the PR's own branch**, so a fork + can edit or delete any `if:` in it and point a job at your runner. Only + GitHub's approval gate stops that. Set **Settings → Actions → General → Fork + pull request workflows → Require approval for all outside collaborators** + (API: `gh api -X PUT + repos/OWNER/REPO/actions/permissions/fork-pr-contributor-approval -f + approval_policy=all_external_contributors`). The default, + `first_time_contributors`, runs a returning contributor's fork PR without + asking. Never approve a fork PR's workflows unless you have read its + `.github/` changes. - **Same-repository gate on auto-runs:** the `pull_request` job (open/reopen/push, i.e. `synchronize`) is written to run only when the PR head is a branch **in this repository** (`github.event.pull_request.head.repo.full_name == github.repository`). @@ -242,13 +253,13 @@ yours to accept: `scripts/agy-review.sh`, which asks the permissions API for the commenter and fails closed; the script also re-checks that the PR is not from a fork, because the `issue_comment` payload has no head-repo field for the `if:` to gate on. -- **First-install bootstrap:** as shipped, on a repository whose default branch has - no reviewer yet, the workflow runs the PR head's scripts once, only for a +- **First-install bootstrap:** as shipped, on a repository whose default branch + has no reviewer yet, the workflow runs the PR head's scripts once, only for a same-repo branch whose author has write access *at run time*. Remove the bootstrap steps once the reviewer is on the default branch (they also trip - CodeQL's `actions/untrusted-checkout`); most repositories carrying this reviewer - have done so. Without them, a PR opened while the default branch has no - reviewer gets a `::warning::` and a skipped review step (the "Check the + CodeQL's `actions/untrusted-checkout`); most repositories carrying this + reviewer have done so. Without them, a PR opened while the default branch has + no reviewer gets a `::warning::` and a skipped review step (the "Check the reviewer is present" step), not a red check. - **Least surface in the job:** review-only prompt, `--sandbox`, no repo secrets (built-in `GITHUB_TOKEN` only), temp files cleaned via an `EXIT` trap. @@ -265,36 +276,38 @@ yours to accept: keyring item (the `gh` token), the bulk `GetSecrets` call or any other session service is `AccessDenied`. A host without `bwrap`, `xdg-dbus-proxy` or `gdbus` fails closed. `AGY_ISOLATION=none` opts out, which is not recommended. -- **The jail has no network of its own (`AGY_EGRESS=filtered`, the default):** agy - must be able to read its own Google login token, so the network is the remaining - way to leak it. The jail gets only its own loopback. Its single route out is an - HTTPS `CONNECT` proxy outside the jail, reached through a bind-mounted Unix socket, - which tunnels only to port 443 of hosts that **exactly** match `AGY_EGRESS_ALLOW`. - Wildcards are rejected, because `.googleapis.com` would include Cloud Storage, - where anyone can own a writable bucket. One host needs more than that: - `www.googleapis.com` serves both the userinfo call agy makes at startup and the - Cloud Storage JSON API. So the proxy terminates TLS for that host only, with a - per-run CA whose private key never enters the jail, and forwards only a body-less - `GET /oauth2/v2/userinfo` (exact path, no query), which it rebuilds itself. It - sets its own `Host` header, because Google's front end routes by `Host` and a - forwarded one could front to Cloud Storage. It also copies only a short header - allowlist, and refuses bare CR or LF, control bytes, obs-fold and duplicate or - foreign `Host` headers. Verified from inside the jail: Cloud Storage uploads and - reads through `www.googleapis.com` (including path-traversal, encoded-path and +- **The jail has no network of its own (`AGY_EGRESS=filtered`, the default):** + agy must be able to read its own Google login token, so the network is the + remaining way to leak it. The jail gets only its own loopback. Its single + route out is an HTTPS `CONNECT` proxy outside the jail, reached through a + bind-mounted Unix socket, which tunnels only to port 443 of hosts that + **exactly** match `AGY_EGRESS_ALLOW`. Wildcards are rejected, because + `.googleapis.com` would include Cloud Storage, where anyone can own a writable + bucket. One host needs more than that: `www.googleapis.com` serves both the + userinfo call agy makes at startup and the Cloud Storage JSON API. So the + proxy terminates TLS for that host only, with a per-run CA whose private key + never enters the jail, and forwards only a body-less `GET /oauth2/v2/userinfo` + (exact path, no query), which it rebuilds itself. It sets its own `Host` + header, because Google's front end routes by `Host` and a forwarded one could + front to Cloud Storage. It also copies only a short header allowlist, and + refuses bare CR or LF, control bytes, obs-fold and duplicate or foreign `Host` + headers. Verified from inside the jail: Cloud Storage uploads and reads + through `www.googleapis.com` (including path-traversal, encoded-path and HTTP/2 variants), `storage.googleapis.com`, any other host or port, direct connections, raw TCP and DNS are all refused, while a full review completes. - The job log reports egress verdict **counts** only, because a denied host name or - path is attacker-chosen and could itself carry a secret into a public log. + The job log reports egress verdict **counts** only, because a denied host name + or path is attacker-chosen and could itself carry a secret into a public log. Residual risk: the allowed Gemini backends and the token endpoint can still be - reached, but data sent there goes to Google under the reviewer's own account, not - to an attacker. - **If reviews start failing after an agy update**, the new version probably needs - a host that is not on the list. The job log shows the egress counts. Denied host - names never appear there; they go to - `~/.gemini/antigravity-cli/agy-egress-denied.log` on the runner host (mode 600, - beside agy's own state). Add a needed host to `AGY_EGRESS_ALLOW`, which takes - exact names only. If the host also serves storage or another API, path-filter it - through `AGY_EGRESS_INTERCEPT_HOST` and `AGY_EGRESS_INTERCEPT_PATH` instead. + reached, but data sent there goes to Google under the reviewer's own account, + not to an attacker. + **If reviews start failing after an agy update**, the new version probably + needs a host that is not on the list. The job log shows the egress counts. + Denied host names never appear there; they go to + `~/.gemini/antigravity-cli/agy-egress-denied.log` on the runner host (mode + 600, beside agy's own state). Add a needed host to `AGY_EGRESS_ALLOW`, which + takes exact names only. If the host also serves storage or another API, + path-filter it through `AGY_EGRESS_INTERCEPT_HOST` and + `AGY_EGRESS_INTERCEPT_PATH` instead. - **agy never sees the checkout:** agy runs with `--dangerously-skip-permissions` and reads an untrusted diff, so a prompt injection could try to write files. It is started from a private, empty `mktemp -d` sandbox under `$RUNNER_TEMP` @@ -304,30 +317,34 @@ yours to accept: later token-bearing `git` call would execute, is therefore out of reach; the script's own post-agy `git` calls also run with `core.hooksPath=/dev/null` and `core.fsmonitor=false`. -- **agy gets no credentials:** agy is started with an **allowlisted** environment - (`env -i` plus `HOME`, `PATH`, `USER`, `LOGNAME`, `SHELL`, the locale, `TERM`, - `TMPDIR`, `TZ`, the `XDG_*` directories, `DBUS_SESSION_BUS_ADDRESS`, `DISPLAY`, - `WAYLAND_DISPLAY`, `XAUTHORITY`). Nothing else from the job reaches it: no - `GH_TOKEN`/`GITHUB_TOKEN`, no `ACTIONS_RUNTIME_TOKEN` or OIDC request token, and no - workflow `env:` value, including secrets under ordinary names that a - name-pattern denylist would miss. The session variables are what agy needs to - reach the desktop keyring holding its Google OAuth session, which was verified on - the runner host. `AGY_ENV_PASSTHROUGH` (space-separated names) adds a variable - if a host needs one. `unbuffer` keeps its own environment and runs `env -i ... agy`, - so only agy is reduced. `agy-review-selftest.sh` asserts all of the above. - -To reduce the remaining exposure, run each job on a **clean, disposable host** (a VM or -container image recreated per job). Re-registering a runner on the same host is not enough, -because the host's state survives. Making the repository private does not remove the risk either: -if fork workflows are enabled for a private repository, anyone who can fork it can still reach the -runner, so disable fork workflows there or gate them the same way. +- **agy gets no credentials:** agy is started with an **allowlisted** + environment (`env -i` plus `HOME`, `PATH`, `USER`, `LOGNAME`, `SHELL`, the + locale, `TERM`, `TMPDIR`, `TZ`, the `XDG_*` directories, + `DBUS_SESSION_BUS_ADDRESS`, `DISPLAY`, `WAYLAND_DISPLAY`, `XAUTHORITY`). + Nothing else from the job reaches it: no `GH_TOKEN`/`GITHUB_TOKEN`, no + `ACTIONS_RUNTIME_TOKEN` or OIDC request token, and no workflow `env:` value, + including secrets under ordinary names that a name-pattern denylist would + miss. The session variables are what agy needs to reach the desktop keyring + holding its Google OAuth session, which was verified on the runner host. + `AGY_ENV_PASSTHROUGH` (space-separated names) adds a variable if a host needs + one. `env -i` starts `unbuffer` itself, so no allowlisted value appears in the + argv of the long-lived `unbuffer` process, which is readable by every local + user in `/proc`. `agy-review-selftest.sh` asserts all of the above. + +To reduce the remaining exposure, run each job on a **clean, disposable host** +(a VM or container image recreated per job). Re-registering a runner on the same +host is not enough, because the host's state survives. Making the repository +private does not remove the risk either: if fork workflows are enabled for a +private repository, anyone who can fork it can still reach the runner, so +disable fork workflows there or gate them the same way. --- ## Configuration (workflow `env:`) + | Variable | Default | Meaning | -|----------|---------|---------| +| --- | --- | --- | | `AGY_MODEL` | *(agy default)* | e.g. `gemini-3-pro`; run `agy models` to see IDs | | `AGY_EFFORT` | `high` | reasoning effort: `low` / `medium` / `high` | | `AGY_PRINT_TIMEOUT` | `10m` | base wait for a single `agy --print`; raised for a large diff (next row). Setting it pins it and turns the raise off. Was `5m`: mid-size inlined diffs at `high` effort timed out at that base | @@ -346,6 +363,7 @@ runner, so disable fork workflows there or gate them the same way. | `AGY_EGRESS_DENIED_LOG` | `~/.gemini/antigravity-cli/agy-egress-denied.log` | host-private (mode 600) log of denied egress host names, for diagnosing an agy update; never printed to the job log | | `AGY_KEYRING_ATTRS` | `username=antigravity service=gemini` | Secret Service attributes of agy's own login item; the jail's D-Bus proxy allows `GetSecret` on the matching item(s) only | | `AGY_ENV_PASSTHROUGH` | *(empty)* | extra environment variable NAMES (space-separated) to pass to agy on top of the session allowlist; everything else is withheld | + --- @@ -381,20 +399,20 @@ runner, so disable fork workflows there or gate them the same way. script change only after it reaches the default branch. - **Job never starts:** no runner is online/idle with the `agy` label, or the machine is asleep. Check `systemctl --user status github-agy-runner`. -- **Review fails on a very large PR (`gh pr diff failed`):** GitHub's API refuses - any diff over **20,000 lines** with HTTP 406, so `gh pr diff` cannot fetch it at - all. This is separate from — and upstream of — the arg-size handling - (`AGY_DIFF_MODE`): that decides how a diff *already in hand* reaches agy, but a - 406 means there is no diff in hand. The script now detects the 406 specifically - (a genuine auth/network/bad-PR failure is still fatal) and falls back to - computing the diff locally: it fetches `refs/pull//head` and the base branch - into private `refs/agy/*`, takes `git merge-base`, and `git diff`s them. It - fetches objects but **never checks them out** — the working tree is untouched and - the PR content is never executed — and the refs are removed on exit. The - recovered diff then flows through the normal inline/file path, so a 67k-line PR - reviews the same as a 50-line one. The fetch authenticates via `http.extraheader` - (Actions `GITHUB_TOKEN`), falling back to git's ambient credentials for a hand - run, so it does not depend on `persist-credentials`. +- **Review fails on a very large PR (`gh pr diff failed`):** GitHub's API + refuses any diff over **20,000 lines** with HTTP 406, so `gh pr diff` cannot + fetch it at all. This is separate from — and upstream of — the arg-size + handling (`AGY_DIFF_MODE`): that decides how a diff *already in hand* reaches + agy, but a 406 means there is no diff in hand. The script now detects the 406 + specifically (a genuine auth/network/bad-PR failure is still fatal) and falls + back to computing the diff locally: it fetches `refs/pull//head` and the + base branch into private `refs/agy/*`, takes `git merge-base`, and `git diff`s + them. It fetches objects but **never checks them out** — the working tree is + untouched and the PR content is never executed — and the refs are removed on + exit. The recovered diff then flows through the normal inline/file path, so a + 67k-line PR reviews the same as a 50-line one. The fetch authenticates via + `http.extraheader` (Actions `GITHUB_TOKEN`), falling back to git's ambient + credentials for a hand run, so it does not depend on `persist-credentials`. --- From 58ef4b9463a77bf909c9cde313ea39ac9f57d55b Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 16:27:53 -0500 Subject: [PATCH 05/14] fix(deps): bump url to 2.5.9 in fuzz/Cargo.lock too Dependency Audit scans both lockfiles. aae5617 bumped only the workspace Cargo.lock, so RUSTSEC-2026-0592 (url 2.5.8) still failed from fuzz/Cargo.lock. The fuzz crate now takes 2.5.9 as well. Verification: cargo audit --file fuzz/Cargo.lock reports no vulnerabilities. Co-Authored-By: Claude Opus 5.5 --- fuzz/Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 4f55b09e..0160f70b 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -941,9 +941,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -3166,9 +3166,9 @@ checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", From 92ca264bde30a2f84e7f4968078763a7bd7feeeb Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 17:03:27 -0500 Subject: [PATCH 06/14] ci: re-sync the reviewer to template 1d782bb (all-host interception) Re-syncs the vendored reviewer scripts and .github/AGY-REVIEWER.md byte for byte from the antigravity-pr-review template at 1d782bb. Local workflow overrides are unchanged. - Fronting fix (HIGH from this PR's review, reproduced live): only www.googleapis.com was intercepted, and Google's front end routes by Host on any googleapis connection, so a request to oauth2, aicode or daily-cloudcode-pa carrying `Host: storage.googleapis.com` reached Cloud Storage. Every allowed host is now TLS-intercepted. Each connection carries one HTTP/1.1 request, validated strictly and rebuilt with the proxy's own Host and a body forwarded exactly once. Fronting through all four hosts is verified blocked from inside the jail, and a full review completes. - AGY_EGRESS_PATH_RULES (host=/exact/path, literal) replaces AGY_EGRESS_INTERCEPT_HOST/_PATH. - Credential-shaped output is redacted to `[REDACTED: ]` with a note in the comment, instead of failing the review. The scan cannot tell a secret from a test fixture. Anything redaction misses still fails closed. - Python >= 3.11 is checked. The jail refuses to launch agy when its egress bridge is down. The denied-host log keeps the newest 500 records, and streams are closed on every error path. - Self-test: the TLS cases no longer depend on curl, and a certificate failure is a FAIL. There are 20 offline proxy cases and full redaction coverage. Verification: agy-review-selftest.sh all checks passed; actionlint clean; markdownlint clean on AGY-REVIEWER.md; gitleaks no leaks in scripts/. Co-Authored-By: Claude Opus 5.5 --- .github/AGY-REVIEWER.md | 67 +++-- scripts/agy-review-selftest.sh | 213 ++++++++------- scripts/agy-review.sh | 464 +++++++++++++++++++++------------ 3 files changed, 465 insertions(+), 279 deletions(-) diff --git a/.github/AGY-REVIEWER.md b/.github/AGY-REVIEWER.md index c0376e41..05c96f1e 100644 --- a/.github/AGY-REVIEWER.md +++ b/.github/AGY-REVIEWER.md @@ -84,7 +84,7 @@ agy -p "reply with the single word: ok" # should print: ok # Tools the reviewer uses (all already present here): # gh jq sqlite3 col script, plus unbuffer (from `expect`) # bwrap xdg-dbus-proxy gdbus the agy jail (AGY_ISOLATION=bwrap) -# socat python3 openssl its egress filter (AGY_EGRESS=filtered) +# socat python3>=3.11 openssl its egress filter (AGY_EGRESS=filtered) # iconv (glibc) scrubs UTF-8; python3 is the fallback without iconv # Verify; install any missing with paru/pacman: pacman -Q github-cli jq sqlite expect util-linux bubblewrap \ @@ -280,34 +280,55 @@ yours to accept: agy must be able to read its own Google login token, so the network is the remaining way to leak it. The jail gets only its own loopback. Its single route out is an HTTPS `CONNECT` proxy outside the jail, reached through a - bind-mounted Unix socket, which tunnels only to port 443 of hosts that + bind-mounted Unix socket, which accepts only port 443 of hosts that **exactly** match `AGY_EGRESS_ALLOW`. Wildcards are rejected, because `.googleapis.com` would include Cloud Storage, where anyone can own a writable - bucket. One host needs more than that: `www.googleapis.com` serves both the - userinfo call agy makes at startup and the Cloud Storage JSON API. So the - proxy terminates TLS for that host only, with a per-run CA whose private key - never enters the jail, and forwards only a body-less `GET /oauth2/v2/userinfo` - (exact path, no query), which it rebuilds itself. It sets its own `Host` - header, because Google's front end routes by `Host` and a forwarded one could - front to Cloud Storage. It also copies only a short header allowlist, and - refuses bare CR or LF, control bytes, obs-fold and duplicate or foreign `Host` - headers. Verified from inside the jail: Cloud Storage uploads and reads - through `www.googleapis.com` (including path-traversal, encoded-path and - HTTP/2 variants), `storage.googleapis.com`, any other host or port, direct - connections, raw TCP and DNS are all refused, while a full review completes. - The job log reports egress verdict **counts** only, because a denied host name - or path is attacker-chosen and could itself carry a secret into a public log. - Residual risk: the allowed Gemini backends and the token endpoint can still be - reached, but data sent there goes to Google under the reviewer's own account, - not to an attacker. + bucket. + + An exact host list is not enough on its own: Google's front end routes by the + `Host` header on any googleapis connection, so a request to an allowed host + carrying `Host: storage.googleapis.com` reaches Cloud Storage (verified + through `oauth2`, `aicode` and `daily-cloudcode-pa`). So the proxy terminates + TLS for **every** allowed host, with a per-run CA whose private key never + enters the jail, and carries exactly one HTTP/1.1 request per connection, + which it validates strictly and rebuilds. It sets its own `Host` header and + refuses a missing, duplicate or foreign one, an absolute-form target, bare CR + or LF, control bytes and obs-fold. It forwards the body exactly once (one + `Content-Length`, or `chunked` parsed chunk by chunk; both, or any other + coding, is refused) and never forwards bytes after it, so nothing can be + smuggled behind the request. It sends `Connection: close` and streams the + response back unchanged, so server-sent events keep working. + + A host in `AGY_EGRESS_PATH_RULES` accepts only a body-less GET of exactly that + path, with no query, matched literally. The default keeps + `www.googleapis.com`, which also serves the Cloud Storage JSON API, to the + `/oauth2/v2/userinfo` call agy makes at startup. Verified from inside the + jail: fronting through all four allowed hosts, Cloud Storage uploads and + reads, `storage.googleapis.com`, any other host or port, direct connections, + raw TCP and DNS are all refused, while a full review completes. The job log + reports egress verdict **counts** only, because a denied host name or path is + attacker-chosen and could itself carry a secret into a public log. Residual + risk: the allowed Gemini backends and the token endpoint can still be reached, + but data sent there goes to Google under the reviewer's own account, not to an + attacker. The proxy needs Python 3.11 or later. + **If reviews start failing after an agy update**, the new version probably needs a host that is not on the list. The job log shows the egress counts. Denied host names never appear there; they go to `~/.gemini/antigravity-cli/agy-egress-denied.log` on the runner host (mode 600, beside agy's own state). Add a needed host to `AGY_EGRESS_ALLOW`, which - takes exact names only. If the host also serves storage or another API, - path-filter it through `AGY_EGRESS_INTERCEPT_HOST` and - `AGY_EGRESS_INTERCEPT_PATH` instead. + takes exact names only, and add a path rule for it too if it also serves + storage or another API. +- **Credential-shaped output is redacted:** before posting, agy's output is + scanned for Google OAuth tokens, GitHub tokens, private keys, JWTs, and AWS, + Anthropic, OpenAI and Slack keys. Each match is replaced with `[REDACTED: + ]` and the comment says that something was redacted; the review is still + posted. The scan cannot tell a leaked secret from a sample a PR adds (a + test-fixture JWT), so a redaction note on a PR that adds sample tokens is + expected. If redaction cannot remove every match, nothing is posted. A + credential-shaped tail of agy's stderr is withheld from the job log entirely. + The scan is a backstop: an injected prompt could encode a token so it does not + match, which is why the jail and the egress filter are the real boundary. - **agy never sees the checkout:** agy runs with `--dangerously-skip-permissions` and reads an untrusted diff, so a prompt injection could try to write files. It is started from a private, empty `mktemp -d` sandbox under `$RUNNER_TEMP` @@ -359,7 +380,7 @@ disable fork workflows there or gate them the same way. | `AGY_ISOLATION` | `bwrap` | `bwrap` runs agy in the jail described under the security model; `none` runs it unjailed (not recommended) | | `AGY_EGRESS` | `filtered` | `filtered` gives the jail no network except the allowlisting proxy; `open` keeps the host network (not recommended) | | `AGY_EGRESS_ALLOW` | the 4 hosts agy needs | space-separated EXACT host names the proxy will tunnel to on port 443; wildcards and suffixes are rejected | -| `AGY_EGRESS_INTERCEPT_HOST` / `_PATH` | `www.googleapis.com` / `/oauth2/v2/userinfo` | the one host whose TLS is terminated so that only body-less GETs fully matching the path regex are forwarded | +| `AGY_EGRESS_PATH_RULES` | `www.googleapis.com=/oauth2/v2/userinfo` | space-separated `host=/exact/path` entries; such a host accepts only a body-less GET of exactly that path (no query, matched literally). Every allowed host is TLS-intercepted and gets its `Host` header rebuilt, whether or not it has a rule | | `AGY_EGRESS_DENIED_LOG` | `~/.gemini/antigravity-cli/agy-egress-denied.log` | host-private (mode 600) log of denied egress host names, for diagnosing an agy update; never printed to the job log | | `AGY_KEYRING_ATTRS` | `username=antigravity service=gemini` | Secret Service attributes of agy's own login item; the jail's D-Bus proxy allows `GetSecret` on the matching item(s) only | | `AGY_ENV_PASSTHROUGH` | *(empty)* | extra environment variable NAMES (space-separated) to pass to agy on top of the session allowlist; everything else is withheld | diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index 004cf341..85b9664c 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -799,31 +799,116 @@ check "the CA and leaf keys are never bound into the jail" "0" \ "$(grep -E -- '--(ro-)?bind[^)]*(pki|ca\.key|leaf\.key)' "$SCRIPT" | grep -vc '^ *#')" check "egress needs socat/python3/openssl or fails closed" "1" \ "$(grep -c '\[ "\$AGY_EGRESS" = filtered \] && _need+=( socat python3 openssl )' "$SCRIPT")" +check "egress needs python3 >= 3.11 or fails closed" "1" \ + "$(grep -c "sys.exit(sys.version_info < (3, 11))" "$SCRIPT")" +check "the bridge wrapper refuses to launch agy when the bridge is down" "1" \ + "$(grep -c 'agy-jail: the egress bridge did not start' "$SCRIPT")" +check "path rules must name an allowlisted host" "1" "$(grep -c 'which is not in AGY_EGRESS_ALLOW' "$SCRIPT")" +check "the leaf certificate covers every allowlisted host" "1" "$(grep -c '_san="DNS:\${_allow//,/,DNS:}"' "$SCRIPT")" check "the job log prints egress verdict counts, never names" "1" \ "$(grep -c "awk '{print \$1}' \"\$agy_jail_rt/egress.log\"" "$SCRIPT")" proxy_py="$TMPD/egress.py" sed -n "/^ cat <<'AGYPY'$/,/^AGYPY$/p" "$SCRIPT" | sed '1d;$d' > "$proxy_py" check "the embedded egress proxy compiles" "0" \ "$(python3 -I -m py_compile "$proxy_py" >/dev/null 2>&1; echo $?)" -if command -v python3 >/dev/null 2>&1 && command -v curl >/dev/null 2>&1; then - # Unix socket paths are capped at 108 bytes, so the sockets live in a short dir, not under TMPD. +# The egress proxy, exercised offline over real TLS (round 6). EVERY allowlisted host is +# TLS-terminated and each request is rebuilt, because Google's front end routes by Host on any +# googleapis connection (fronting to Cloud Storage was verified through oauth2, aicode and +# daily-cloudcode-pa). Every refusal below happens before any upstream connection, so no network +# is needed. A host that has python3 and openssl must run these: a certificate failure is a FAIL. +if command -v python3 >/dev/null 2>&1 && command -v openssl >/dev/null 2>&1; then + # Unix socket paths are capped at 108 bytes, so the socket lives in a short dir, not under TMPD. sockd="$(mktemp -d "${XDG_RUNTIME_DIR:-/tmp}/agyst.XXXXXX")" - px_sock="$sockd/e.sock"; px_log="$TMPD/egress.log"; : > "$px_log" - python3 -I "$proxy_py" "$px_sock" "$px_log" "allowed.example" & - px_pid=$! - for _ in $(seq 1 50); do [ -S "$px_sock" ] && break; sleep 0.1; done - px() { curl -s -m 5 -o /dev/null -w '%{http_code}' --unix-socket "$px_sock" -X CONNECT \ - --request-target "$1" "http://proxy/" 2>/dev/null; } - check "proxy refuses an unlisted host" "403" "$(px 'secret-token-in-name.evil.example:443')" - check "proxy refuses a suffix of an allowed host" "403" "$(px 'x.allowed.example:443')" - check "proxy refuses an allowed host on another port" "403" "$(px 'allowed.example:80')" - check "proxy refuses plain-HTTP proxying" "405" \ - "$(curl -s -m 5 -o /dev/null -w '%{http_code}' --unix-socket "$px_sock" http://allowed.example/ 2>/dev/null)" - kill "$px_pid" 2>/dev/null; wait "$px_pid" 2>/dev/null || true # 143 from the kill is expected - check "proxy never logs a denied host name" "0" "$(grep -c 'evil' "$px_log")" - check "proxy logged all three denials" "3" "$(grep -c '^DENY' "$px_log")" - check "a denial names only an allowlisted host, if any" "0" \ - "$(grep '^DENY ' "$px_log" | grep -vcx 'DENY allowed.example')" + ip="$TMPD/icpt"; mkdir -p "$ip" + certs_ok=no + if { openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 1 \ + -subj "/CN=selftest CA" -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,keyCertSign" -keyout "$ip/ca.key" -out "$ip/ca.pem" \ + && openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=selftest" \ + -keyout "$ip/leaf.key" -out "$ip/leaf.csr" \ + && openssl x509 -req -in "$ip/leaf.csr" -CA "$ip/ca.pem" -CAkey "$ip/ca.key" -days 1 \ + -extfile <(printf 'subjectAltName=DNS:allowed.example,DNS:paths.example\nextendedKeyUsage=serverAuth\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n') \ + -out "$ip/leaf.pem"; } >/dev/null 2>&1; then + certs_ok=yes + fi + check "the self-test can create its TLS certificates (openssl present)" "yes" "$certs_ok" + if [ "$certs_ok" = yes ]; then + px_log="$ip/log"; : > "$px_log" + python3 -I "$proxy_py" "$sockd/p.sock" "$px_log" "allowed.example,paths.example" \ + "$ip/leaf.pem" "$ip/leaf.key" "paths.example=/oauth2/v2/userinfo" 2>"$ip/err" & + px_pid=$! + for _ in $(seq 1 50); do [ -S "$sockd/p.sock" ] && break; sleep 0.1; done + cat > "$ip/client.py" <<'PYC' +import socket, ssl, sys +sock_path, ca, target, raw = sys.argv[1:5] +head = raw.encode("latin-1").decode("unicode_escape").encode("latin-1") +s = socket.socket(socket.AF_UNIX); s.settimeout(10); s.connect(sock_path) +s.sendall(f"CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n".encode()) +first = s.recv(4096).split(b"\r\n", 1)[0].split(b" ") +if len(first) < 2 or first[1] != b"200": + print(first[1].decode() if len(first) > 1 else "closed"); sys.exit() +if raw == "-": + print("200"); sys.exit() +t = ssl.create_default_context(cafile=ca).wrap_socket(s, server_hostname=target.rsplit(":", 1)[0]) +t.sendall(head) +try: + print(t.recv(4096).split(b"\r\n", 1)[0].split(b" ")[1].decode()) +except (OSError, IndexError): + print("closed") +PYC + pc() { python3 -I "$ip/client.py" "$sockd/p.sock" "$ip/ca.pem" "$1" "$2" 2>/dev/null || echo error; } + A='allowed.example:443'; H='Host: allowed.example\r\n' + check "proxy refuses an unlisted host" "403" "$(pc 'secret-token-in-name.evil.example:443' -)" + check "proxy refuses a suffix of an allowed host" "403" "$(pc 'x.allowed.example:443' -)" + check "proxy refuses an allowed host on another port" "403" "$(pc 'allowed.example:80' -)" + check "fronting refused: foreign Host on an allowed connection" "403" \ + "$(pc "$A" 'GET /storage/v1/b/x HTTP/1.1\r\nHost: storage.googleapis.com\r\n\r\n')" + check "fronting refused: bucket subdomain Host" "403" \ + "$(pc "$A" 'GET /p?t=secret HTTP/1.1\r\nHost: evil-bucket.storage.googleapis.com\r\n\r\n')" + check "duplicate Host refused" "403" "$(pc "$A" "GET / HTTP/1.1\\r\\n${H}Host: storage.googleapis.com\\r\\n\\r\\n")" + check "missing Host refused" "403" "$(pc "$A" 'GET / HTTP/1.1\r\n\r\n')" + check "absolute-form target refused" "403" \ + "$(pc "$A" "GET https://storage.googleapis.com/x HTTP/1.1\\r\\n${H}\\r\\n")" + check "Content-Length with Transfer-Encoding refused" "403" \ + "$(pc "$A" "POST / HTTP/1.1\\r\\n${H}Content-Length: 3\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n")" + check "a transfer coding other than chunked refused" "403" \ + "$(pc "$A" "POST / HTTP/1.1\\r\\n${H}Transfer-Encoding: gzip, chunked\\r\\n\\r\\n")" + check "conflicting Content-Length values refused" "403" \ + "$(pc "$A" "POST / HTTP/1.1\\r\\n${H}Content-Length: 3\\r\\nContent-Length: 4\\r\\n\\r\\n")" + check "bare LF inside the head refused (smuggling)" "403" \ + "$(pc "$A" "GET / HTTP/1.1\\r\\n${H}X-A: 1\\nHost: storage.googleapis.com\\r\\n\\r\\n")" + check "obs-fold refused" "403" "$(pc "$A" "GET / HTTP/1.1\\r\\n${H}X-A: 1\\r\\n folded\\r\\n\\r\\n")" + check "control byte refused" "403" "$(pc "$A" "GET / HTTP/1.1\\r\\n${H}X-A: a\\x01b\\r\\n\\r\\n")" + check "HTTP/1.0 refused" "403" "$(pc "$A" "GET / HTTP/1.0\\r\\n${H}\\r\\n")" + P='paths.example:443'; PH='Host: paths.example\r\n' + check "path rule: a query string is refused" "403" \ + "$(pc "$P" "GET /oauth2/v2/userinfo?x=secret HTTP/1.1\\r\\n${PH}\\r\\n")" + check "path rule: another path is refused" "403" "$(pc "$P" "GET /storage/v1/b/x HTTP/1.1\\r\\n${PH}\\r\\n")" + check "path rule: a POST to the allowed path is refused" "403" \ + "$(pc "$P" "POST /oauth2/v2/userinfo HTTP/1.1\\r\\n${PH}Content-Length: 1\\r\\n\\r\\n")" + check "path rule: the path is literal, not a regex" "403" \ + "$(pc "$P" "GET /oauth2/v2/userinfoX HTTP/1.1\\r\\n${PH}\\r\\n")" + kill "$px_pid" 2>/dev/null; wait "$px_pid" 2>/dev/null || true # 143 from the kill is expected + check "proxy never logs a denied host name" "0" "$(grep -c 'evil' "$px_log")" + check "every denial is logged by verdict" "yes" \ + "$([ "$(grep -cE '^DENY' "$px_log")" -ge 17 ] && echo yes || echo no)" + # rebuild_request, unit level: Host set by the proxy, hop-by-hop dropped, framing canonical. + rb="$(python3 -I - "$proxy_py" "$ip/leaf.pem" "$ip/leaf.key" <<'PYR' 2>/dev/null +import sys +src = open(sys.argv[1]).read().split("\nasyncio.run(main())", 1)[0] +sys.argv = ["x", "/dev/null", "/dev/null", "allowed.example", sys.argv[2], sys.argv[3], ""] +ns = {"__name__": "agy_egress_test"} +exec(compile(src, "proxy", "exec"), ns) +head = (b"POST /v1/x HTTP/1.1\r\nHost: allowed.example\r\nAuthorization: Bearer t\r\n" + b"Connection: keep-alive\r\nUpgrade: h2c\r\nTransfer-Encoding: chunked\r\nX-Goog-Api-Client: a\r\n\r\n") +out, kind, n = ns["rebuild_request"](head, "allowed.example") +print(kind + "|" + "|".join(out.decode().split("\r\n"))) +PYR +)" || rb="(rebuild_request missing or failed)" + check "the rebuilt request sets Host itself, drops hop-by-hop headers, keeps chunked framing" \ + "chunked|POST /v1/x HTTP/1.1|Host: allowed.example|Authorization: Bearer t|X-Goog-Api-Client: a|Transfer-Encoding: chunked|Connection: close||" "$rb" + fi + rm -rf -- "$sockd" fi # A jail launch diagnostic is never accepted as a review (Codex P2), and cleanup survives a dead proxy. jf="$TMPD/jail-fail.txt" @@ -864,76 +949,25 @@ check "denied-host log is mode 600" "600" "$(stat -c %a "$ddst" 2>/dev/null || e agy_record_denied "$dsrc" "$ddst" "o/r#2" check "denied-host log appends on a later run" "4" "$(wc -l < "$ddst" 2>/dev/null || echo 0)" for _ in $(seq 1 300); do agy_record_denied "$dsrc" "$ddst" "o/r#n"; done -check "denied-host log stays bounded" "yes" "$([ "$(wc -l < "$ddst")" -le 500 ] && echo yes || echo no)" -# The intercepted host: the proxy must REBUILD the request (round 5, commit security review). -# Every case below is refused before any upstream connection, so this runs offline over real TLS. -if command -v python3 >/dev/null 2>&1 && command -v openssl >/dev/null 2>&1; then - ip="$TMPD/icpt"; mkdir -p "$ip" - if { openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 1 \ - -subj "/CN=selftest CA" -addext "basicConstraints=critical,CA:TRUE" \ - -addext "keyUsage=critical,keyCertSign" -keyout "$ip/ca.key" -out "$ip/ca.pem" \ - && openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=allowed.example" \ - -keyout "$ip/leaf.key" -out "$ip/leaf.csr" \ - && openssl x509 -req -in "$ip/leaf.csr" -CA "$ip/ca.pem" -CAkey "$ip/ca.key" -days 1 \ - -extfile <(printf 'subjectAltName=DNS:allowed.example\nextendedKeyUsage=serverAuth\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n') \ - -out "$ip/leaf.pem"; } >/dev/null 2>&1; then - python3 -I "$proxy_py" "$sockd/i.sock" "$ip/log" "allowed.example" \ - "allowed.example" "/oauth2/v2/userinfo" "$ip/leaf.pem" "$ip/leaf.key" & - ip_pid=$! - for _ in $(seq 1 50); do [ -S "$sockd/i.sock" ] && break; sleep 0.1; done - cat > "$ip/client.py" <<'PYC' -import socket, ssl, sys -sock_path, ca, head = sys.argv[1], sys.argv[2], sys.argv[3].encode("latin-1").decode("unicode_escape").encode("latin-1") -s = socket.socket(socket.AF_UNIX); s.settimeout(10); s.connect(sock_path) -s.sendall(b"CONNECT allowed.example:443 HTTP/1.1\r\nHost: allowed.example:443\r\n\r\n") -if b" 200 " not in s.recv(4096): - print("no-tunnel"); sys.exit() -ctx = ssl.create_default_context(cafile=ca) -t = ctx.wrap_socket(s, server_hostname="allowed.example") -t.sendall(head) -try: - print(t.recv(4096).split(b"\r\n", 1)[0].split(b" ")[1].decode()) -except (OSError, IndexError): - print("closed") -PYC - ic() { python3 -I "$ip/client.py" "$sockd/i.sock" "$ip/ca.pem" "$1" 2>/dev/null || echo error; } - H='Host: allowed.example\r\n' - check "intercept refuses a foreign Host (fronting to another Google service)" "403" \ - "$(ic 'GET /oauth2/v2/userinfo HTTP/1.1\r\nHost: bucket.storage.googleapis.com\r\n\r\n')" - check "intercept refuses a duplicate Host" "403" \ - "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}Host: evil.example\\r\\n\\r\\n")" - check "intercept refuses a missing Host" "403" "$(ic 'GET /oauth2/v2/userinfo HTTP/1.1\r\n\r\n')" - check "intercept refuses a query string (a data channel)" "403" \ - "$(ic "GET /oauth2/v2/userinfo?x=secret HTTP/1.1\\r\\n${H}\\r\\n")" - check "intercept refuses another path" "403" "$(ic "GET /storage/v1/b/x HTTP/1.1\\r\\n${H}\\r\\n")" - check "intercept refuses an absolute-form target" "403" \ - "$(ic "GET https://storage.googleapis.com/oauth2/v2/userinfo HTTP/1.1\\r\\n${H}\\r\\n")" - check "intercept refuses a bare LF inside the head (smuggling)" "403" \ - "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}X-A: 1\\nHost: evil.example\\r\\n\\r\\n")" - check "intercept refuses obs-fold" "403" "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}X-A: 1\\r\\n folded\\r\\n\\r\\n")" - check "intercept refuses a control byte" "403" "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}X-A: a\\x01b\\r\\n\\r\\n")" - check "intercept refuses a request body" "403" \ - "$(ic "GET /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}Content-Length: 5\\r\\n\\r\\n")" - check "intercept refuses a non-GET method" "403" "$(ic "POST /oauth2/v2/userinfo HTTP/1.1\\r\\n${H}\\r\\n")" - kill "$ip_pid" 2>/dev/null; wait "$ip_pid" 2>/dev/null || true # 143 from the kill is expected - fi -fi -[ -n "${sockd:-}" ] && rm -rf -- "$sockd" -# rebuild_request, unit level: the upstream head is built by the proxy, never copied. -rb="$(python3 -I - "$proxy_py" <<'PYR' 2>/dev/null -import importlib.util, sys -src = open(sys.argv[1]).read().split("\nasyncio.run(main())", 1)[0] -ns = {"__name__": "agy_egress_test"} -sys.argv = ["x", "/dev/null", "/dev/null", "", "www.googleapis.com", "/oauth2/v2/userinfo", "", ""] -code = src.replace(' server_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n server_ctx.load_cert_chain(sys.argv[6], sys.argv[7])\n', ' server_ctx = None\n') -exec(compile(code.replace(" server_ctx.set_alpn_protocols", " pass #"), "proxy", "exec"), ns) -head = b"GET /oauth2/v2/userinfo HTTP/1.1\r\nHost: www.googleapis.com\r\nAuthorization: Bearer t\r\nX-Exfil: data\r\nUser-Agent: agy\r\n\r\n" -out = ns["rebuild_request"](head, "www.googleapis.com").decode() -print("|".join(out.split("\r\n"))) -PYR -)" || rb="(rebuild_request missing or failed)" -check "the rebuilt request sets Host itself and drops unlisted headers" \ - "GET /oauth2/v2/userinfo HTTP/1.1|Host: www.googleapis.com|Authorization: Bearer t|User-Agent: agy|Connection: close||" "$rb" +check "denied-host log keeps exactly the newest 500 records" "500" "$(wc -l < "$ddst")" +check "the newest record survives trimming" "yes" "$(tail -n 1 "$ddst" | grep -q 'o/r#n other.example:443' && echo yes || echo no)" +# Redaction (redact-and-post): every positive shape is fully redacted, boundaries survive, and a +# fixture-style JWT in an otherwise ordinary review leaves the rest of the text intact. +rd="$TMPD/redact.txt" +s_jwt2="eyJ""hbGciOiJIUzI1NiJ9.""eyJ""zdWIiOiIxMjM0NTY3ODkwIn0.abcdefghijklmnop" +printf '## Review\n\nThe fixture (%s) in tests/auth.rs is fine.\nKeep this line.\n' "$s_jwt2" > "$rd" +agy_redact_credentials "$rd" +check "a fixture JWT is redacted, not fatal" "yes" "$(grep -q '(\[REDACTED: jwt\]) in tests/auth.rs is fine.' "$rd" && echo yes || echo no)" +check "redaction leaves the rest of the review intact" "yes" "$(grep -qx 'Keep this line.' "$rd" && echo yes || echo no)" +printf 'one\n-----BEGIN OPENSSH ''PRIVATE KEY-----\nAAAAB3NzaC1yc2E\nmore-key-body\n-----END OPENSSH ''PRIVATE KEY-----\ntwo\n' > "$rd" +agy_redact_credentials "$rd" +check "a private-key block is redacted whole, body lines included" "one|[REDACTED: private-key-block]|two" "$(paste -sd'|' "$rd")" +printf 'keys %s.%s and %s\n' "AKI""AABCDEFGHIJKLMNOP" "AKI""AQRSTUVWXYZ234567" "gh""p_$(printf 'c%.0s' {1..36})" > "$rd" +agy_redact_credentials "$rd" +check "adjacent matches are all redacted, boundaries kept" "keys [REDACTED: aws-access-key-id].[REDACTED: aws-access-key-id] and [REDACTED: github-token]" "$(cat "$rd")" +check "the capture loop redacts instead of failing" "1" \ + "$(grep -c '^ if ! agy_redact_credentials "\$out_file" || left="\$(credential_kind_present "\$out_file")"; then' "$SCRIPT")" +check "a redacted review says so in the comment" "1" "$(grep -c 'credential-shaped strings were redacted from this review before posting' "$SCRIPT")" # Credential scan: every shape is caught, ordinary review text is not. cred_tmp="$TMPD/cred.txt" # Samples are assembled at runtime from split pieces, so this file never contains a literal that a @@ -948,6 +982,9 @@ for sample in "token ya2""9.$(printf 'a%.0s' {1..30})" "refresh 1/""/0$(printf ' printf '## Review\n\nfound %s here\n' "$sample" > "$cred_tmp" check "credential scan catches: ${sample:0:14}..." "yes" \ "$(credential_kind_present "$cred_tmp" >/dev/null && echo yes || echo no)" + agy_redact_credentials "$cred_tmp" + check "redaction removes it entirely: ${sample:0:14}..." "no" \ + "$(credential_kind_present "$cred_tmp" >/dev/null && echo yes || echo no)" done # No false positives on ordinary identifiers that merely CONTAIN a token prefix. for benign in "task-$(printf 'g%.0s' {1..40})" "disk-$(printf 'h%.0s' {1..40})" \ diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index 75a20084..e37ce70d 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -161,7 +161,7 @@ agy_record_denied() { ( umask 077 { - if [ -f "$dst" ]; then tail -n 400 "$dst"; fi + if [ -f "$dst" ]; then cat "$dst"; fi sort -u "$src" | cut -c1-253 | sed "s|^|${stamp} ${tag} |" } > "$dst.new" || exit 1 tail -n 500 "$dst.new" > "$dst.tmp" && mv -f "$dst.tmp" "$dst" && rm -f -- "$dst.new" @@ -182,25 +182,53 @@ agy_jail_failed() { # tool and a shell `cat`), so a prompt-injected diff could make it print a token from the runner # host. Fail closed on any match in agy's output. The log names only the KIND that matched, never # the value, since Actions logs of a public repository are public too. +# One table for detection AND redaction (`~`-separated, a non-whitespace IFS so empty fields +# survive: kind, leading boundary, core, trailing +# boundary), so the two can never drift apart. The boundaries keep an ordinary identifier +# (`task-...`, a word ending in `ghp`) from matching. +agy_credential_patterns() { + cat <<'CREDS' +google-oauth-access-token~(^|[^A-Za-z0-9_-])~ya29\.[0-9A-Za-z_-]{20,}~ +google-oauth-refresh-token~(^|[^A-Za-z0-9_/-])~1//0[0-9A-Za-z_-]{20,}~ +github-token~(^|[^A-Za-z0-9_])~gh[pousr]_[A-Za-z0-9]{30,}~ +github-fine-grained-pat~(^|[^A-Za-z0-9_])~github_pat_[A-Za-z0-9_]{40,}~ +private-key-block~~-----BEGIN [A-Z ]*PRIVATE KEY-----~ +jwt~(^|[^A-Za-z0-9_-])~eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}~ +aws-access-key-id~(^|[^A-Za-z0-9])~(AKIA|ASIA)[0-9A-Z]{16}~([^A-Za-z0-9]|$) +anthropic-key~(^|[^A-Za-z0-9_-])~sk-ant-[A-Za-z0-9_-]{32,}~ +openai-key~(^|[^A-Za-z0-9_-])~sk-(proj-)?[A-Za-z0-9]{32,}~([^A-Za-z0-9_-]|$) +slack-token~(^|[^A-Za-z0-9_-])~xox[abprs]-[A-Za-z0-9-]{10,}~ +CREDS +} credential_kind_present() { [ -s "$1" ] || return 1 - local kind re - while IFS='|' read -r kind re; do - if grep -qE -- "$re" "$1"; then printf '%s' "$kind"; return 0; fi - done <<'CREDS' -google-oauth-access-token|(^|[^A-Za-z0-9_-])ya29\.[0-9A-Za-z_-]{20,} -google-oauth-refresh-token|(^|[^A-Za-z0-9_/-])1//0[0-9A-Za-z_-]{20,} -github-token|(^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{30,} -github-fine-grained-pat|(^|[^A-Za-z0-9_])github_pat_[A-Za-z0-9_]{40,} -private-key-block|-----BEGIN [A-Z ]*PRIVATE KEY----- -jwt|(^|[^A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,} -aws-access-key-id|(^|[^A-Za-z0-9])(AKIA|ASIA)[0-9A-Z]{16}([^A-Za-z0-9]|$) -anthropic-key|(^|[^A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{32,} -openai-key|(^|[^A-Za-z0-9_-])sk-(proj-)?[A-Za-z0-9]{32,}([^A-Za-z0-9_-]|$) -slack-token|(^|[^A-Za-z0-9_-])xox[abprs]-[A-Za-z0-9-]{10,} -CREDS + local kind lead core trail + while IFS='~' read -r kind lead core trail; do + if grep -qE -- "${lead}${core}${trail}" "$1"; then printf '%s' "$kind"; return 0; fi + done < <(agy_credential_patterns) return 1 } +# Replace every credential-shaped string in $1 (in place) with `[REDACTED: ]`, keeping the +# boundary characters. A private-key block is replaced whole, from its BEGIN line through its END +# line (or to the end of the text, which fails safe). Several passes, because adjacent matches +# can share a boundary character. The caller re-scans and fails closed on anything left. +agy_redact_credentials() { + local f="$1" kind lead core trail groups n pass + local tmp="$1.redact" # a sibling of the capture, removed below + for pass in 1 2 3; do + while IFS='~' read -r kind lead core trail; do + if [ "$kind" = private-key-block ]; then + sed -E "/${core}/,/-----END [A-Z ]*PRIVATE KEY-----/c\\[REDACTED: ${kind}]" "$f" > "$tmp" || return 1 + else + groups="${core//[^(]/}"; n=$(( 2 + ${#groups} )) + sed -E "s#${lead:-()}${core}${trail:-()}#\\1[REDACTED: ${kind}]\\${n}#g" "$f" > "$tmp" || return 1 + fi + cat "$tmp" > "$f" + done < <(agy_credential_patterns) + : "$pass" + done + rm -f -- "$tmp" +} # <<< SELFTEST-EXTRACT # --- configuration (all env-overridable from the workflow) --------------------- @@ -311,13 +339,13 @@ case "$AGY_EGRESS" in filtered|open) ;; *) echo "AGY_EGRESS must be filtered or # userinfo eligibility check. Telemetry, the avatar host and the auto-updater are left out (agy # works without them). AGY_EGRESS_ALLOW="${AGY_EGRESS_ALLOW:-daily-cloudcode-pa.googleapis.com aicode.googleapis.com oauth2.googleapis.com www.googleapis.com}" -# www.googleapis.com ALSO serves the Cloud Storage JSON API (verified: an upload to a nonexistent -# bucket there answers "The specified bucket does not exist"), so that host is TLS-intercepted and -# only this path is forwarded, as a body-less GET that the proxy REBUILDS (its own Host header, a -# short header allowlist): forwarding the client's Host would let it front to any Google service. -AGY_EGRESS_INTERCEPT_HOST="${AGY_EGRESS_INTERCEPT_HOST:-www.googleapis.com}" -# Exact path, no query: agy sends none (verified), and a query string is a data channel. -AGY_EGRESS_INTERCEPT_PATH="${AGY_EGRESS_INTERCEPT_PATH:-/oauth2/v2/userinfo}" +# Every allowlisted host is TLS-intercepted and each request is REBUILT with the proxy's own Host +# header: Google's front end routes by Host on ANY googleapis connection (verified: a request to +# oauth2, aicode or daily-cloudcode-pa carrying `Host: storage.googleapis.com` reaches Cloud +# Storage). A host listed here additionally accepts only a body-less GET of exactly this path (no +# query; matched literally): www.googleapis.com also serves the Cloud Storage JSON API, and agy +# needs only its userinfo call there. Entries are `host=/path`, space-separated. +AGY_EGRESS_PATH_RULES="${AGY_EGRESS_PATH_RULES:-www.googleapis.com=/oauth2/v2/userinfo}" AGY_DIFF_MODE="${AGY_DIFF_MODE:-auto}" # auto|inline|file. A diff is passed to agy either inlined # in the --print prompt, or written to a FILE agy reads with # its own tools. `auto` inlines a diff that fits under the @@ -431,7 +459,7 @@ REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY not set}" # _perm_err so cleanup() could never see it (agy review, GH-ListRollup PR #6). # Remove every temp file on exit. Pre-declared so the trap is safe under `set -u` even if the # script exits before a given file is created. -diff_file= diff_err= meta_file= prompt_file= out_file= raw= body_file= agy_diff_file= agy_sandbox= agy_jail_home= agy_jail_rt= agy_proxy_pid= agy_egress_pid= jq_err= log_tail= prior_body_file= archived_file= api_err= +diff_file= diff_err= meta_file= prompt_file= out_file= raw= body_file= agy_diff_file= agy_sandbox= agy_jail_home= agy_jail_rt= agy_proxy_pid= agy_egress_pid= jq_err= log_tail= redacted_kinds= left= prior_body_file= archived_file= api_err= # Also created mid-flight (permission lookup, compare-API merge base, archive trimming); a signal # or abort while one of those commands runs would otherwise leak the file in /tmp. _perm_err='' compare_err='' trimmed='' @@ -1182,20 +1210,32 @@ while IFS= read -r -d '' arg; do agy_env+=( "$arg" ); done < <(agy_allowlisted_e # set stays the same in every repository). The self-test extracts and exercises it. agy_egress_proxy_src() { cat <<'AGYPY' -"""agy-review egress proxy: the jail's only route to the network (stdlib only). - -Serves HTTP CONNECT on a Unix socket that is bind-mounted into the jail. A tunnel is opened only -to port 443 of a host that EXACTLY equals an allowlist entry (no wildcards, no suffixes: a -wildcard such as .googleapis.com would include Cloud Storage, where anyone can own a bucket). -One host may be intercepted: TLS is terminated with a per-run leaf certificate the jail trusts -(the CA key never enters the jail) and only body-less HTTP/1.1 GETs whose path fully matches a -regex are forwarded, one request per connection. This exists because www.googleapis.com serves -both the userinfo call agy needs and the Cloud Storage JSON API. +"""agy-review egress proxy: the jail's only route to the network (stdlib only, Python >= 3.11). + +Serves HTTP CONNECT on a Unix socket that is bind-mounted into the jail. A CONNECT is accepted only +for port 443 of a host that EXACTLY equals an allowlist entry (no wildcards: `.googleapis.com` +would include Cloud Storage, where anyone can own a writable bucket). + +Every accepted tunnel is TLS-terminated with a per-run leaf certificate the jail trusts (the CA key +never enters the jail). A raw tunnel is not enough: Google's front end routes by the Host header, +so a request on a connection to ANY allowed googleapis host that says `Host: storage.googleapis.com` +reaches Cloud Storage (verified for oauth2, aicode and daily-cloudcode-pa). So each connection +carries exactly one HTTP/1.1 request, which the proxy validates strictly and REBUILDS: + * Host is set by the proxy to the CONNECT host; a missing, duplicate or foreign Host is refused; + * only origin-form targets; bare CR/LF, control bytes, DEL, non-ASCII, obs-fold and non-token + header names are refused; + * the body is forwarded exactly once: one Content-Length (that many bytes), or Transfer-Encoding + exactly `chunked` (parsed chunk by chunk); both, or any other coding, is refused. Bytes after + the request are never forwarded, so nothing can be smuggled behind it; + * hop-by-hop headers are dropped and `Connection: close` is sent, so upstream closes after one + response, which is streamed back unchanged (server-sent events keep working). +A host with a path rule accepts only body-less GETs of exactly that path (no query). The log records verdicts and allowlisted host names only. A denied host name or any path is -attacker-chosen and could carry a secret, so neither is ever written anywhere. +attacker-chosen and could carry a secret, so neither is written to it. Denied CONNECT targets go +to the private file named by AGY_EGRESS_DENIED_FILE (outside the jail, never the job log). -argv: SOCKET LOG ALLOW_CSV [INTERCEPT_HOST PATH_REGEX CERT KEY] +argv: SOCKET LOG ALLOW_CSV CERT KEY [PATH_RULES] PATH_RULES: "host=/exact/path,host2=/p" """ import asyncio @@ -1205,24 +1245,48 @@ import re import ssl import sys -sock_path, log_path, allow_csv = sys.argv[1], sys.argv[2], sys.argv[3] +sock_path, log_path, allow_csv, cert, key = sys.argv[1:6] allow = {h for h in allow_csv.split(",") if h} -icpt_host = sys.argv[4] if len(sys.argv) > 4 else "" -icpt_path = re.compile(sys.argv[5]) if icpt_host else None -server_ctx = None -if icpt_host: - server_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) - server_ctx.load_cert_chain(sys.argv[6], sys.argv[7]) - server_ctx.set_alpn_protocols(["http/1.1"]) +path_rules = {} +for rule in (sys.argv[6] if len(sys.argv) > 6 else "").split(","): + if rule: + rule_host, _, rule_path = rule.partition("=") + path_rules[rule_host] = rule_path +server_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) +server_ctx.load_cert_chain(cert, key) +server_ctx.set_alpn_protocols( + ["http/1.1"] +) # one HTTP/1.1 request per connection, never h2 upstream_ctx = ssl.create_default_context() logf = open(log_path, "a", buffering=1) # noqa: SIM115 - lives as long as the process -# Private file OUTSIDE the jail for denied names (never the public job log). denied_path = os.environ.get("AGY_EGRESS_DENIED_FILE", "") deniedf = open(denied_path, "a", buffering=1) if denied_path else None # noqa: SIM115 +TOKEN = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+") +HOP_BY_HOP = { + "connection", + "keep-alive", + "proxy-connection", + "proxy-authorization", + "proxy-authenticate", + "te", + "trailer", + "upgrade", + "host", + "content-length", + "transfer-encoding", +} +METHODS = {"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"} +MAX_HEAD = 65536 +MAX_CHUNK_LINE = 4096 + + +class Refuse(Exception): + """The request is refused (403); the reason is never echoed anywhere.""" + def log(verdict, host=""): - logf.write(f"{verdict} {host if host in allow else ''}\n".rstrip() + "\n") + logf.write(f"{verdict} {host if host in allow else ''}".rstrip() + "\n") def close(w): @@ -1230,17 +1294,6 @@ def close(w): w.close() -async def pipe(r, w): - try: - while data := await r.read(65536): - w.write(data) - await w.drain() - except (ConnectionError, OSError, asyncio.IncompleteReadError): - pass - finally: - close(w) - - async def refuse(cw, status): with contextlib.suppress(OSError, RuntimeError): cw.write(status + b"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") @@ -1248,153 +1301,204 @@ async def refuse(cw, status): close(cw) -async def read_head(cr): - return await asyncio.wait_for(cr.readuntil(b"\r\n\r\n"), 30) - - -async def handle(cr, cw): - try: - head = await read_head(cr) - except ( - TimeoutError, - OSError, - asyncio.IncompleteReadError, - asyncio.LimitOverrunError, - ): - close(cw) - return - parts = head.split(b"\r\n", 1)[0].decode("latin-1", "replace").split() - if len(parts) != 3 or parts[0] != "CONNECT": - log("REFUSE-NONCONNECT") - await refuse(cw, b"HTTP/1.1 405 Method Not Allowed") - return - host, _, port = parts[1].rpartition(":") - if port != "443" or host not in allow: - log("DENY", host) - if deniedf is not None: - deniedf.write(parts[1][:300].replace("\n", " ") + "\n") - await refuse(cw, b"HTTP/1.1 403 Forbidden") - return - if host == icpt_host: - await intercept(cr, cw, host) - return - try: - ur, uw = await asyncio.wait_for(asyncio.open_connection(host, 443), 30) - except (TimeoutError, OSError): - log("FAIL", host) - await refuse(cw, b"HTTP/1.1 502 Bad Gateway") - return - log("ALLOW", host) - cw.write(b"HTTP/1.1 200 Connection Established\r\n\r\n") - await cw.drain() - await asyncio.gather(pipe(cr, uw), pipe(ur, cw)) - - -TOKEN = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+") -# Only these client headers are forwarded; everything else (including the client's own Host, -# Content-Length and Transfer-Encoding) is dropped, and Host is set by the proxy. -FORWARD = ( - "authorization", - "user-agent", - "accept", - "accept-encoding", - "accept-language", -) +def clean_head(head): + """Validate a request head's bytes; return its lines (request line first).""" + if not head.endswith(b"\r\n\r\n"): + raise Refuse + body = head[:-4] + if not body.isascii(): + raise Refuse + stripped = body.replace(b"\r\n", b"") + if b"\r" in stripped or b"\n" in stripped: + raise Refuse + if any(c < 0x20 or c == 0x7F for c in stripped): + raise Refuse + return body.decode("ascii").split("\r\n") def rebuild_request(head, host): - """Return the upstream request bytes, or None to refuse. + """Return (upstream head bytes, body kind, body length) or raise Refuse. - Nothing the client wrote is forwarded verbatim: the request line is rebuilt from the - validated path, Host is the intercepted host, and only FORWARD headers are copied. + Body kind is "none", "length" or "chunked". Nothing the client wrote is forwarded verbatim. """ - if not head.endswith(b"\r\n\r\n"): - return None - body = head[:-4] - # Every line must end in CRLF: no bare CR or LF anywhere, and no other control byte or DEL. - if b"\r" in body.replace(b"\r\n", b"") or b"\n" in body.replace(b"\r\n", b""): - return None - if any((c < 0x20 and c not in (0x0D, 0x0A)) or c == 0x7F for c in body): - return None - lines = body.decode("ascii", "strict").split("\r\n") if body.isascii() else None - if not lines: - return None + lines = clean_head(head) req = lines[0].split(" ") - if len(req) != 3 or req[0] != "GET" or req[2] != "HTTP/1.1": - return None - if icpt_path is None or icpt_path.fullmatch(req[1]) is None: - return None - hosts, keep = [], [] + if len(req) != 3 or req[0] not in METHODS or req[2] != "HTTP/1.1": + raise Refuse + method, target = req[0], req[1] + if not target.startswith("/") or target.startswith("//"): + raise Refuse # origin-form only: no absolute-form or authority-form target + hosts, keep, lengths, codings = [], [], [], [] for line in lines[1:]: if not line or line[0] in " \t": - return None # empty line inside the head, or obs-fold continuation + raise Refuse # empty line inside the head, or obs-fold continuation name, sep, value = line.partition(":") if not sep or TOKEN.fullmatch(name) is None: - return None + raise Refuse lname, value = name.lower(), value.strip(" \t") if lname == "host": hosts.append(value.lower()) - elif lname in ("content-length", "transfer-encoding"): - if lname == "transfer-encoding" or value != "0": - return None - elif lname in FORWARD: + elif lname == "content-length": + lengths.append(value) + elif lname == "transfer-encoding": + codings.append(value.lower()) + elif lname not in HOP_BY_HOP: keep.append(f"{name}: {value}") if len(hosts) != 1 or hosts[0] not in (host, f"{host}:443"): - return None + raise Refuse + if lengths and codings: + raise Refuse + if codings: + if codings != ["chunked"]: + raise Refuse + kind, length = "chunked", 0 + elif lengths: + if len(set(lengths)) != 1 or not lengths[0].isdigit() or len(lengths[0]) > 15: + raise Refuse + length = int(lengths[0]) + kind = "length" if length else "none" + else: + kind, length = "none", 0 + if host in path_rules and ( + method != "GET" or target != path_rules[host] or kind != "none" + ): + raise Refuse + framing = [] + if kind == "length": + framing = [f"Content-Length: {length}"] + elif kind == "chunked": + framing = ["Transfer-Encoding: chunked"] out = [ - f"GET {req[1]} HTTP/1.1", + f"{method} {target} HTTP/1.1", f"Host: {host}", *keep, + *framing, "Connection: close", "", "", ] - return "\r\n".join(out).encode("ascii") + return "\r\n".join(out).encode("ascii"), kind, length + + +async def copy_exact(cr, uw, n): + while n > 0: + data = await cr.read(min(65536, n)) + if not data: + raise Refuse + uw.write(data) + await uw.drain() + n -= len(data) + + +async def copy_chunked(cr, uw): + while True: + line = await cr.readuntil(b"\r\n") + if len(line) > MAX_CHUNK_LINE: + raise Refuse + size_txt = line[:-2].split(b";", 1)[0].strip() + if not size_txt or not re.fullmatch(rb"[0-9A-Fa-f]{1,15}", size_txt): + raise Refuse + size = int(size_txt, 16) + uw.write(f"{size:x}\r\n".encode()) # chunk extensions are dropped + if size == 0: + while True: # trailers, forwarded only if they are well formed + t = await cr.readuntil(b"\r\n") + if t == b"\r\n": + uw.write(b"\r\n") + await uw.drain() + return + if ( + len(t) > MAX_CHUNK_LINE + or TOKEN.fullmatch(t[:-2].split(b":", 1)[0].decode("latin-1")) + is None + ): + raise Refuse + uw.write(t) + await copy_exact(cr, uw, size) + if await cr.readexactly(2) != b"\r\n": + raise Refuse + uw.write(b"\r\n") + await uw.drain() -async def intercept(cr, cw, host): - cw.write(b"HTTP/1.1 200 Connection Established\r\n\r\n") - await cw.drain() +async def pipe(r, w): try: - await cw.start_tls(server_ctx) - head = await read_head(cr) + while data := await r.read(65536): + w.write(data) + await w.drain() + except (ConnectionError, OSError, asyncio.IncompleteReadError): + pass + + +async def handle(cr, cw): + try: + head = await asyncio.wait_for(cr.readuntil(b"\r\n\r\n"), 30) except ( TimeoutError, - ssl.SSLError, OSError, asyncio.IncompleteReadError, asyncio.LimitOverrunError, ): - log("FAIL-TLS", host) close(cw) return - out = rebuild_request(head, host) - if out is None: - log("DENY-PATH", host) + parts = head.split(b"\r\n", 1)[0].decode("latin-1", "replace").split() + if len(parts) != 3 or parts[0] != "CONNECT": + log("REFUSE-NONCONNECT") + await refuse(cw, b"HTTP/1.1 405 Method Not Allowed") + return + host, _, port = parts[1].rpartition(":") + if port != "443" or host not in allow: + log("DENY", host) + if deniedf is not None: + deniedf.write(parts[1][:300] + "\n") await refuse(cw, b"HTTP/1.1 403 Forbidden") return + uw = None try: + cw.write(b"HTTP/1.1 200 Connection Established\r\n\r\n") + await cw.drain() + await cw.start_tls(server_ctx) + rhead = await asyncio.wait_for(cr.readuntil(b"\r\n\r\n"), 60) + try: + out, kind, length = rebuild_request(rhead, host) + except Refuse: + log("DENY-REQ", host) + await refuse(cw, b"HTTP/1.1 403 Forbidden") + return ur, uw = await asyncio.wait_for( asyncio.open_connection(host, 443, ssl=upstream_ctx, server_hostname=host), 30, ) - except (TimeoutError, OSError): + uw.write(out) + await uw.drain() + if kind == "length": + await copy_exact(cr, uw, length) + elif kind == "chunked": + await copy_chunked(cr, uw) + log("ALLOW", host) + await pipe( + ur, cw + ) # Connection: close upstream ends the response; later client bytes are ignored + except Refuse: + log("DENY-BODY", host) + except ( + TimeoutError, + ssl.SSLError, + OSError, + asyncio.IncompleteReadError, + asyncio.LimitOverrunError, + ): log("FAIL", host) + finally: + if uw is not None: + close(uw) close(cw) - return - log("ALLOW-PATH", host) - uw.write(out) - await uw.drain() - await pipe( - ur, cw - ) # requests after the first one on this connection are never forwarded - close(uw) async def main(): with contextlib.suppress(FileNotFoundError): os.unlink(sock_path) - srv = await asyncio.start_unix_server(handle, path=sock_path) + srv = await asyncio.start_unix_server(handle, path=sock_path, limit=MAX_HEAD) os.chmod(sock_path, 0o600) async with srv: await srv.serve_forever() @@ -1416,6 +1520,10 @@ if [ "$AGY_ISOLATION" = bwrap ]; then for _t in "${_need[@]}"; do command -v "$_t" >/dev/null 2>&1 || { log "AGY_ISOLATION=bwrap needs '$_t' on the runner host; refusing to run agy unjailed (set AGY_ISOLATION=none to override, not recommended)"; exit 1; } done + # The egress proxy needs asyncio's StreamWriter.start_tls (Python 3.11+). + if [ "$AGY_EGRESS" = filtered ] && ! python3 -I -c 'import sys; sys.exit(sys.version_info < (3, 11))'; then + log "AGY_EGRESS=filtered needs python3 >= 3.11 on the runner host (found $(python3 -V 2>&1)); refusing to run agy"; exit 1 + fi [ -n "${XDG_RUNTIME_DIR:-}" ] && [ -n "${DBUS_SESSION_BUS_ADDRESS:-}" ] \ || { log "AGY_ISOLATION=bwrap needs XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS (a user session)"; exit 1; } # agy's own keyring item(s), resolved OUTSIDE the jail: object paths only, never secrets. @@ -1457,21 +1565,30 @@ if [ "$AGY_ISOLATION" = bwrap ]; then || { log "invalid AGY_EGRESS_ALLOW entry '$_h' (exact lowercase host names only, no wildcards)"; exit 1; } _allow="${_allow:+$_allow,}$_h" done + _prules="" + for _r in $AGY_EGRESS_PATH_RULES; do + [[ "$_r" =~ ^([a-z0-9.-]+)=(/[A-Za-z0-9._~/-]*)$ ]] \ + || { log "invalid AGY_EGRESS_PATH_RULES entry '$_r' (expected host=/exact/path)"; exit 1; } + [[ ",$_allow," == *",${BASH_REMATCH[1]},"* ]] \ + || { log "AGY_EGRESS_PATH_RULES names '${BASH_REMATCH[1]}', which is not in AGY_EGRESS_ALLOW"; exit 1; } + _prules="${_prules:+$_prules,}$_r" + done + _san="DNS:${_allow//,/,DNS:}" _ca_sys="" for _c in /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/cert.pem; do [ -s "$_c" ] && { _ca_sys="$_c"; break; } done [ -n "$_ca_sys" ] || { log "AGY_EGRESS=filtered: no system CA bundle found; refusing to run agy"; exit 1; } - # Per-run CA + leaf for the intercepted host. Both keys stay in the private runtime dir, which - # is never mounted into the jail; the jail gets only a CA bundle (system roots + this CA). + # Per-run CA + one leaf covering every allowlisted host. Both keys stay in the private runtime + # dir, which is never mounted into the jail; the jail gets only a CA bundle (roots + this CA). _pki="$agy_jail_rt/pki"; mkdir -m 700 "$_pki" if ! { openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 1 \ -subj "/CN=agy-review egress CA" -addext "basicConstraints=critical,CA:TRUE" \ -addext "keyUsage=critical,keyCertSign" -keyout "$_pki/ca.key" -out "$_pki/ca.pem" \ && openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \ - -subj "/CN=$AGY_EGRESS_INTERCEPT_HOST" -keyout "$_pki/leaf.key" -out "$_pki/leaf.csr" \ + -subj "/CN=agy-review egress" -keyout "$_pki/leaf.key" -out "$_pki/leaf.csr" \ && openssl x509 -req -in "$_pki/leaf.csr" -CA "$_pki/ca.pem" -CAkey "$_pki/ca.key" -days 1 \ - -extfile <(printf 'subjectAltName=DNS:%s\nextendedKeyUsage=serverAuth\nbasicConstraints=CA:FALSE\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n' "$AGY_EGRESS_INTERCEPT_HOST") \ + -extfile <(printf 'subjectAltName=%s\nextendedKeyUsage=serverAuth\nbasicConstraints=CA:FALSE\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n' "$_san") \ -out "$_pki/leaf.pem"; } >/dev/null 2>&1; then log "AGY_EGRESS=filtered: could not create the per-run certificates; refusing to run agy"; exit 1 fi @@ -1480,7 +1597,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then : > "$agy_jail_rt/egress-denied.txt"; chmod 600 "$agy_jail_rt/egress-denied.txt" AGY_EGRESS_DENIED_FILE="$agy_jail_rt/egress-denied.txt" \ python3 -I "$agy_jail_rt/egress.py" "$agy_jail_rt/egress.sock" "$agy_jail_rt/egress.log" "$_allow" \ - "$AGY_EGRESS_INTERCEPT_HOST" "$AGY_EGRESS_INTERCEPT_PATH" "$_pki/leaf.pem" "$_pki/leaf.key" \ + "$_pki/leaf.pem" "$_pki/leaf.key" "$_prules" \ 2>>"$LOG" & agy_egress_pid=$! for _ in $(seq 1 100); do [ -S "$agy_jail_rt/egress.sock" ] && break; sleep 0.1; done @@ -1492,7 +1609,9 @@ if [ "$AGY_ISOLATION" = bwrap ]; then "HTTP_PROXY=http://127.0.0.1:3128" "http_proxy=http://127.0.0.1:3128" "NO_PROXY=" "no_proxy=" "SSL_CERT_FILE=/run/agy-ca-bundle.pem" ) # Inside the jail: bridge loopback 3128 to the proxy socket, wait for it, then exec the payload. - _inner=( /usr/bin/bash -c 'socat TCP-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:/run/agy-egress.sock 2>/dev/null & for _ in $(seq 1 100); do (exec 3<>/dev/tcp/127.0.0.1/3128) 2>/dev/null && break; sleep 0.1; done; exec "$@"' agy-jail ) + # Inside the jail: bridge loopback 3128 to the proxy socket and wait for it. If the bridge never + # comes up, say so with the `agy-jail:` prefix (agy_jail_failed) instead of launching agy anyway. + _inner=( /usr/bin/bash -c 'socat TCP-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:/run/agy-egress.sock 2>/dev/null & up=0; for _ in $(seq 1 100); do if (exec 3<>/dev/tcp/127.0.0.1/3128) 2>/dev/null; then up=1; break; fi; sleep 0.1; done; [ "$up" = 1 ] || { echo "agy-jail: the egress bridge did not start" >&2; exit 1; }; exec "$@"' agy-jail ) fi # Mirror the host's real top-level layout: merged-/usr distributions differ (Arch links /lib64 # to usr/lib, Debian and Ubuntu to usr/lib64), and the ELF interpreter must resolve the same way. @@ -1515,7 +1634,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then # Inside the jail, D-Bus is the filtered proxy (later env assignments override earlier ones). agy_env+=( "XDG_RUNTIME_DIR=/run/user/$_uid" "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$_uid/bus" "TMPDIR=/tmp" "${_egress_env[@]}" ) log "agy isolation: bwrap jail, empty HOME, D-Bus limited to ${#_items[@]} keyring item(s), egress ${AGY_EGRESS}" - unset _t _need _dict _kv _items _rules _it _uid _net _egress_binds _egress_env _inner _allow _h _ca_sys _c _pki _toplevel _d + unset _t _need _dict _kv _items _rules _it _uid _net _egress_binds _egress_env _inner _allow _h _ca_sys _c _pki _toplevel _d _prules _r _san fi [ -n "$AGY_MODEL" ] && flags+=( --model "$AGY_MODEL" ) [ -n "$AGY_EFFORT" ] && flags+=( --effort "$AGY_EFFORT" ) @@ -1589,10 +1708,16 @@ for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do # These two run on EVERY capture before any handler below logs or clears it: the backend-error # handler prints a short capture's first line to the public job log, which must never carry a # credential, and a jail diagnostic must never be retried or posted. + # A credential-shaped string is REDACTED, not fatal: the scan cannot tell a leaked secret from a + # test fixture a PR adds (a sample JWT), and either way the string never reaches the comment. if cred_kind="$(credential_kind_present "$out_file")"; then - log "refusing to post: agy's output contains a credential-shaped string (${cred_kind}) (attempt ${attempt}/${AGY_RETRIES}). Nothing was posted or logged from it. Inspect the runner host; the diff may carry a prompt injection." - : > "$out_file" - exit 1 + if ! agy_redact_credentials "$out_file" || left="$(credential_kind_present "$out_file")"; then + log "refusing to post: a credential-shaped string (${left:-$cred_kind}) could not be redacted from agy's output. Nothing was posted." + : > "$out_file" + exit 1 + fi + redacted_kinds="${redacted_kinds:+$redacted_kinds, }${cred_kind}" + log "redacted credential-shaped string(s) (${cred_kind}, and any others) from agy's output (attempt ${attempt}/${AGY_RETRIES}). If this PR adds sample tokens (test fixtures), that is the likely source; otherwise inspect the runner host, the diff may carry a prompt injection." fi # A jail that never started (no user namespaces, a missing bind source, ...) prints its own # diagnostic, which the PTY capture keeps while `|| true` drops the exit status. Never let that @@ -1740,10 +1865,13 @@ body_file="$(mktemp)" printf '## Antigravity review (Gemini via Ultra)\n\n' cat "$out_file" printf '%s' "$truncated" + if [ -n "${redacted_kinds:-}" ]; then + printf '\n\n> **Note:** credential-shaped strings were redacted from this review before posting (%s). If this PR adds sample tokens, that is the likely source.\n' "$redacted_kinds" + fi printf '\n\nAutomated first-pass review by `agy` on a self-hosted runner -- not a human review.\n' } > "$body_file" -# Fail closed before ANY post path (edit-in-place or new comment) if agy's output carries a -# credential shape; see credential_kind_present. +# Last-resort guard before ANY post path (edit-in-place or new comment). The capture loop already +# redacted every credential shape, so reaching this means redaction missed one: fail closed. if cred_kind="$(credential_kind_present "$out_file")"; then log "refusing to post: agy's output contains a credential-shaped string (${cred_kind}). Nothing was posted. Inspect the runner host; the diff may carry a prompt injection." exit 1 From 795e6791956a7825135d97f5fe104f3b79afb97b Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 17:43:23 -0500 Subject: [PATCH 07/14] ci: re-sync the reviewer to template f29c2ab Two follow-ups from the automated security review of 1d782bb: - Chunk trailers are read (bounded) and discarded; only the terminating CRLF goes upstream, so no header can be added after validation. - Credential redaction runs in memory instead of through a predictable "$f.redact" sibling file in a possibly shared TMPDIR. Verification: agy-review-selftest.sh all checks passed; actionlint clean. Live: a jailed review through the proxy posted (26 rebuilt requests), leaving nothing behind. Co-Authored-By: Claude Opus 5.5 --- scripts/agy-review-selftest.sh | 7 +++++++ scripts/agy-review.sh | 27 +++++++++++++-------------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index 85b9664c..90f948fa 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -968,6 +968,13 @@ check "adjacent matches are all redacted, boundaries kept" "keys [REDACTED: aws- check "the capture loop redacts instead of failing" "1" \ "$(grep -c '^ if ! agy_redact_credentials "\$out_file" || left="\$(credential_kind_present "\$out_file")"; then' "$SCRIPT")" check "a redacted review says so in the comment" "1" "$(grep -c 'credential-shaped strings were redacted from this review before posting' "$SCRIPT")" +# Commit security review of 1d782bb: chunk trailers are discarded, never forwarded, and redaction +# uses no scratch file (a predictable sibling in a shared TMPDIR). +check "chunked trailers are read and discarded, never written upstream" "0" "$(grep -c '^ *uw.write(t)$' "$proxy_py")" +check "only the terminating CRLF follows the last chunk" "1" \ + "$(grep -c 'Trailers are read (bounded) and DISCARDED' "$proxy_py")" +check "redaction works in memory, with no scratch file" "0" \ + "$(sed -n '/^agy_redact_credentials() {/,/^}/p' "$SCRIPT" | grep -cE 'mktemp|\.redact|> *"\$tmp"')" # Credential scan: every shape is caught, ordinary review text is not. cred_tmp="$TMPD/cred.txt" # Samples are assembled at runtime from split pieces, so this file never contains a literal that a diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index e37ce70d..b8bce154 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -213,21 +213,22 @@ credential_kind_present() { # line (or to the end of the text, which fails safe). Several passes, because adjacent matches # can share a boundary character. The caller re-scans and fails closed on anything left. agy_redact_credentials() { - local f="$1" kind lead core trail groups n pass - local tmp="$1.redact" # a sibling of the capture, removed below + # In memory, not through a scratch file: the capture is bounded (GitHub's comment limit), and a + # predictable sibling in a shared TMPDIR would be readable or symlink-raceable. The `x` sentinel + # keeps trailing newlines through the command substitution. + local f="$1" buf kind lead core trail groups n pass for pass in 1 2 3; do while IFS='~' read -r kind lead core trail; do if [ "$kind" = private-key-block ]; then - sed -E "/${core}/,/-----END [A-Z ]*PRIVATE KEY-----/c\\[REDACTED: ${kind}]" "$f" > "$tmp" || return 1 + buf="$(sed -E "/${core}/,/-----END [A-Z ]*PRIVATE KEY-----/c\\[REDACTED: ${kind}]" "$f" && printf x)" || return 1 else groups="${core//[^(]/}"; n=$(( 2 + ${#groups} )) - sed -E "s#${lead:-()}${core}${trail:-()}#\\1[REDACTED: ${kind}]\\${n}#g" "$f" > "$tmp" || return 1 + buf="$(sed -E "s#${lead:-()}${core}${trail:-()}#\\1[REDACTED: ${kind}]\\${n}#g" "$f" && printf x)" || return 1 fi - cat "$tmp" > "$f" + printf '%s' "${buf%x}" > "$f" done < <(agy_credential_patterns) : "$pass" done - rm -f -- "$tmp" } # <<< SELFTEST-EXTRACT @@ -1401,19 +1402,17 @@ async def copy_chunked(cr, uw): size = int(size_txt, 16) uw.write(f"{size:x}\r\n".encode()) # chunk extensions are dropped if size == 0: - while True: # trailers, forwarded only if they are well formed + # Trailers are read (bounded) and DISCARDED: forwarding them would let a client add + # headers after validation. Only the terminating CRLF goes upstream. + for _ in range(64): t = await cr.readuntil(b"\r\n") + if len(t) > MAX_CHUNK_LINE: + raise Refuse if t == b"\r\n": uw.write(b"\r\n") await uw.drain() return - if ( - len(t) > MAX_CHUNK_LINE - or TOKEN.fullmatch(t[:-2].split(b":", 1)[0].decode("latin-1")) - is None - ): - raise Refuse - uw.write(t) + raise Refuse await copy_exact(cr, uw, size) if await cr.readexactly(2) != b"\r\n": raise Refuse From 22c0da334e1abb2c923b7eaae57920306233fbe7 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 19:20:03 -0500 Subject: [PATCH 08/14] ci: re-sync the reviewer to template accfc51 Re-syncs the vendored reviewer scripts and .github/AGY-REVIEWER.md byte for byte from the antigravity-pr-review template at accfc51. Local workflow overrides are unchanged. From CodeRabbit's review of CyberChef-MCP #184: - A backend error is classified on agy's raw capture, before redaction. A redaction marker is longer than the key it replaces, so a near-limit error could outgrow the size guard and be posted. - A private key whose BEGIN and END share one line no longer deletes the rest of the review. - The egress proxy drops fields named in Connection (RFC 9110) and answers Expect with 417 instead of stalling. - Self-test: the path-rule fixture contains a `.`, so literal and regex matching are told apart, and the denial count is exact. Verification: agy-review-selftest.sh all checks passed (each new check fails against f29c2ab); actionlint clean; markdownlint clean. Co-Authored-By: Claude Opus 5.5 --- .github/AGY-REVIEWER.md | 4 ++++ scripts/agy-review-selftest.sh | 44 ++++++++++++++++++++++++++-------- scripts/agy-review.sh | 32 +++++++++++++++++++++---- 3 files changed, 66 insertions(+), 14 deletions(-) diff --git a/.github/AGY-REVIEWER.md b/.github/AGY-REVIEWER.md index 05c96f1e..ac310ec3 100644 --- a/.github/AGY-REVIEWER.md +++ b/.github/AGY-REVIEWER.md @@ -187,6 +187,10 @@ to `.agy-review-work/` in the checkout and required `/.agy-review-work/` in PR that adds the workflow is itself a live test, and every follow-up push re-reviews (`synchronize`). Auto-runs only for PRs authored by a trusted user (see the security model) so a fork's code never auto-executes on the runner. + The PR that adds the reviewer is reviewed only while the workflow keeps its + first-install bootstrap steps. Most repositories remove them (see the security + model), and there reviews start once the reviewer is on the default branch; + until then the review step is skipped with a warning. - **On demand:** comment **`/agy-review`** on any PR to (re)run it. ### One comment per PR, appended to — never replaced diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index 90f948fa..5315b797 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -835,7 +835,7 @@ if command -v python3 >/dev/null 2>&1 && command -v openssl >/dev/null 2>&1; the if [ "$certs_ok" = yes ]; then px_log="$ip/log"; : > "$px_log" python3 -I "$proxy_py" "$sockd/p.sock" "$px_log" "allowed.example,paths.example" \ - "$ip/leaf.pem" "$ip/leaf.key" "paths.example=/oauth2/v2/userinfo" 2>"$ip/err" & + "$ip/leaf.pem" "$ip/leaf.key" "paths.example=/v1/user.info" 2>"$ip/err" & px_pid=$! for _ in $(seq 1 50); do [ -S "$sockd/p.sock" ] && break; sleep 0.1; done cat > "$ip/client.py" <<'PYC' @@ -882,16 +882,18 @@ PYC check "HTTP/1.0 refused" "403" "$(pc "$A" "GET / HTTP/1.0\\r\\n${H}\\r\\n")" P='paths.example:443'; PH='Host: paths.example\r\n' check "path rule: a query string is refused" "403" \ - "$(pc "$P" "GET /oauth2/v2/userinfo?x=secret HTTP/1.1\\r\\n${PH}\\r\\n")" + "$(pc "$P" "GET /v1/user.info?x=secret HTTP/1.1\\r\\n${PH}\\r\\n")" check "path rule: another path is refused" "403" "$(pc "$P" "GET /storage/v1/b/x HTTP/1.1\\r\\n${PH}\\r\\n")" check "path rule: a POST to the allowed path is refused" "403" \ - "$(pc "$P" "POST /oauth2/v2/userinfo HTTP/1.1\\r\\n${PH}Content-Length: 1\\r\\n\\r\\n")" - check "path rule: the path is literal, not a regex" "403" \ - "$(pc "$P" "GET /oauth2/v2/userinfoX HTTP/1.1\\r\\n${PH}\\r\\n")" + "$(pc "$P" "POST /v1/user.info HTTP/1.1\\r\\n${PH}Content-Length: 1\\r\\n\\r\\n")" + check "path rule: the path is literal, not a regex (. is not a wildcard)" "403" \ + "$(pc "$P" "GET /v1/userXinfo HTTP/1.1\\r\\n${PH}\\r\\n")" + check "Expect: 100-continue is answered 417, not stalled" "417" \ + "$(pc "$A" "POST / HTTP/1.1\\r\\n${H}Content-Length: 1\\r\\nExpect: 100-continue\\r\\n\\r\\n")" kill "$px_pid" 2>/dev/null; wait "$px_pid" 2>/dev/null || true # 143 from the kill is expected check "proxy never logs a denied host name" "0" "$(grep -c 'evil' "$px_log")" - check "every denial is logged by verdict" "yes" \ - "$([ "$(grep -cE '^DENY' "$px_log")" -ge 17 ] && echo yes || echo no)" + # One verdict per refused case above: 3 CONNECT, 12 request-head, 4 path-rule, 1 Expect. + check "every denial is logged by verdict, one per refused request" "20" "$(grep -cE '^DENY' "$px_log")" # rebuild_request, unit level: Host set by the proxy, hop-by-hop dropped, framing canonical. rb="$(python3 -I - "$proxy_py" "$ip/leaf.pem" "$ip/leaf.key" <<'PYR' 2>/dev/null import sys @@ -900,12 +902,13 @@ sys.argv = ["x", "/dev/null", "/dev/null", "allowed.example", sys.argv[2], sys.a ns = {"__name__": "agy_egress_test"} exec(compile(src, "proxy", "exec"), ns) head = (b"POST /v1/x HTTP/1.1\r\nHost: allowed.example\r\nAuthorization: Bearer t\r\n" - b"Connection: keep-alive\r\nUpgrade: h2c\r\nTransfer-Encoding: chunked\r\nX-Goog-Api-Client: a\r\n\r\n") + b"Connection: keep-alive, X-Diag\r\nX-Diag: local\r\nUpgrade: h2c\r\nTransfer-Encoding: chunked\r\n" + b"X-Goog-Api-Client: a\r\n\r\n") out, kind, n = ns["rebuild_request"](head, "allowed.example") print(kind + "|" + "|".join(out.decode().split("\r\n"))) PYR )" || rb="(rebuild_request missing or failed)" - check "the rebuilt request sets Host itself, drops hop-by-hop headers, keeps chunked framing" \ + check "the rebuilt request sets Host itself, drops hop-by-hop and Connection-named headers, keeps chunked framing" \ "chunked|POST /v1/x HTTP/1.1|Host: allowed.example|Authorization: Bearer t|X-Goog-Api-Client: a|Transfer-Encoding: chunked|Connection: close||" "$rb" fi rm -rf -- "$sockd" @@ -924,9 +927,21 @@ check "cleanup ignores a failed kill of either proxy (set -e safe)" "2" \ "$(grep -cE '^ \[ -n "\$\{agy_(proxy|egress)_pid:-\}" \] && \{ kill "\$agy_(proxy|egress)_pid" 2>/dev/null \|\| true; \}$' "$SCRIPT")" # Round-4 review fixes. cred_line="$(grep -n '^ if cred_kind="\$(credential_kind_present "\$out_file")"; then' "$SCRIPT" | head -1 | cut -d: -f1 || true)" -svc_line="$(grep -n '^ if service_error_present "\$out_file"; then' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +svc_line="$(grep -n '^ if \[ "\$svc_err" = yes \]; then' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +svc_class="$(grep -n '^ svc_err=no; service_error_present "\$out_file" && svc_err=yes$' "$SCRIPT" | head -1 | cut -d: -f1 || true)" check "each capture is credential-scanned before any handler logs it" "yes" \ "$([ -n "$cred_line" ] && [ -n "$svc_line" ] && [ "$cred_line" -lt "$svc_line" ] && echo yes || echo no)" +# Round 8: a backend error is classified on the unredacted capture, because a redaction marker +# is longer than the key it replaces and can push a short error past AGY_ERROR_MAX_BYTES. +check "a backend error is classified before redaction can lengthen it" "yes" \ + "$([ -n "$svc_class" ] && [ -n "$cred_line" ] && [ "$svc_class" -lt "$cred_line" ] && echo yes || echo no)" +grow="$TMPD/grow.txt" +{ printf 'Error: backend failed for key AKIA%s ' "$(printf 'Q%.0s' {1..16})"; head -c 1945 /dev/zero | tr '\0' x; } > "$grow" +check "(why) a near-limit backend error is caught as agy produced it" "yes" \ + "$(service_error_present "$grow" && echo yes || echo no)" +agy_redact_credentials "$grow" +check "(why) the same error, redacted, has grown past the size guard" "no" \ + "$(service_error_present "$grow" && echo yes || echo no)" check "the public stderr tail is scanned from a regular file and withheld on a match" "1" \ "$(grep -c '^ if log_cred="\$(credential_kind_present "\$log_tail")"; then' "$SCRIPT")" check "an empty AGY_KEYRING_ATTRS is refused (SearchItems {} matches every item)" "1" \ @@ -962,6 +977,15 @@ check "redaction leaves the rest of the review intact" "yes" "$(grep -qx 'Keep t printf 'one\n-----BEGIN OPENSSH ''PRIVATE KEY-----\nAAAAB3NzaC1yc2E\nmore-key-body\n-----END OPENSSH ''PRIVATE KEY-----\ntwo\n' > "$rd" agy_redact_credentials "$rd" check "a private-key block is redacted whole, body lines included" "one|[REDACTED: private-key-block]|two" "$(paste -sd'|' "$rd")" +printf 'one\nkey -----BEGIN RSA ''PRIVATE KEY-----MIIEabc-----END RSA ''PRIVATE KEY----- here\ntwo\nthree\n' > "$rd" +agy_redact_credentials "$rd" +check "a one-line private key is redacted without eating the rest of the review" \ + "one|key [REDACTED: private-key-block] here|two|three" "$(paste -sd'|' "$rd")" +printf 'one\n-----BEGIN RSA ''PRIVATE KEY-----\nMIIEabc\n' > "$rd" +agy_redact_credentials "$rd" +# GNU sed prints a `c` range's text only when the range closes; unclosed, it deletes to the end. +check "an unterminated private key is deleted through the end of the text (fail safe)" \ + "one" "$(paste -sd'|' "$rd")" printf 'keys %s.%s and %s\n' "AKI""AABCDEFGHIJKLMNOP" "AKI""AQRSTUVWXYZ234567" "gh""p_$(printf 'c%.0s' {1..36})" > "$rd" agy_redact_credentials "$rd" check "adjacent matches are all redacted, boundaries kept" "keys [REDACTED: aws-access-key-id].[REDACTED: aws-access-key-id] and [REDACTED: github-token]" "$(cat "$rd")" diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index b8bce154..e0adc840 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -220,7 +220,11 @@ agy_redact_credentials() { for pass in 1 2 3; do while IFS='~' read -r kind lead core trail; do if [ "$kind" = private-key-block ]; then - buf="$(sed -E "/${core}/,/-----END [A-Z ]*PRIVATE KEY-----/c\\[REDACTED: ${kind}]" "$f" && printf x)" || return 1 + # A one-line block is substituted in place first: a range looks for its END only from + # the NEXT line, so it would swallow the rest of the review. A multi-line or + # unterminated block still goes through the range (to the end of text, fail safe). + buf="$(sed -E -e "s#${core}.*-----END [A-Z ]*PRIVATE KEY-----#[REDACTED: ${kind}]#g" \ + -e "/${core}/,/-----END [A-Z ]*PRIVATE KEY-----/c\\[REDACTED: ${kind}]" "$f" && printf x)" || return 1 else groups="${core//[^(]/}"; n=$(( 2 + ${#groups} )) buf="$(sed -E "s#${lead:-()}${core}${trail:-()}#\\1[REDACTED: ${kind}]\\${n}#g" "$f" && printf x)" || return 1 @@ -1286,6 +1290,11 @@ class Refuse(Exception): """The request is refused (403); the reason is never echoed anywhere.""" +class ExpectationFailed(Refuse): + """`Expect` is not supported: answered 417 so a client can retry without it, instead of + waiting for a `100 Continue` the proxy would only relay after the body (a stall).""" + + def log(verdict, host=""): logf.write(f"{verdict} {host if host in allow else ''}".rstrip() + "\n") @@ -1329,7 +1338,7 @@ def rebuild_request(head, host): method, target = req[0], req[1] if not target.startswith("/") or target.startswith("//"): raise Refuse # origin-form only: no absolute-form or authority-form target - hosts, keep, lengths, codings = [], [], [], [] + hosts, keep, lengths, codings, conn_opts = [], [], [], [], set() for line in lines[1:]: if not line or line[0] in " \t": raise Refuse # empty line inside the head, or obs-fold continuation @@ -1343,8 +1352,14 @@ def rebuild_request(head, host): lengths.append(value) elif lname == "transfer-encoding": codings.append(value.lower()) + elif lname == "expect": + raise ExpectationFailed + elif lname == "connection": + conn_opts.update(t.strip(" \t").lower() for t in value.split(",")) elif lname not in HOP_BY_HOP: - keep.append(f"{name}: {value}") + keep.append((lname, f"{name}: {value}")) + # RFC 9110 7.6.1: a field named in Connection is connection-local and is not forwarded. + keep = [line for lname, line in keep if lname not in conn_opts] if len(hosts) != 1 or hosts[0] not in (host, f"{host}:443"): raise Refuse if lengths and codings: @@ -1460,6 +1475,10 @@ async def handle(cr, cw): rhead = await asyncio.wait_for(cr.readuntil(b"\r\n\r\n"), 60) try: out, kind, length = rebuild_request(rhead, host) + except ExpectationFailed: + log("DENY-EXPECT", host) + await refuse(cw, b"HTTP/1.1 417 Expectation Failed") + return except Refuse: log("DENY-REQ", host) await refuse(cw, b"HTTP/1.1 403 Forbidden") @@ -1704,6 +1723,11 @@ for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do # normalize CRs without sed -i (avoid in-place edit footguns) tr -d '\r' < "$out_file" > "$out_file.clean" && mv "$out_file.clean" "$out_file" + # Classify a backend error on the capture exactly as agy produced it, BEFORE redaction: a + # marker is longer than what it replaces (a 20-byte AWS key id becomes 29 bytes), so a short + # error could otherwise grow past AGY_ERROR_MAX_BYTES, escape the guard and be posted. + # Only the decision is taken here; the handler below logs the REDACTED first line. + svc_err=no; service_error_present "$out_file" && svc_err=yes # These two run on EVERY capture before any handler below logs or clears it: the backend-error # handler prints a short capture's first line to the public job log, which must never carry a # credential, and a jail diagnostic must never be retried or posted. @@ -1755,7 +1779,7 @@ for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do # output" cause, and the reverse would claim the backend was down on every attempt when it was # down on one. Both exit non-zero, so nothing unsafe -- but the log line is the only thing # telling a human which outage they are looking at. - if service_error_present "$out_file"; then + if [ "$svc_err" = yes ]; then log "agy returned a backend error rather than a review (attempt ${attempt}/${AGY_RETRIES}): $(head -n 1 "$out_file")" : > "$out_file" service_errors=$(( ${service_errors:-0} + 1 )) From ae8ba95994d34933d15ee993460e065b6cdafe3b Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 19:23:51 -0500 Subject: [PATCH 09/14] ci: re-sync the reviewer to template 499bb51 Re-syncs the vendored reviewer scripts and .github/AGY-REVIEWER.md byte for byte from the antigravity-pr-review template at 499bb51. Local workflow overrides are unchanged. From CodeRabbit's review of CyberChef-MCP #184: - A backend error is classified on agy's raw capture, before redaction. A redaction marker is longer than the key it replaces, so a near-limit error could outgrow the size guard and be posted. - Private-key redaction uses awk: a one-line block is replaced in place, and a block with no END line ends in a visible marker saying the rest of the review was removed, instead of a silent truncation. - The egress proxy drops fields named in Connection (RFC 9110) and answers Expect with 417 instead of stalling. - Self-test: the path-rule fixture contains a `.`, so literal and regex matching are told apart, and the denial count is exact. Verification: agy-review-selftest.sh all checks passed (each new check fails against f29c2ab); actionlint clean; markdownlint clean. Co-Authored-By: Claude Opus 5.5 --- scripts/agy-review-selftest.sh | 5 ++--- scripts/agy-review.sh | 15 ++++++++++----- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index 5315b797..54c47cf9 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -983,9 +983,8 @@ check "a one-line private key is redacted without eating the rest of the review" "one|key [REDACTED: private-key-block] here|two|three" "$(paste -sd'|' "$rd")" printf 'one\n-----BEGIN RSA ''PRIVATE KEY-----\nMIIEabc\n' > "$rd" agy_redact_credentials "$rd" -# GNU sed prints a `c` range's text only when the range closes; unclosed, it deletes to the end. -check "an unterminated private key is deleted through the end of the text (fail safe)" \ - "one" "$(paste -sd'|' "$rd")" +check "an unterminated private key is removed to the end, and the comment says text was removed" \ + "one|[REDACTED: private-key-block]|[REDACTED: the rest of this review was removed: it quoted the start of a private key with no END line]" "$(paste -sd'|' "$rd")" printf 'keys %s.%s and %s\n' "AKI""AABCDEFGHIJKLMNOP" "AKI""AQRSTUVWXYZ234567" "gh""p_$(printf 'c%.0s' {1..36})" > "$rd" agy_redact_credentials "$rd" check "adjacent matches are all redacted, boundaries kept" "keys [REDACTED: aws-access-key-id].[REDACTED: aws-access-key-id] and [REDACTED: github-token]" "$(cat "$rd")" diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index e0adc840..f48cb965 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -220,11 +220,16 @@ agy_redact_credentials() { for pass in 1 2 3; do while IFS='~' read -r kind lead core trail; do if [ "$kind" = private-key-block ]; then - # A one-line block is substituted in place first: a range looks for its END only from - # the NEXT line, so it would swallow the rest of the review. A multi-line or - # unterminated block still goes through the range (to the end of text, fail safe). - buf="$(sed -E -e "s#${core}.*-----END [A-Z ]*PRIVATE KEY-----#[REDACTED: ${kind}]#g" \ - -e "/${core}/,/-----END [A-Z ]*PRIVATE KEY-----/c\\[REDACTED: ${kind}]" "$f" && printf x)" || return 1 + # awk, not a sed range: a one-line block (BEGIN and END on the same line) is replaced in + # place, a multi-line block becomes one marker line, and a block with NO END line removes + # the rest of the text but SAYS so, so the review can never be silently cut short. + buf="$(awk -v b="$core" -v e='-----END [A-Z ]*PRIVATE KEY-----' -v m="[REDACTED: ${kind}]" ' + inblk { if ($0 ~ e) inblk = 0; next } + { gsub(b ".*" e, m) } + $0 ~ b { print m; inblk = 1; if ($0 ~ e) inblk = 0; next } + { print } + END { if (inblk) print "[REDACTED: the rest of this review was removed: it quoted the start of a private key with no END line]" } + ' "$f" && printf x)" || return 1 else groups="${core//[^(]/}"; n=$(( 2 + ${#groups} )) buf="$(sed -E "s#${lead:-()}${core}${trail:-()}#\\1[REDACTED: ${kind}]\\${n}#g" "$f" && printf x)" || return 1 From 4f49a8a291a7314fe47045245c5cb376a0b633b1 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 20:56:59 -0500 Subject: [PATCH 10/14] ci: re-sync the reviewer to template 8782d07 Re-syncs scripts/agy-review-selftest.sh byte for byte from the antigravity-pr-review template at 8782d07. No other reviewer file changed; local workflow overrides are unchanged. - The chunked-trailer checks counted source text, so removing the terminating CRLF or forwarding a trailer through another write call left them green (CodeRabbit on CyberChef-MCP #184). They now run the real copy_chunked on an asyncio stream with a recording writer: a trailer is dropped, exactly `0\r\n\r\n` goes upstream, and the bytes of a following request stay unread. Both mutations turn them red. Verification: agy-review-selftest.sh all checks passed; actionlint clean. Co-Authored-By: Claude Opus 5.5 --- scripts/agy-review-selftest.sh | 45 +++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index 54c47cf9..a441f19a 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -910,6 +910,47 @@ PYR )" || rb="(rebuild_request missing or failed)" check "the rebuilt request sets Host itself, drops hop-by-hop and Connection-named headers, keeps chunked framing" \ "chunked|POST /v1/x HTTP/1.1|Host: allowed.example|Authorization: Bearer t|X-Goog-Api-Client: a|Transfer-Encoding: chunked|Connection: close||" "$rb" + # copy_chunked on real streams (round 9): a trailer after the last chunk is consumed and NOT + # forwarded, exactly the terminating `0\r\n\r\n` goes upstream, and the bytes of a following + # request stay unread (never smuggled upstream behind the body). + cc="$(python3 -I - "$proxy_py" "$ip/leaf.pem" "$ip/leaf.key" <<'PYC' 2>/dev/null +import asyncio, sys +src = open(sys.argv[1]).read().split("\nasyncio.run(main())", 1)[0] +sys.argv = ["x", "/dev/null", "/dev/null", "allowed.example", sys.argv[2], sys.argv[3], ""] +ns = {"__name__": "agy_egress_test"} +exec(compile(src, "proxy", "exec"), ns) + + +class Rec: + def __init__(self): + self.out = bytearray() + + def write(self, b): + self.out += b + + async def drain(self): + pass + + +async def run(feed): + r = asyncio.StreamReader() + r.feed_data(feed) + r.feed_eof() + w = Rec() + await ns["copy_chunked"](r, w) + return bytes(w.out), await r.read() + + +for feed in (b"0\r\nX-Injected: 1\r\n\r\nGET /next HTTP/1.1\r\n", + b"3;ext=1\r\nabc\r\n0\r\n\r\nGET /next HTTP/1.1\r\n"): + out, rest = asyncio.run(run(feed)) + print(repr(out) + "|" + repr(rest)) +PYC +)" || cc="(copy_chunked missing or failed)" + check "a chunk trailer is dropped and exactly 0 CRLF CRLF goes upstream; the next request stays unread" \ + "b'0\\r\\n\\r\\n'|b'GET /next HTTP/1.1\\r\\n'" "$(printf '%s\n' "$cc" | sed -n 1p)" + check "a data chunk is forwarded without its extension, then the terminator; the next request stays unread" \ + "b'3\\r\\nabc\\r\\n0\\r\\n\\r\\n'|b'GET /next HTTP/1.1\\r\\n'" "$(printf '%s\n' "$cc" | sed -n 2p)" fi rm -rf -- "$sockd" fi @@ -993,9 +1034,7 @@ check "the capture loop redacts instead of failing" "1" \ check "a redacted review says so in the comment" "1" "$(grep -c 'credential-shaped strings were redacted from this review before posting' "$SCRIPT")" # Commit security review of 1d782bb: chunk trailers are discarded, never forwarded, and redaction # uses no scratch file (a predictable sibling in a shared TMPDIR). -check "chunked trailers are read and discarded, never written upstream" "0" "$(grep -c '^ *uw.write(t)$' "$proxy_py")" -check "only the terminating CRLF follows the last chunk" "1" \ - "$(grep -c 'Trailers are read (bounded) and DISCARDED' "$proxy_py")" +# (The trailer handling is exercised on real streams in the TLS block above.) check "redaction works in memory, with no scratch file" "0" \ "$(sed -n '/^agy_redact_credentials() {/,/^}/p' "$SCRIPT" | grep -cE 'mktemp|\.redact|> *"\$tmp"')" # Credential scan: every shape is caught, ordinary review text is not. From 4040f462d0a566084ed866741607300d4486da51 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 21:40:14 -0500 Subject: [PATCH 11/14] ci: re-sync the reviewer to template 2a366ac Re-syncs the vendored reviewer scripts byte for byte from the antigravity-pr-review template at 2a366ac (round 10 of the agy and CodeRabbit findings). Local workflow overrides are unchanged. - A second private key opened on the first key's END line was dropped from redaction; each line is now scanned left to right. - OpenAI sk-proj-/sk-svcacct- keys (base64url) are recognized. - The redaction note names every kind and is reset per attempt; the last guard scans the assembled comment body. - The egress proxy forwards Content-Length: 0 (Google answers an empty POST without it with 411). - Control bytes are stripped from the denied-host log; the agy lock is taken before the jail starts; cleanup reaps both proxies. - Self-test: two pipefail races (one made it flake) are removed, and the TLS cases are skipped by name on python < 3.11. Verification: agy-review-selftest.sh all checks passed; actionlint clean; a live jailed review from the same scripts completed and cleaned up after itself. Co-Authored-By: Claude Opus 5.5 --- scripts/agy-review-selftest.sh | 89 ++++++++++++++++++-- scripts/agy-review.sh | 145 ++++++++++++++++++++++----------- 2 files changed, 178 insertions(+), 56 deletions(-) diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index a441f19a..8a7d7d97 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -281,8 +281,10 @@ fi # Line continuations are folded first: `--arg` moved onto a continuation line would otherwise sit # on a different physical line from `gh api`, and a line-by-line grep would report a false pass on # exactly the mistake this check exists to catch. -if sed -e ':a' -e '/\\$/{N;s/\\\n//;ba' -e '}' "$SCRIPT_DIR/agy-review.sh" \ - | grep -qE 'gh api[^|]*--(arg|argjson)'; then +# grep reads a process substitution, not a pipe: under pipefail, grep -q exiting on an early +# match SIGPIPEs the writer and fails the pipeline, which here would read as a PASS. +if grep -qE 'gh api[^|]*--(arg|argjson)' \ + < <(sed -e ':a' -e '/\\$/{N;s/\\\n//;ba' -e '}' "$SCRIPT_DIR/agy-review.sh"); then echo " FAIL --arg/--argjson passed to \`gh api\` (jq flags; gh api rejects them)" fails=$((fails + 1)) else @@ -296,7 +298,18 @@ fi # string as its entire body. A control that cannot fail is worse than no control. se() { printf '%s' "$1" > "$TMPD/cap"; service_error_present "$TMPD/cap" && echo MATCH || echo NOMATCH; } TMPD="$(mktemp -d)" -trap 'rm -rf "$TMPD"' EXIT +# The live proxy and its socket dir are removed too if the suite exits early. +# Each is cleared as soon as the suite cleans it up itself, so the trap never signals a reaped +# (possibly reused) PID; the suite's own exit status is kept. +px_pid= sockd= +selftest_exit() { + local st=$? + rm -rf "$TMPD" + if [ -n "$px_pid" ]; then kill "$px_pid" 2>/dev/null || true; fi + if [ -n "$sockd" ]; then rm -rf -- "$sockd"; fi + exit "$st" +} +trap selftest_exit EXIT check "a bare backend 503 is caught" "MATCH" \ "$(se 'Error: Eligibility check failed: UNAVAILABLE (code 503): The service is currently unavailable.')" @@ -431,7 +444,9 @@ check "localized script records are stripped too" "## Review|body" \ cleanup_src="$(sed -n '/^cleanup() {/,/^}/p' "$SCRIPT_DIR/agy-review.sh")" missing="" for v in $(grep -oE '[A-Za-z_][A-Za-z0-9_]*="\$\(mktemp' "$SCRIPT_DIR/agy-review.sh" | cut -d= -f1 | sort -u); do - printf '%s' "$cleanup_src" | grep -qF "\${$v:-}" || missing="$missing $v" + # A here-string, not `printf | grep -q`: under pipefail an early match can SIGPIPE printf and + # report a present variable as missing (this check flaked that way, 2026-11-23). + grep -qF "\${$v:-}" <<<"$cleanup_src" || missing="$missing $v" done check "every mktemp'd variable is in the cleanup trap" "" "${missing# }" # REGRESSION (agy review, GH-ListRollup PR #6): listing a variable in cleanup() is not enough if @@ -816,7 +831,10 @@ check "the embedded egress proxy compiles" "0" \ # googleapis connection (fronting to Cloud Storage was verified through oauth2, aicode and # daily-cloudcode-pa). Every refusal below happens before any upstream connection, so no network # is needed. A host that has python3 and openssl must run these: a certificate failure is a FAIL. -if command -v python3 >/dev/null 2>&1 && command -v openssl >/dev/null 2>&1; then +# The proxy needs Python 3.11 (StreamWriter.start_tls); an older python3 would fail every TLS case +# with an opaque error, so it is reported as a skip instead. +if command -v python3 >/dev/null 2>&1 && python3 -I -c 'import sys; sys.exit(sys.version_info < (3, 11))' \ + && command -v openssl >/dev/null 2>&1; then # Unix socket paths are capped at 108 bytes, so the socket lives in a short dir, not under TMPD. sockd="$(mktemp -d "${XDG_RUNTIME_DIR:-/tmp}/agyst.XXXXXX")" ip="$TMPD/icpt"; mkdir -p "$ip" @@ -891,6 +909,7 @@ PYC check "Expect: 100-continue is answered 417, not stalled" "417" \ "$(pc "$A" "POST / HTTP/1.1\\r\\n${H}Content-Length: 1\\r\\nExpect: 100-continue\\r\\n\\r\\n")" kill "$px_pid" 2>/dev/null; wait "$px_pid" 2>/dev/null || true # 143 from the kill is expected + px_pid= check "proxy never logs a denied host name" "0" "$(grep -c 'evil' "$px_log")" # One verdict per refused case above: 3 CONNECT, 12 request-head, 4 path-rule, 1 Expect. check "every denial is logged by verdict, one per refused request" "20" "$(grep -cE '^DENY' "$px_log")" @@ -910,6 +929,25 @@ PYR )" || rb="(rebuild_request missing or failed)" check "the rebuilt request sets Host itself, drops hop-by-hop and Connection-named headers, keeps chunked framing" \ "chunked|POST /v1/x HTTP/1.1|Host: allowed.example|Authorization: Bearer t|X-Goog-Api-Client: a|Transfer-Encoding: chunked|Connection: close||" "$rb" + cl0="$(python3 -I - "$proxy_py" "$ip/leaf.pem" "$ip/leaf.key" <<'PYL' 2>/dev/null +import sys +src = open(sys.argv[1]).read().split("\nasyncio.run(main())", 1)[0] +sys.argv = ["x", "/dev/null", "/dev/null", "allowed.example", sys.argv[2], sys.argv[3], ""] +ns = {"__name__": "agy_egress_test"} +exec(compile(src, "proxy", "exec"), ns) +for head in (b"POST /v1/x HTTP/1.1\r\nHost: allowed.example\r\nContent-Length: 0\r\n\r\n", + b"POST /v1/x HTTP/1.1\r\nHost: allowed.example\r\n\r\n", + b"GET /v1/x HTTP/1.1\r\nHost: allowed.example\r\n\r\n"): + out, kind, n = ns["rebuild_request"](head, "allowed.example") + print(kind + "|" + "|".join(out.decode().split("\r\n"))) +PYL +)" || cl0="(rebuild_request missing or failed)" + check "an empty POST keeps Content-Length: 0 (Google answers 411 without it)" \ + "none|POST /v1/x HTTP/1.1|Host: allowed.example|Content-Length: 0|Connection: close||" "$(printf '%s\n' "$cl0" | sed -n 1p)" + check "a POST with no length header is sent with Content-Length: 0" \ + "none|POST /v1/x HTTP/1.1|Host: allowed.example|Content-Length: 0|Connection: close||" "$(printf '%s\n' "$cl0" | sed -n 2p)" + check "a GET with no body gets no framing header" \ + "none|GET /v1/x HTTP/1.1|Host: allowed.example|Connection: close||" "$(printf '%s\n' "$cl0" | sed -n 3p)" # copy_chunked on real streams (round 9): a trailer after the last chunk is consumed and NOT # forwarded, exactly the terminating `0\r\n\r\n` goes upstream, and the bytes of a following # request stay unread (never smuggled upstream behind the body). @@ -952,7 +990,9 @@ PYC check "a data chunk is forwarded without its extension, then the terminator; the next request stays unread" \ "b'3\\r\\nabc\\r\\n0\\r\\n\\r\\n'|b'GET /next HTTP/1.1\\r\\n'" "$(printf '%s\n' "$cc" | sed -n 2p)" fi - rm -rf -- "$sockd" + rm -rf -- "$sockd"; sockd= +else + echo " skip the egress-proxy cases: they need python3 >= 3.11 and openssl" fi # A jail launch diagnostic is never accepted as a review (Codex P2), and cleanup survives a dead proxy. jf="$TMPD/jail-fail.txt" @@ -964,6 +1004,17 @@ printf '## Review\n\nThe bwrap: prefix appears only mid-review here.\nbwrap: not check "a review that merely mentions bwrap is not a jail failure" "no" "$(agy_jail_failed "$jf" && echo yes || echo no)" check "the capture loop refuses a jail failure before any retry or post" "1" \ "$(grep -c '^ if agy_jail_failed "\$out_file"; then' "$SCRIPT")" +check "cleanup reaps both proxies before removing their runtime dir" "2" \ + "$(grep -cE '^ \[ -n "\$\{agy_(proxy|egress)_pid:-\}" \] && \{ wait "\$agy_(proxy|egress)_pid" 2>/dev/null \|\| true; \}$' "$SCRIPT")" +lock_line="$(grep -n '^flock -w "\$AGY_LOCK_WAIT" 9 || {$' "$SCRIPT" | head -1 | cut -d: -f1)" +jail_line="$(grep -n '^ agy_jail_rt="\$(mktemp -d' "$SCRIPT" | head -1 | cut -d: -f1)" +check "the agy lock is taken before the jail and its proxies are started" "yes" \ + "$([ -n "$lock_line" ] && [ -n "$jail_line" ] && [ "$lock_line" -lt "$jail_line" ] && echo yes || echo no)" +check "each attempt starts with no redactions recorded" "1" \ + "$(grep -c '^ redacted_kinds= # this attempt' "$SCRIPT")" +check "the last guard scans the assembled comment body" "1" \ + "$(grep -c '^if cred_kind="\$(credential_kind_present "\$body_file")"; then$' "$SCRIPT")" +check "an empty AGY_EGRESS_ALLOW is refused by name" "1" "$(grep -c 'AGY_EGRESS_ALLOW is empty; refusing' "$SCRIPT")" check "cleanup ignores a failed kill of either proxy (set -e safe)" "2" \ "$(grep -cE '^ \[ -n "\$\{agy_(proxy|egress)_pid:-\}" \] && \{ kill "\$agy_(proxy|egress)_pid" 2>/dev/null \|\| true; \}$' "$SCRIPT")" # Round-4 review fixes. @@ -1007,6 +1058,17 @@ check "denied-host log appends on a later run" "4" "$(wc -l < "$ddst" 2>/dev/nul for _ in $(seq 1 300); do agy_record_denied "$dsrc" "$ddst" "o/r#n"; done check "denied-host log keeps exactly the newest 500 records" "500" "$(wc -l < "$ddst")" check "the newest record survives trimming" "yes" "$(tail -n 1 "$ddst" | grep -q 'o/r#n other.example:443' && echo yes || echo no)" +# Round 10: control bytes never reach the host log, and a custom log path's directory is created. +printf 'evil\033]0;pwned\007.example:443\n' > "$dsrc" +ddst2="$TMPD/new/dir/agy-egress-denied.log" +agy_record_denied "$dsrc" "$ddst2" "o/r#c" || true # a failure is reported by the checks below +check "denied-host log creates a missing parent directory" "yes" "$([ -s "$ddst2" ] && echo yes || echo no)" +check "denied-host log strips control bytes from attacker-chosen targets" "0" \ + "$(LC_ALL=C grep -c "$(printf '[\001-\010\013-\037\177]')" "$ddst2" || true)" +printf 'a|b&c\\d.example:443\n' > "$dsrc" +agy_record_denied "$dsrc" "$ddst2" 'o/r|&\x' || true # a failure is reported by the checks below +check "denied-host log prefixes a tag with sed metacharacters intact" "yes" \ + "$(tail -n 1 "$ddst2" | grep -qF 'o/r|&\x a|b&c\d.example:443' && echo yes || echo no)" # Redaction (redact-and-post): every positive shape is fully redacted, boundaries survive, and a # fixture-style JWT in an otherwise ordinary review leaves the rest of the text intact. rd="$TMPD/redact.txt" @@ -1026,6 +1088,15 @@ printf 'one\n-----BEGIN RSA ''PRIVATE KEY-----\nMIIEabc\n' > "$rd" agy_redact_credentials "$rd" check "an unterminated private key is removed to the end, and the comment says text was removed" \ "one|[REDACTED: private-key-block]|[REDACTED: the rest of this review was removed: it quoted the start of a private key with no END line]" "$(paste -sd'|' "$rd")" +# Round 10: an END followed by a second BEGIN on the same line must not hide the second key. +printf -- '-----BEGIN RSA ''PRIVATE KEY-----\nAAAA\n-----END RSA ''PRIVATE KEY----- x -----BEGIN EC ''PRIVATE KEY-----\nBBBB\n-----END EC ''PRIVATE KEY-----\ntwo\n' > "$rd" +agy_redact_credentials "$rd" +check "a second private key opened on the first key's END line is redacted too" \ + "[REDACTED: private-key-block]| x [REDACTED: private-key-block]|two" "$(paste -sd'|' "$rd")" +printf 'a -----BEGIN RSA ''PRIVATE KEY-----K1-----END RSA ''PRIVATE KEY----- b -----BEGIN RSA ''PRIVATE KEY-----K2-----END RSA ''PRIVATE KEY----- c\n' > "$rd" +agy_redact_credentials "$rd" +check "two one-line private keys on one line keep the text between them" \ + "a [REDACTED: private-key-block] b [REDACTED: private-key-block] c" "$(cat "$rd")" printf 'keys %s.%s and %s\n' "AKI""AABCDEFGHIJKLMNOP" "AKI""AQRSTUVWXYZ234567" "gh""p_$(printf 'c%.0s' {1..36})" > "$rd" agy_redact_credentials "$rd" check "adjacent matches are all redacted, boundaries kept" "keys [REDACTED: aws-access-key-id].[REDACTED: aws-access-key-id] and [REDACTED: github-token]" "$(cat "$rd")" @@ -1039,6 +1110,9 @@ check "redaction works in memory, with no scratch file" "0" \ "$(sed -n '/^agy_redact_credentials() {/,/^}/p' "$SCRIPT" | grep -cE 'mktemp|\.redact|> *"\$tmp"')" # Credential scan: every shape is caught, ordinary review text is not. cred_tmp="$TMPD/cred.txt" +printf 'key AKIA%s and gh''p_%s here\n' "$(printf 'Q%.0s' {1..16})" "$(printf 'k%.0s' {1..36})" > "$cred_tmp" +check "every credential kind present is named, not only the first" "github-token, aws-access-key-id" \ + "$(credential_kinds_present "$cred_tmp")" # Samples are assembled at runtime from split pieces, so this file never contains a literal that a # repository secret scanner (gitleaks) would flag. s_jwt="eyJ""hbGciOiJIUzI1NiJ9.""eyJ""zdWIiOiIxMjM0NTY3ODkwIn0.abcdefghijklmnop" @@ -1047,7 +1121,8 @@ s_key="-----BEGIN OPENSSH ""PRIVATE KEY-----" for sample in "token ya2""9.$(printf 'a%.0s' {1..30})" "refresh 1/""/0$(printf 'b%.0s' {1..30})" \ "gh""p_$(printf 'c%.0s' {1..36})" "github""_pat_$(printf 'd%.0s' {1..50})" \ "$s_key" "$s_jwt" "key $s_aws." "sk-a""nt-$(printf 'e%.0s' {1..40})" \ - "sk-pro""j-$(printf 'f%.0s' {1..40})" "xox""b-1234567890-abcdef"; do + "sk-pro""j-$(printf 'f%.0s' {1..40})" "xox""b-1234567890-abcdef" \ + "sk-pro""j-$(printf 'aB3_-%.0s' {1..9})" "sk-svc""acct-$(printf 'Zq9-_%.0s' {1..8})"; do printf '## Review\n\nfound %s here\n' "$sample" > "$cred_tmp" check "credential scan catches: ${sample:0:14}..." "yes" \ "$(credential_kind_present "$cred_tmp" >/dev/null && echo yes || echo no)" diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index f48cb965..5472b9b8 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -160,9 +160,13 @@ agy_record_denied() { stamp="$(date -u +%FT%TZ)" ( umask 077 + mkdir -p -- "$(dirname -- "$dst")" || exit 1 { if [ -f "$dst" ]; then cat "$dst"; fi - sort -u "$src" | cut -c1-253 | sed "s|^|${stamp} ${tag} |" + # Control bytes are stripped: a denied target is attacker-chosen, and raw escape sequences + # would act on the terminal of whoever later reads this log. + LC_ALL=C tr -d '\000-\010\013-\037\177' < "$src" | sort -u | cut -c1-253 \ + | AGY_DENIED_PREFIX="${stamp} ${tag} " awk '{ print ENVIRON["AGY_DENIED_PREFIX"] $0 }' # not -v: it would expand backslashes } > "$dst.new" || exit 1 tail -n 500 "$dst.new" > "$dst.tmp" && mv -f "$dst.tmp" "$dst" && rm -f -- "$dst.new" ) @@ -196,7 +200,7 @@ private-key-block~~-----BEGIN [A-Z ]*PRIVATE KEY-----~ jwt~(^|[^A-Za-z0-9_-])~eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}~ aws-access-key-id~(^|[^A-Za-z0-9])~(AKIA|ASIA)[0-9A-Z]{16}~([^A-Za-z0-9]|$) anthropic-key~(^|[^A-Za-z0-9_-])~sk-ant-[A-Za-z0-9_-]{32,}~ -openai-key~(^|[^A-Za-z0-9_-])~sk-(proj-)?[A-Za-z0-9]{32,}~([^A-Za-z0-9_-]|$) +openai-key~(^|[^A-Za-z0-9_-])~sk-(proj-|svcacct-|admin-)?[A-Za-z0-9_-]{32,}~([^A-Za-z0-9_-]|$) slack-token~(^|[^A-Za-z0-9_-])~xox[abprs]-[A-Za-z0-9-]{10,}~ CREDS } @@ -208,6 +212,15 @@ credential_kind_present() { done < <(agy_credential_patterns) return 1 } +# Every kind present in $1, comma-separated (empty when none): the note names all of them. +credential_kinds_present() { + [ -s "$1" ] || return 0 + local kind lead core trail found="" + while IFS='~' read -r kind lead core trail; do + grep -qE -- "${lead}${core}${trail}" "$1" && found="${found:+$found, }$kind" + done < <(agy_credential_patterns) + printf '%s' "$found" +} # Replace every credential-shaped string in $1 (in place) with `[REDACTED: ]`, keeping the # boundary characters. A private-key block is replaced whole, from its BEGIN line through its END # line (or to the end of the text, which fails safe). Several passes, because adjacent matches @@ -220,14 +233,28 @@ agy_redact_credentials() { for pass in 1 2 3; do while IFS='~' read -r kind lead core trail; do if [ "$kind" = private-key-block ]; then - # awk, not a sed range: a one-line block (BEGIN and END on the same line) is replaced in - # place, a multi-line block becomes one marker line, and a block with NO END line removes - # the rest of the text but SAYS so, so the review can never be silently cut short. + # awk, not a sed range. Each line is scanned left to right: text before a BEGIN is kept and + # the block becomes one marker; inside a block everything up to its END is dropped, and the + # scan resumes AFTER the END, so a second BEGIN on that same line (or a second one-line key) + # is caught too. A line wholly inside a block prints nothing. A block with NO END line + # removes the rest of the text but SAYS so, so the review can never be silently cut short. buf="$(awk -v b="$core" -v e='-----END [A-Z ]*PRIVATE KEY-----' -v m="[REDACTED: ${kind}]" ' - inblk { if ($0 ~ e) inblk = 0; next } - { gsub(b ".*" e, m) } - $0 ~ b { print m; inblk = 1; if ($0 ~ e) inblk = 0; next } - { print } + { + line = $0; out = ""; emit = !inblk + while (1) { + if (inblk) { + if (match(line, e)) { line = substr(line, RSTART + RLENGTH); inblk = 0; continue } + break + } + if (match(line, b)) { + out = out substr(line, 1, RSTART - 1) m; emit = 1 + line = substr(line, RSTART + RLENGTH); inblk = 1; continue + } + if (line != "") { out = out line; emit = 1 } + break + } + if (emit) print out + } END { if (inblk) print "[REDACTED: the rest of this review was removed: it quoted the start of a private key with no END line]" } ' "$f" && printf x)" || return 1 else @@ -469,7 +496,7 @@ REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY not set}" # _perm_err so cleanup() could never see it (agy review, GH-ListRollup PR #6). # Remove every temp file on exit. Pre-declared so the trap is safe under `set -u` even if the # script exits before a given file is created. -diff_file= diff_err= meta_file= prompt_file= out_file= raw= body_file= agy_diff_file= agy_sandbox= agy_jail_home= agy_jail_rt= agy_proxy_pid= agy_egress_pid= jq_err= log_tail= redacted_kinds= left= prior_body_file= archived_file= api_err= +diff_file= diff_err= meta_file= prompt_file= out_file= raw= body_file= agy_diff_file= agy_sandbox= agy_jail_home= agy_jail_rt= agy_proxy_pid= agy_egress_pid= jq_err= log_tail= redacted_kinds= cred_kinds= left= prior_body_file= archived_file= api_err= # Also created mid-flight (permission lookup, compare-API merge base, archive trimming); a signal # or abort while one of those commands runs would otherwise leak the file in /tmp. _perm_err='' compare_err='' trimmed='' @@ -535,6 +562,9 @@ cleanup() { # before the jail home and runtime dirs below are removed. [ -n "${agy_proxy_pid:-}" ] && { kill "$agy_proxy_pid" 2>/dev/null || true; } [ -n "${agy_egress_pid:-}" ] && { kill "$agy_egress_pid" 2>/dev/null || true; } + # Reap them before their runtime dir goes, so no in-flight log write races the removal. + [ -n "${agy_proxy_pid:-}" ] && { wait "$agy_proxy_pid" 2>/dev/null || true; } + [ -n "${agy_egress_pid:-}" ] && { wait "$agy_egress_pid" 2>/dev/null || true; } [ -n "${agy_jail_home:-}" ] && [ -d "$agy_jail_home" ] && rm -rf -- "$agy_jail_home" [ -n "${agy_jail_rt:-}" ] && [ -d "$agy_jail_rt" ] && rm -rf -- "$agy_jail_rt" if [ -n "${agy_refs_created:-}" ] && [ -n "${PR:-}" ]; then @@ -1385,7 +1415,9 @@ def rebuild_request(head, host): ): raise Refuse framing = [] - if kind == "length": + if kind == "length" or ( + kind == "none" and (lengths or method in ("POST", "PUT", "PATCH")) + ): framing = [f"Content-Length: {length}"] elif kind == "chunked": framing = ["Transfer-Encoding: chunked"] @@ -1469,7 +1501,10 @@ async def handle(cr, cw): if port != "443" or host not in allow: log("DENY", host) if deniedf is not None: - deniedf.write(parts[1][:300] + "\n") + # attacker-chosen: only printable characters reach the host log + deniedf.write( + "".join(c if c.isprintable() else "?" for c in parts[1][:300]) + "\n" + ) await refuse(cw, b"HTTP/1.1 403 Forbidden") return uw = None @@ -1531,6 +1566,39 @@ asyncio.run(main()) AGYPY } +# Serialize agy across concurrent review jobs on this host. Taken BEFORE the jail is built, so +# its proxies and per-run CA are not left idling for the whole wait. agy runs a SINGLETON +# local language-server + conversation store per user, so two `--print` calls at +# once collide (one reports the backend "unavailable"). flock makes jobs queue +# instead of failing. FAIL CLOSED: if flock is missing, or the lock can't be +# taken/times out, exit rather than let two agy processes race each other -- +# a fail-open here made the exact collision this lock exists to prevent still +# reachable (one run can burn the whole ${AGY_RETRIES}x${AGY_LOCK_WAIT}s wait). +command -v flock >/dev/null 2>&1 || { + log "flock is required to serialize agy; refusing to run unserialized" + exit 1 +} +# Create the lock dir first: a failed `exec 9>` redirection is a FATAL shell error (it aborts +# before the `|| log` fallback can run), so ensure the parent exists on a fresh runner. `>>` opens +# for append rather than truncating the lockfile — flock uses the fd, not the contents. +# Validated before use: an empty `AGY_LOCK` (an env override set to "") would make `dirname` +# yield "." and the redirection below fail with an obscure shell error, at the one point where a +# clear message matters -- this is the guard that keeps two agy runs off each other. +if [ -z "$AGY_LOCK" ]; then + log "AGY_LOCK is empty; refusing to run unserialized" + exit 1 +fi +mkdir -p "$(dirname "$AGY_LOCK")" +exec 9>>"$AGY_LOCK" +flock -w "$AGY_LOCK_WAIT" 9 || { + log "agy lock timed out after ${AGY_LOCK_WAIT}s" + exit 1 +} + +# One resolution of the script directory, shared by the jail bind and the script(1) fallback, so a +# symlinked checkout path cannot make them name different files. +here="$(cd "$(dirname "$0")" && pwd)" +[ "$AGY_ISOLATION" = none ] && log "WARNING: AGY_ISOLATION=none: agy runs unjailed, with the host's files, keyring and network; AGY_EGRESS has no effect" # --- the bubblewrap jail (AGY_ISOLATION=bwrap) -------------------------------------------------- # Verified 2026-11-22: inside this jail agy authenticates and reviews, sees only an empty HOME, has # no MCP servers/skills/hooks, cannot read any host file outside the jail, and over D-Bus can fetch @@ -1588,6 +1656,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then || { log "invalid AGY_EGRESS_ALLOW entry '$_h' (exact lowercase host names only, no wildcards)"; exit 1; } _allow="${_allow:+$_allow,}$_h" done + [ -n "$_allow" ] || { log "AGY_EGRESS_ALLOW is empty; refusing to run agy with no reachable host"; exit 1; } _prules="" for _r in $AGY_EGRESS_PATH_RULES; do [[ "$_r" =~ ^([a-z0-9.-]+)=(/[A-Za-z0-9._~/-]*)$ ]] \ @@ -1631,7 +1700,6 @@ if [ "$AGY_ISOLATION" = bwrap ]; then _egress_env=( "HTTPS_PROXY=http://127.0.0.1:3128" "https_proxy=http://127.0.0.1:3128" "HTTP_PROXY=http://127.0.0.1:3128" "http_proxy=http://127.0.0.1:3128" "NO_PROXY=" "no_proxy=" "SSL_CERT_FILE=/run/agy-ca-bundle.pem" ) - # Inside the jail: bridge loopback 3128 to the proxy socket, wait for it, then exec the payload. # Inside the jail: bridge loopback 3128 to the proxy socket and wait for it. If the bridge never # comes up, say so with the `agy-jail:` prefix (agy_jail_failed) instead of launching agy anyway. _inner=( /usr/bin/bash -c 'socat TCP-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:/run/agy-egress.sock 2>/dev/null & up=0; for _ in $(seq 1 100); do if (exec 3<>/dev/tcp/127.0.0.1/3128) 2>/dev/null; then up=1; break; fi; sleep 0.1; done; [ "$up" = 1 ] || { echo "agy-jail: the egress bridge did not start" >&2; exit 1; }; exec "$@"' agy-jail ) @@ -1649,7 +1717,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then --ro-bind /etc /etc --proc /proc --dev /dev --tmpfs /tmp --tmpfs /home --bind "$agy_jail_home" "$HOME" --ro-bind "$(readlink -f "$AGY_BIN")" "$AGY_BIN" - --ro-bind "$(cd "$(dirname "$0")" && pwd)/_agy_print.sh" "$(cd "$(dirname "$0")" && pwd)/_agy_print.sh" + --ro-bind "$here/_agy_print.sh" "$here/_agy_print.sh" --ro-bind "$prompt_file" "$prompt_file" --bind "$agy_sandbox" "$agy_sandbox" --chdir "$agy_sandbox" --dir "/run/user/$_uid" --ro-bind "$agy_jail_rt/bus" "/run/user/$_uid/bus" @@ -1663,42 +1731,15 @@ fi [ -n "$AGY_EFFORT" ] && flags+=( --effort "$AGY_EFFORT" ) out_file="$(mktemp)" -here="$(cd "$(dirname "$0")" && pwd)" : > "$LOG" -# Serialize agy across concurrent review jobs on this host. agy runs a SINGLETON -# local language-server + conversation store per user, so two `--print` calls at -# once collide (one reports the backend "unavailable"). flock makes jobs queue -# instead of failing. FAIL CLOSED: if flock is missing, or the lock can't be -# taken/times out, exit rather than let two agy processes race each other -- -# a fail-open here made the exact collision this lock exists to prevent still -# reachable (one run can burn the whole ${AGY_RETRIES}x${AGY_LOCK_WAIT}s wait). -command -v flock >/dev/null 2>&1 || { - log "flock is required to serialize agy; refusing to run unserialized" - exit 1 -} -# Create the lock dir first: a failed `exec 9>` redirection is a FATAL shell error (it aborts -# before the `|| log` fallback can run), so ensure the parent exists on a fresh runner. `>>` opens -# for append rather than truncating the lockfile — flock uses the fd, not the contents. -# Validated before use: an empty `AGY_LOCK` (an env override set to "") would make `dirname` -# yield "." and the redirection below fail with an obscure shell error, at the one point where a -# clear message matters -- this is the guard that keeps two agy runs off each other. -if [ -z "$AGY_LOCK" ]; then - log "AGY_LOCK is empty; refusing to run unserialized" - exit 1 -fi -mkdir -p "$(dirname "$AGY_LOCK")" -exec 9>>"$AGY_LOCK" -flock -w "$AGY_LOCK_WAIT" 9 || { - log "agy lock timed out after ${AGY_LOCK_WAIT}s" - exit 1 -} # Retry the whole agy attempt on empty/failed output: transient "agy is down" # (backend rate-limit / local-server contention) usually clears within seconds. # The flock (above) is held across all attempts, released after the loop. for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do : > "$out_file" # clear any partial output from a prior attempt + redacted_kinds= # this attempt's only: a discarded attempt's redactions must not reach the note if command -v unbuffer >/dev/null 2>&1; then log "running agy via unbuffer (allocates a PTY) [attempt ${attempt}/${AGY_RETRIES}]" @@ -1739,13 +1780,14 @@ for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do # A credential-shaped string is REDACTED, not fatal: the scan cannot tell a leaked secret from a # test fixture a PR adds (a sample JWT), and either way the string never reaches the comment. if cred_kind="$(credential_kind_present "$out_file")"; then + cred_kinds="$(credential_kinds_present "$out_file")" if ! agy_redact_credentials "$out_file" || left="$(credential_kind_present "$out_file")"; then log "refusing to post: a credential-shaped string (${left:-$cred_kind}) could not be redacted from agy's output. Nothing was posted." : > "$out_file" exit 1 fi - redacted_kinds="${redacted_kinds:+$redacted_kinds, }${cred_kind}" - log "redacted credential-shaped string(s) (${cred_kind}, and any others) from agy's output (attempt ${attempt}/${AGY_RETRIES}). If this PR adds sample tokens (test fixtures), that is the likely source; otherwise inspect the runner host, the diff may carry a prompt injection." + redacted_kinds="${cred_kinds:-$cred_kind}" + log "redacted credential-shaped string(s) (${redacted_kinds}) from agy's output (attempt ${attempt}/${AGY_RETRIES}). If this PR adds sample tokens (test fixtures), that is the likely source; otherwise inspect the runner host, the diff may carry a prompt injection." fi # A jail that never started (no user namespaces, a missing bind source, ...) prints its own # diagnostic, which the PTY capture keeps while `|| true` drops the exit status. Never let that @@ -1898,11 +1940,16 @@ body_file="$(mktemp)" fi printf '\n\nAutomated first-pass review by `agy` on a self-hosted runner -- not a human review.\n' } > "$body_file" -# Last-resort guard before ANY post path (edit-in-place or new comment). The capture loop already -# redacted every credential shape, so reaching this means redaction missed one: fail closed. -if cred_kind="$(credential_kind_present "$out_file")"; then - log "refusing to post: agy's output contains a credential-shaped string (${cred_kind}). Nothing was posted. Inspect the runner host; the diff may carry a prompt injection." - exit 1 +# Last-resort guard before ANY post path (edit-in-place or new comment), on the BODY that is posted: +# agy's output was redacted in the capture loop, but the header and the archived earlier rounds +# were not. Those rounds were posted by an earlier template whose patterns may have been narrower, +# so a match there is redacted too; anything redaction cannot remove fails closed. +if cred_kind="$(credential_kind_present "$body_file")"; then + if ! agy_redact_credentials "$body_file" || left="$(credential_kind_present "$body_file")"; then + log "refusing to post: the comment body contains a credential-shaped string (${left:-$cred_kind}) that could not be redacted. Nothing was posted. Inspect the runner host; the diff may carry a prompt injection." + exit 1 + fi + log "redacted a credential-shaped string (${cred_kind}) from the assembled comment body (header or archived rounds)" fi # Final hard guard — the last line of defense, and UNCONDITIONAL, run BEFORE anything is From 8a62d6515b067de5b0c5875e955be468a82774e8 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 22:05:09 -0500 Subject: [PATCH 12/14] ci: re-sync the reviewer to template b940416 Re-syncs the vendored reviewer scripts byte for byte from the antigravity-pr-review template at b940416 (round 11). Local workflow overrides are unchanged. - The archived earlier rounds are now redacted, and the assembled comment body is scanned after they are appended. 2a366ac's guard ran before the append and so never saw the archive. - Egress proxy: the CONNECT host is matched case-insensitively, bytes pipelined behind a CONNECT are refused, and a duplicate path rule for one host is refused. - Both proxies stop once agy finishes; a dead proxy ends the startup wait at once; a missing AGY_BIN is refused before the jail is built. Verification: agy-review-selftest.sh all checks passed; actionlint clean; a live jailed review from the same scripts completed and cleaned up after itself. Co-Authored-By: Claude Opus 5.5 --- scripts/agy-review-selftest.sh | 39 ++++++++++++++++++++--- scripts/agy-review.sh | 58 +++++++++++++++++++++++++++------- 2 files changed, 81 insertions(+), 16 deletions(-) diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index 8a7d7d97..bab648ee 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -879,6 +879,16 @@ PYC check "proxy refuses an unlisted host" "403" "$(pc 'secret-token-in-name.evil.example:443' -)" check "proxy refuses a suffix of an allowed host" "403" "$(pc 'x.allowed.example:443' -)" check "proxy refuses an allowed host on another port" "403" "$(pc 'allowed.example:80' -)" + check "proxy matches an allowed host case-insensitively" "200" "$(pc 'ALLOWED.Example:443' -)" + pipelined="$(python3 -I - "$sockd/p.sock" <<'PYP' 2>/dev/null || echo error +import socket, sys +s = socket.socket(socket.AF_UNIX); s.settimeout(10); s.connect(sys.argv[1]) +s.sendall(b"CONNECT allowed.example:443 HTTP/1.1\r\nHost: allowed.example:443\r\n\r\nGET / HTTP/1.1\r\n\r\n") +first = s.recv(4096).split(b"\r\n", 1)[0].split(b" ") +print(first[1].decode() if len(first) > 1 else "closed") +PYP +)" + check "bytes pipelined behind CONNECT are refused, not fed to TLS" "400" "$pipelined" check "fronting refused: foreign Host on an allowed connection" "403" \ "$(pc "$A" 'GET /storage/v1/b/x HTTP/1.1\r\nHost: storage.googleapis.com\r\n\r\n')" check "fronting refused: bucket subdomain Host" "403" \ @@ -911,8 +921,8 @@ PYC kill "$px_pid" 2>/dev/null; wait "$px_pid" 2>/dev/null || true # 143 from the kill is expected px_pid= check "proxy never logs a denied host name" "0" "$(grep -c 'evil' "$px_log")" - # One verdict per refused case above: 3 CONNECT, 12 request-head, 4 path-rule, 1 Expect. - check "every denial is logged by verdict, one per refused request" "20" "$(grep -cE '^DENY' "$px_log")" + # One verdict per refused case above: 3 CONNECT, 1 pipelined, 12 request-head, 4 path-rule, 1 Expect. + check "every denial is logged by verdict, one per refused request" "21" "$(grep -cE '^DENY' "$px_log")" # rebuild_request, unit level: Host set by the proxy, hop-by-hop dropped, framing canonical. rb="$(python3 -I - "$proxy_py" "$ip/leaf.pem" "$ip/leaf.key" <<'PYR' 2>/dev/null import sys @@ -1006,15 +1016,34 @@ check "the capture loop refuses a jail failure before any retry or post" "1" \ "$(grep -c '^ if agy_jail_failed "\$out_file"; then' "$SCRIPT")" check "cleanup reaps both proxies before removing their runtime dir" "2" \ "$(grep -cE '^ \[ -n "\$\{agy_(proxy|egress)_pid:-\}" \] && \{ wait "\$agy_(proxy|egress)_pid" 2>/dev/null \|\| true; \}$' "$SCRIPT")" -lock_line="$(grep -n '^flock -w "\$AGY_LOCK_WAIT" 9 || {$' "$SCRIPT" | head -1 | cut -d: -f1)" -jail_line="$(grep -n '^ agy_jail_rt="\$(mktemp -d' "$SCRIPT" | head -1 | cut -d: -f1)" +lock_line="$(grep -n '^flock -w "\$AGY_LOCK_WAIT" 9 || {$' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +jail_line="$(grep -n '^ agy_jail_rt="\$(mktemp -d' "$SCRIPT" | head -1 | cut -d: -f1 || true)" check "the agy lock is taken before the jail and its proxies are started" "yes" \ "$([ -n "$lock_line" ] && [ -n "$jail_line" ] && [ "$lock_line" -lt "$jail_line" ] && echo yes || echo no)" check "each attempt starts with no redactions recorded" "1" \ "$(grep -c '^ redacted_kinds= # this attempt' "$SCRIPT")" -check "the last guard scans the assembled comment body" "1" \ +check "the new round's head is scanned before any post path" "1" \ "$(grep -c '^if cred_kind="\$(credential_kind_present "\$body_file")"; then$' "$SCRIPT")" +# Round 11 (agy, wave A): the archive is redacted before trimming, and the assembled body is scanned +# AFTER the archive is appended -- an ordering check, since a presence check passed with the scan +# placed before the append. +arch_red="$(grep -n '^ if cred_kind="\$(credential_kind_present "\$archived_file")"; then$' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +arch_trim="$(grep -n '^ combined_size=\$(( \$(wc -c < "\$body_file")' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +arch_app="$(grep -n '^ } >> "\$body_file"$' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +final_scan="$(grep -n '^ if cred_kind="\$(credential_kind_present "\$body_file")"; then$' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +check "archived rounds are redacted before the size trimming" "yes" \ + "$([ -n "$arch_red" ] && [ -n "$arch_trim" ] && [ "$arch_red" -lt "$arch_trim" ] && echo yes || echo no)" +check "the assembled body is scanned after the archive is appended" "yes" \ + "$([ -n "$final_scan" ] && [ -n "$arch_app" ] && [ "$final_scan" -gt "$arch_app" ] && echo yes || echo no)" check "an empty AGY_EGRESS_ALLOW is refused by name" "1" "$(grep -c 'AGY_EGRESS_ALLOW is empty; refusing' "$SCRIPT")" +check "a second path rule for the same host is refused" "1" "$(grep -c "names '\${_rh}' twice (one exact path per host)" "$SCRIPT")" +check "a missing AGY_BIN is refused before the jail is built" "1" "$(grep -c 'is not an executable file on the runner host; refusing to build the jail' "$SCRIPT")" +check "the proxy startup waits stop as soon as the proxy has exited" "2" \ + "$(grep -cE 'kill -0 "\$agy_(proxy|egress)_pid" 2>/dev/null \|\| break; sleep 0.1; done$' "$SCRIPT")" +stop_line="$(grep -n '^for _pp in "\${agy_egress_pid:-}" "\${agy_proxy_pid:-}"; do$' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +sum_line="$(grep -n '^# Egress summary: verdict COUNTS only' "$SCRIPT" | head -1 | cut -d: -f1 || true)" +check "both proxies are stopped once agy is done, before the egress summary" "yes" \ + "$([ -n "$stop_line" ] && [ -n "$sum_line" ] && [ "$stop_line" -lt "$sum_line" ] && echo yes || echo no)" check "cleanup ignores a failed kill of either proxy (set -e safe)" "2" \ "$(grep -cE '^ \[ -n "\$\{agy_(proxy|egress)_pid:-\}" \] && \{ kill "\$agy_(proxy|egress)_pid" 2>/dev/null \|\| true; \}$' "$SCRIPT")" # Round-4 review fixes. diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index 5472b9b8..4718daad 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -1498,6 +1498,7 @@ async def handle(cr, cw): await refuse(cw, b"HTTP/1.1 405 Method Not Allowed") return host, _, port = parts[1].rpartition(":") + host = host.lower() # DNS names are case-insensitive; the allowlist is lowercase if port != "443" or host not in allow: log("DENY", host) if deniedf is not None: @@ -1507,6 +1508,12 @@ async def handle(cr, cw): ) await refuse(cw, b"HTTP/1.1 403 Forbidden") return + # Bytes sent behind the CONNECT, before its 200, would sit in the reader's buffer and be read + # after start_tls as if they were decrypted application data. No real client does this. + if getattr(cr, "_buffer", b""): + log("DENY-PIPELINED", host) + await refuse(cw, b"HTTP/1.1 400 Bad Request") + return uw = None try: cw.write(b"HTTP/1.1 200 Connection Established\r\n\r\n") @@ -1644,7 +1651,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then agy_jail_home="$(cd "$agy_jail_home" && pwd -P)" xdg-dbus-proxy "$DBUS_SESSION_BUS_ADDRESS" "$agy_jail_rt/bus" --filter "${_rules[@]}" & agy_proxy_pid=$! - for _ in $(seq 1 100); do [ -S "$agy_jail_rt/bus" ] && break; sleep 0.1; done + for _ in $(seq 1 100); do [ -S "$agy_jail_rt/bus" ] && break; kill -0 "$agy_proxy_pid" 2>/dev/null || break; sleep 0.1; done [ -S "$agy_jail_rt/bus" ] || { log "xdg-dbus-proxy did not start; refusing to run agy unjailed"; exit 1; } _uid="$(id -u)" _net=( --share-net --ro-bind-try /run/systemd/resolve /run/systemd/resolve ) @@ -1657,12 +1664,18 @@ if [ "$AGY_ISOLATION" = bwrap ]; then _allow="${_allow:+$_allow,}$_h" done [ -n "$_allow" ] || { log "AGY_EGRESS_ALLOW is empty; refusing to run agy with no reachable host"; exit 1; } - _prules="" + _prules="" _prhosts="" for _r in $AGY_EGRESS_PATH_RULES; do [[ "$_r" =~ ^([a-z0-9.-]+)=(/[A-Za-z0-9._~/-]*)$ ]] \ || { log "invalid AGY_EGRESS_PATH_RULES entry '$_r' (expected host=/exact/path)"; exit 1; } - [[ ",$_allow," == *",${BASH_REMATCH[1]},"* ]] \ - || { log "AGY_EGRESS_PATH_RULES names '${BASH_REMATCH[1]}', which is not in AGY_EGRESS_ALLOW"; exit 1; } + _rh="${BASH_REMATCH[1]}" + [[ ",$_allow," == *",${_rh},"* ]] \ + || { log "AGY_EGRESS_PATH_RULES names '${_rh}', which is not in AGY_EGRESS_ALLOW"; exit 1; } + # One path per host: the proxy keeps a single path for each, so a second rule would silently + # replace the first. + [[ ",$_prhosts," != *",${_rh},"* ]] \ + || { log "AGY_EGRESS_PATH_RULES names '${_rh}' twice (one exact path per host)"; exit 1; } + _prhosts="${_prhosts:+$_prhosts,}$_rh" _prules="${_prules:+$_prules,}$_r" done _san="DNS:${_allow//,/,DNS:}" @@ -1692,7 +1705,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then "$_pki/leaf.pem" "$_pki/leaf.key" "$_prules" \ 2>>"$LOG" & agy_egress_pid=$! - for _ in $(seq 1 100); do [ -S "$agy_jail_rt/egress.sock" ] && break; sleep 0.1; done + for _ in $(seq 1 100); do [ -S "$agy_jail_rt/egress.sock" ] && break; kill -0 "$agy_egress_pid" 2>/dev/null || break; sleep 0.1; done [ -S "$agy_jail_rt/egress.sock" ] || { log "egress proxy did not start; refusing to run agy"; exit 1; } _net=() # --unshare-all without --share-net: the jail has only its own loopback _egress_binds=( --ro-bind "$agy_jail_rt/egress.sock" /run/agy-egress.sock @@ -1712,6 +1725,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then elif [ -d "$_d" ]; then _toplevel+=( --ro-bind "$_d" "$_d" ) fi done + [ -x "$AGY_BIN" ] || { log "AGY_BIN ($AGY_BIN) is not an executable file on the runner host; refusing to build the jail"; exit 1; } agy_jail=( bwrap --unshare-all "${_net[@]}" --die-with-parent --new-session --ro-bind /usr /usr "${_toplevel[@]}" --ro-bind /etc /etc --proc /proc --dev /dev --tmpfs /tmp @@ -1725,7 +1739,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then # Inside the jail, D-Bus is the filtered proxy (later env assignments override earlier ones). agy_env+=( "XDG_RUNTIME_DIR=/run/user/$_uid" "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$_uid/bus" "TMPDIR=/tmp" "${_egress_env[@]}" ) log "agy isolation: bwrap jail, empty HOME, D-Bus limited to ${#_items[@]} keyring item(s), egress ${AGY_EGRESS}" - unset _t _need _dict _kv _items _rules _it _uid _net _egress_binds _egress_env _inner _allow _h _ca_sys _c _pki _toplevel _d _prules _r _san + unset _t _need _dict _kv _items _rules _it _uid _net _egress_binds _egress_env _inner _allow _h _ca_sys _c _pki _toplevel _d _prules _r _san _rh _prhosts fi [ -n "$AGY_MODEL" ] && flags+=( --model "$AGY_MODEL" ) [ -n "$AGY_EFFORT" ] && flags+=( --effort "$AGY_EFFORT" ) @@ -1848,6 +1862,13 @@ for (( attempt=1; attempt<=AGY_RETRIES; attempt++ )); do sleep "$delay" fi done +# agy is done: stop both proxies now rather than at exit, so nothing outlives the review and the +# egress log is final before it is summarized (it is line-buffered, so no record is lost). +for _pp in "${agy_egress_pid:-}" "${agy_proxy_pid:-}"; do + if [ -n "$_pp" ]; then kill "$_pp" 2>/dev/null || true; wait "$_pp" 2>/dev/null || true; fi +done +agy_egress_pid= agy_proxy_pid= +unset _pp # Egress summary: verdict COUNTS only. A denied host name or path is attacker-chosen and could # carry a secret, and this log is public on a public repository, so names are never printed. # Denied names go ONLY to a host-private log (mode 600, beside agy's own state), so a new host @@ -1940,16 +1961,15 @@ body_file="$(mktemp)" fi printf '\n\nAutomated first-pass review by `agy` on a self-hosted runner -- not a human review.\n' } > "$body_file" -# Last-resort guard before ANY post path (edit-in-place or new comment), on the BODY that is posted: -# agy's output was redacted in the capture loop, but the header and the archived earlier rounds -# were not. Those rounds were posted by an earlier template whose patterns may have been narrower, -# so a match there is redacted too; anything redaction cannot remove fails closed. +# Guard on the new round's body (header + review), before ANY post path. agy's output was redacted +# in the capture loop; this covers the header too. The archived earlier rounds are appended later +# and are redacted on their own (below), and the assembled body is scanned once more before posting. if cred_kind="$(credential_kind_present "$body_file")"; then if ! agy_redact_credentials "$body_file" || left="$(credential_kind_present "$body_file")"; then log "refusing to post: the comment body contains a credential-shaped string (${left:-$cred_kind}) that could not be redacted. Nothing was posted. Inspect the runner host; the diff may carry a prompt injection." exit 1 fi - log "redacted a credential-shaped string (${cred_kind}) from the assembled comment body (header or archived rounds)" + log "redacted a credential-shaped string (${cred_kind}) from the comment head" fi # Final hard guard — the last line of defense, and UNCONDITIONAL, run BEFORE anything is @@ -2024,6 +2044,16 @@ if [ -n "$prior_id" ] && [ -s "$prior_body_file" ]; then archived_file="$(mktemp)" agy_assemble_archive "$prior_head" "$prior_archive" "$(date -u +'%Y-%m-%d %H:%M UTC')" \ > "$archived_file" + # Earlier rounds were posted by earlier templates, whose patterns may have been narrower (the + # OpenAI pattern missed base64url keys until 2a366ac), so they are redacted too -- here, before + # the size trimming below, because a marker is longer than what it replaces. + if cred_kind="$(credential_kind_present "$archived_file")"; then + if ! agy_redact_credentials "$archived_file" || left="$(credential_kind_present "$archived_file")"; then + log "refusing to post: an archived earlier round contains a credential-shaped string (${left:-$cred_kind}) that could not be redacted. Nothing was posted." + exit 1 + fi + log "redacted a credential-shaped string (${cred_kind}) from the archived earlier rounds" + fi # Drop the oldest rounds until the whole comment fits, and SAY SO. A silent truncation # here would look identical to "there were never any earlier rounds", which is the exact @@ -2072,6 +2102,12 @@ if [ -n "$prior_id" ] && [ -s "$prior_body_file" ]; then log "refusing to post: the assembled comment body contains a live OAuth authorization URL." exit 1 fi + # And the credential scan, on exactly what is published: every part was redacted above, so a + # match here means redaction missed one. Fail closed. + if cred_kind="$(credential_kind_present "$body_file")"; then + log "refusing to post: the assembled comment body contains a credential-shaped string (${cred_kind}). Nothing was posted." + exit 1 + fi # The body goes through STDIN as JSON, never through argv. At `MAX_BODY_BYTES` # the comment can approach 60 KB, and a single execve argument is capped at From 84d40d9e8dcb016ecba9de1a3a69a2b07b3f6af2 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 22:43:10 -0500 Subject: [PATCH 13/14] ci: re-sync the reviewer to template a7d5273 Re-syncs the vendored reviewer scripts byte for byte from the antigravity-pr-review template at a7d5273 (round 12). Local workflow overrides are unchanged. - AGY_KEYRING_ATTRS, AGY_EGRESS_ALLOW and AGY_EGRESS_PATH_RULES are split with `read -r -a` instead of an unquoted `for`, which globbed. Before, a wildcard such as `*.com` could expand to a file name in the checkout and pass the exact-host validation. - The public stderr tail is withheld when the whole agy log, not just the tail, carries a credential shape. Verification: agy-review-selftest.sh all checks passed; actionlint clean; a live jailed review from the same scripts completed and cleaned up after itself. Co-Authored-By: Claude Opus 5.5 --- scripts/agy-review-selftest.sh | 8 +++++++- scripts/agy-review.sh | 18 +++++++++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index bab648ee..8a35341f 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -1037,6 +1037,12 @@ check "the assembled body is scanned after the archive is appended" "yes" \ "$([ -n "$final_scan" ] && [ -n "$arch_app" ] && [ "$final_scan" -gt "$arch_app" ] && echo yes || echo no)" check "an empty AGY_EGRESS_ALLOW is refused by name" "1" "$(grep -c 'AGY_EGRESS_ALLOW is empty; refusing' "$SCRIPT")" check "a second path rule for the same host is refused" "1" "$(grep -c "names '\${_rh}' twice (one exact path per host)" "$SCRIPT")" +check "list settings are split without pathname expansion" "0" \ + "$(grep -cE '^ *for _(kv|h|r) in \$AGY_' "$SCRIPT")" +check "list settings are read with read -a" "3" \ + "$(grep -cE '^ *read -r -a _(kvs|hs|rs) <<<"\$AGY_(KEYRING_ATTRS|EGRESS_ALLOW|EGRESS_PATH_RULES)"$' "$SCRIPT")" +check "the stderr tail is withheld when the WHOLE log carries a credential shape" "1" \ + "$(grep -c '^ if log_cred="\$(credential_kind_present "\$LOG")" || ' "$SCRIPT")" check "a missing AGY_BIN is refused before the jail is built" "1" "$(grep -c 'is not an executable file on the runner host; refusing to build the jail' "$SCRIPT")" check "the proxy startup waits stop as soon as the proxy has exited" "2" \ "$(grep -cE 'kill -0 "\$agy_(proxy|egress)_pid" 2>/dev/null \|\| break; sleep 0.1; done$' "$SCRIPT")" @@ -1064,7 +1070,7 @@ agy_redact_credentials "$grow" check "(why) the same error, redacted, has grown past the size guard" "no" \ "$(service_error_present "$grow" && echo yes || echo no)" check "the public stderr tail is scanned from a regular file and withheld on a match" "1" \ - "$(grep -c '^ if log_cred="\$(credential_kind_present "\$log_tail")"; then' "$SCRIPT")" + "$(grep -c '|| log_cred="\$(credential_kind_present "\$log_tail")"; then$' "$SCRIPT")" check "an empty AGY_KEYRING_ATTRS is refused (SearchItems {} matches every item)" "1" \ "$(grep -c 'AGY_KEYRING_ATTRS is empty; refusing to grant agy keyring access' "$SCRIPT")" check "agy gets TMPDIR=/tmp inside the jail" "1" "$(grep -c '"TMPDIR=/tmp"' "$SCRIPT")" diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index 4718daad..16075ec0 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -1626,7 +1626,11 @@ if [ "$AGY_ISOLATION" = bwrap ]; then || { log "AGY_ISOLATION=bwrap needs XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS (a user session)"; exit 1; } # agy's own keyring item(s), resolved OUTSIDE the jail: object paths only, never secrets. _dict="" - for _kv in $AGY_KEYRING_ATTRS; do + # Split on whitespace with NO pathname expansion (read -a, not an unquoted for): `for x in $VAR` + # globs, so a wildcard entry (`*.com`) would expand to file names in the checkout -- which the PR + # controls -- and then pass validation as an exact value. + read -r -a _kvs <<<"$AGY_KEYRING_ATTRS" + for _kv in "${_kvs[@]}"; do [[ "$_kv" =~ ^[A-Za-z0-9_.-]+=[A-Za-z0-9_.:@-]+$ ]] || { log "invalid AGY_KEYRING_ATTRS entry '$_kv'"; exit 1; } _dict="${_dict:+$_dict, }'${_kv%%=*}': '${_kv#*=}'" done @@ -1658,14 +1662,16 @@ if [ "$AGY_ISOLATION" = bwrap ]; then _egress_binds=() _egress_env=() _inner=() if [ "$AGY_EGRESS" = filtered ]; then _allow="" - for _h in $AGY_EGRESS_ALLOW; do + read -r -a _hs <<<"$AGY_EGRESS_ALLOW" + for _h in "${_hs[@]}"; do [[ "$_h" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$ ]] \ || { log "invalid AGY_EGRESS_ALLOW entry '$_h' (exact lowercase host names only, no wildcards)"; exit 1; } _allow="${_allow:+$_allow,}$_h" done [ -n "$_allow" ] || { log "AGY_EGRESS_ALLOW is empty; refusing to run agy with no reachable host"; exit 1; } _prules="" _prhosts="" - for _r in $AGY_EGRESS_PATH_RULES; do + read -r -a _rs <<<"$AGY_EGRESS_PATH_RULES" + for _r in "${_rs[@]}"; do [[ "$_r" =~ ^([a-z0-9.-]+)=(/[A-Za-z0-9._~/-]*)$ ]] \ || { log "invalid AGY_EGRESS_PATH_RULES entry '$_r' (expected host=/exact/path)"; exit 1; } _rh="${BASH_REMATCH[1]}" @@ -1739,7 +1745,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then # Inside the jail, D-Bus is the filtered proxy (later env assignments override earlier ones). agy_env+=( "XDG_RUNTIME_DIR=/run/user/$_uid" "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$_uid/bus" "TMPDIR=/tmp" "${_egress_env[@]}" ) log "agy isolation: bwrap jail, empty HOME, D-Bus limited to ${#_items[@]} keyring item(s), egress ${AGY_EGRESS}" - unset _t _need _dict _kv _items _rules _it _uid _net _egress_binds _egress_env _inner _allow _h _ca_sys _c _pki _toplevel _d _prules _r _san _rh _prhosts + unset _t _need _dict _kv _items _rules _it _uid _net _egress_binds _egress_env _inner _allow _h _ca_sys _c _pki _toplevel _d _prules _r _san _rh _prhosts _kvs _hs _rs fi [ -n "$AGY_MODEL" ] && flags+=( --model "$AGY_MODEL" ) [ -n "$AGY_EFFORT" ] && flags+=( --effort "$AGY_EFFORT" ) @@ -1928,7 +1934,9 @@ if ! have_text "$out_file"; then # A regular file, not a pipe: the scan tests -s and reads its input once per pattern. log_tail="$(mktemp)" tail -n "${AGY_LOG_TAIL_LINES:-60}" "$LOG" > "$log_tail" || true - if log_cred="$(credential_kind_present "$log_tail")"; then + # Decided on the WHOLE log, not just the tail printed: a private key whose BEGIN line falls + # before the tail would leave only its body lines in it, which no pattern recognizes. + if log_cred="$(credential_kind_present "$LOG")" || log_cred="$(credential_kind_present "$log_tail")"; then log "(withheld: agy's stderr contains a credential-shaped string (${log_cred}); inspect $LOG on the runner host)" else sed 's/^/[agy] /' "$log_tail" >&2 || true From 5eb2dce112e19af973bec4cc9a539302dc7c3146 Mon Sep 17 00:00:00 2001 From: DoubleGate Date: Sun, 22 Nov 2026 22:46:13 -0500 Subject: [PATCH 14/14] ci: re-sync the reviewer to template 023b552 Re-syncs the vendored reviewer scripts byte for byte from the antigravity-pr-review template at 023b552. Local workflow overrides are unchanged. - List settings (AGY_KEYRING_ATTRS, AGY_EGRESS_ALLOW, AGY_EGRESS_PATH_RULES) are read whole with `read -r -d '' -a`. A plain `read -a` stopped at the first newline, which could drop a later path rule (leaving that host unrestricted) or a keyring attribute. Verification: agy-review-selftest.sh all checks passed; actionlint clean. Co-Authored-By: Claude Opus 5.5 --- scripts/agy-review-selftest.sh | 9 +++++++-- scripts/agy-review.sh | 10 ++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/scripts/agy-review-selftest.sh b/scripts/agy-review-selftest.sh index 8a35341f..1994de0a 100755 --- a/scripts/agy-review-selftest.sh +++ b/scripts/agy-review-selftest.sh @@ -1039,8 +1039,13 @@ check "an empty AGY_EGRESS_ALLOW is refused by name" "1" "$(grep -c 'AGY_EGRESS_ check "a second path rule for the same host is refused" "1" "$(grep -c "names '\${_rh}' twice (one exact path per host)" "$SCRIPT")" check "list settings are split without pathname expansion" "0" \ "$(grep -cE '^ *for _(kv|h|r) in \$AGY_' "$SCRIPT")" -check "list settings are read with read -a" "3" \ - "$(grep -cE '^ *read -r -a _(kvs|hs|rs) <<<"\$AGY_(KEYRING_ATTRS|EGRESS_ALLOW|EGRESS_PATH_RULES)"$' "$SCRIPT")" +check "list settings are read whole with read -d '' -a" "3" \ + "$(grep -cE "^ *IFS=\\\$' \\\\t\\\\n' read -r -d '' -a _(kvs|hs|rs) <<<\"\\\$AGY_(KEYRING_ATTRS|EGRESS_ALLOW|EGRESS_PATH_RULES)\" \|\| true$" "$SCRIPT")" +# The idiom itself, run on a newline-separated value with a wildcard: every entry survives (a plain +# `read -a` keeps only the first line) and nothing is globbed. +list_demo="$(cd "$TMPD" && touch evil.com && v=$'a=1 b=2\nwww.googleapis.com=/x\n*.com' \ + && IFS=$' \t\n' read -r -d '' -a parts <<<"$v" || true; printf '%s|' "${parts[@]}")" +check "a multi-line list keeps every entry and globs nothing" "a=1|b=2|www.googleapis.com=/x|*.com|" "$list_demo" check "the stderr tail is withheld when the WHOLE log carries a credential shape" "1" \ "$(grep -c '^ if log_cred="\$(credential_kind_present "\$LOG")" || ' "$SCRIPT")" check "a missing AGY_BIN is refused before the jail is built" "1" "$(grep -c 'is not an executable file on the runner host; refusing to build the jail' "$SCRIPT")" diff --git a/scripts/agy-review.sh b/scripts/agy-review.sh index 16075ec0..1bd23a67 100755 --- a/scripts/agy-review.sh +++ b/scripts/agy-review.sh @@ -1628,8 +1628,10 @@ if [ "$AGY_ISOLATION" = bwrap ]; then _dict="" # Split on whitespace with NO pathname expansion (read -a, not an unquoted for): `for x in $VAR` # globs, so a wildcard entry (`*.com`) would expand to file names in the checkout -- which the PR - # controls -- and then pass validation as an exact value. - read -r -a _kvs <<<"$AGY_KEYRING_ATTRS" + # controls -- and then pass validation as an exact value. `-d ''` reads the WHOLE value: a plain + # `read` stops at the first newline, which would silently drop a later path rule (leaving that + # host unrestricted) or keyring attribute (widening the item match). It returns 1 at EOF. + IFS=$' \t\n' read -r -d '' -a _kvs <<<"$AGY_KEYRING_ATTRS" || true for _kv in "${_kvs[@]}"; do [[ "$_kv" =~ ^[A-Za-z0-9_.-]+=[A-Za-z0-9_.:@-]+$ ]] || { log "invalid AGY_KEYRING_ATTRS entry '$_kv'"; exit 1; } _dict="${_dict:+$_dict, }'${_kv%%=*}': '${_kv#*=}'" @@ -1662,7 +1664,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then _egress_binds=() _egress_env=() _inner=() if [ "$AGY_EGRESS" = filtered ]; then _allow="" - read -r -a _hs <<<"$AGY_EGRESS_ALLOW" + IFS=$' \t\n' read -r -d '' -a _hs <<<"$AGY_EGRESS_ALLOW" || true for _h in "${_hs[@]}"; do [[ "$_h" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$ ]] \ || { log "invalid AGY_EGRESS_ALLOW entry '$_h' (exact lowercase host names only, no wildcards)"; exit 1; } @@ -1670,7 +1672,7 @@ if [ "$AGY_ISOLATION" = bwrap ]; then done [ -n "$_allow" ] || { log "AGY_EGRESS_ALLOW is empty; refusing to run agy with no reachable host"; exit 1; } _prules="" _prhosts="" - read -r -a _rs <<<"$AGY_EGRESS_PATH_RULES" + IFS=$' \t\n' read -r -d '' -a _rs <<<"$AGY_EGRESS_PATH_RULES" || true for _r in "${_rs[@]}"; do [[ "$_r" =~ ^([a-z0-9.-]+)=(/[A-Za-z0-9._~/-]*)$ ]] \ || { log "invalid AGY_EGRESS_PATH_RULES entry '$_r' (expected host=/exact/path)"; exit 1; }