Skip to content

feat(agent-review): port the scripts to Python and fix four security gaps - #2

Merged
egparedes merged 83 commits into
mainfrom
m1-python-foundation
Nov 16, 2026
Merged

egparedes merged 83 commits into
mainfrom
m1-python-foundation

Conversation

@egparedes

@egparedes egparedes commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Ports the agent review's four host and sandbox scripts (authorize, publish-comment, collect-result, run-review) from bash to Python 3.12, standard library only. The caller contract (inputs, secrets, permissions, outputs) is unchanged. The change also fixes four security gaps that predate it. One new fail-closed case can stop reviews: a base that links an instruction file to a path no reset pattern covers gets no review until the caller adds that path to instruction_files.

Python runtime rules (ADR 0004)

  • How Python runs. Only as /usr/bin/python3 -I -S -B <root>/bin/<name>: no PYTHON* variables, no site, sitecustomize or .pth, no bytecode written, only the standard library on sys.path.
  • Entry points. Each is a fixed template, mode 100644, that exits unless the four sys.flags are set. All logic lives in agent-review/lib/agent_review/.
  • Roots. "${RUNNER_TEMP}/trusted" in authorize, prepare and publish; the root-owned /opt/agent-review in the review jobs.
  • Processes and trust zones (runner.py, the only subprocess user). Argument lists only, programs resolved to absolute paths, output capped.
    • Trusted host (authorize, publish-comment post): gh is found on a fixed PATH: /usr/bin:/bin.
    • Sandbox (run-review): the inherited environment plus the forced GIT_* settings.
    • Tainted host: no process starts there today. The zone exists so that any future one gets an absolute program and a fixed environment.
  • GitHub API. gh api --jq as a subprocess: only gh's decoder handles the API JSON, and our code receives only the projected fields.
  • Untrusted input. Whole-value ASCII matching, validation before int(), I/O as bytes or strict UTF-8, and escaped workflow-command data.
  • Enforcement. agent-review/tests/test-workflow-structure.py checks these rules and the workflow's own invariants on every pull request. The docstring of agent-review/tests/workflow_structure.py is the complete list of checks. bin/probe, run by the stub harness, shows on every self-test that the host and the AWF sandbox use the same interpreter with these flags.
  • Tests and tooling.
    • The .sh suites are the black-box specification of each entry point's command-line contract and run against the Python entry points. One case changed: the coverage check now refuses a pattern that misses a named file, before the fetch.
    • A new python job runs pytest and mypy from a hash-pinned requirements.txt.
    • The ruff and mypy pre-commit hooks are scoped to agent-review/; pr-agent/ stays bash and is untouched.

Behaviour changes callers can see

  • authorize denies or fails where bash allowed:

    • non-ASCII digits and letters, which bash's ranges accept in some locales (en_US.UTF-8, not C.UTF-8), and Unicode whitespace around list entries;
    • a NUL in gh output;
    • gh exiting 0 with output on stderr;
    • . or .. segments in repository names;
    • a CR in api-bases.txt.

    Values in its messages are escaped.

  • publish-comment:

    • It drops every Unicode Cf character as well as the listed invisible ranges, and rejects input that is not strict UTF-8.
    • No raw HTML can form: a zero-width space follows every < that could start a tag, comment or declaration.
    • The truncation note appears if and only if content was cut, and a cut never splits a neutralisation.
    • An unusable review file is reported as invalid (a warning), no longer as a failure.
    • The comment listing is now capped, like every captured command output (16 MiB). To stay under the cap, it keeps only the first 256 characters of each comment's first line, about 1 KB per comment. A pull request with many thousands of comments can still exceed the cap or the time limit, and post then fails without posting.
  • collect-result:

    • It reads through descriptors, opening out/ component by component without following symlinks.
    • It refuses a symlinked destination, and never writes through a planted temporary file.
    • It skips an unreadable file with a warning instead of aborting.
  • run-review:

    • One glob engine: git decides both the coverage check and the reset, so they cannot disagree.
    • out/ is recreated after the harness, and the harness's stdin is /dev/null.
    • Invalid trusted configuration is fatal, and so is a missing or empty central instruction-files.txt.
    • A pr.json with a lone surrogate escape no longer stops the fetch: the character becomes U+FFFD.
    • New link check: a symlink or gitlink at an instruction file or directory must be the base commit's own and lead to a path the reset covers. Otherwise the fetch stops with a message naming the link, its target and the reason. It passes:
      • ./x and x/ link spellings;
      • an unchanged base submodule (an empty directory);
      • where a wildcard pattern only expects a directory on the way, a base link to a regular file or to a missing target.

Security fixes for problems that predate this change

  1. Forged workflow commands from sandbox output (invariant 11). The runner accepts the legacy ##[command] syntax anywhere in a line, so a prefix did not stop it: a sandbox line ##[warning]… became an annotation. Both awf output filters, diag and log_lines now drop NUL bytes and break up every ##[. The self-test asserts through the annotations API that no annotation results.

  2. Text hidden at the HTML level in the posted comment (invariant 5). Attributes, end-tag attributes, bogus comments and &shy in HTML blocks rendered as nothing. No raw HTML can form now.

  3. Instruction-file reset bypass through links (invariant 6).

    • A PR's symlink or gitlink at an instruction directory (.opencode -> evil/) kept its own files readable there.
    • A base link at an instruction file (AGENTS.md -> CONTRIBUTING.md, or a rule file such as docs/RULES.md -> guide.md) let the agent read the PR's edit of the target.
    • A base directory link into a directory that a file pattern only passes through let it read PR-added files.

    The reset now replaces such entries, and a second post-condition fails closed on any remaining link that does not lead to a path the reset covers.

  4. Prompt blow-up through the PR title. Sequential substitution let {{PR_BODY}} in the title copy the body (about 774 KB from a 512-byte title). Substitution is now a single pass.

Invariants touched

  • 2: kept, and reworded (projections only).
  • 3: strengthened. Descriptor-based collection; the teardown gate and every step after the sandbox are machine-checked.
  • 5: rewritten (the neutralisation rules, the bounded listing).
  • 6: extended (one engine; links and gitlinks; the central list required).
  • 11: fixed (##[, NUL).
  • 13: new, the Python runtime rules.

Not yet verified

The release checklist in docs/agent-review.md owns what this change's CI does not exercise: the keyed path (item 3.6), a real comment post under the fixed PATH (item 3.3), a cross-repository call (item 3) and a pull_request_target run from a fork (item 3.10).

Evidence

Each script was ported in its own pull request, each with a differential test against the bash version run in CI: #4 (collect-result), #5 (publish-comment), #6 (run-review), #7 (authorize).

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 5.5 noreply@anthropic.com

egparedes and others added 30 commits November 14, 2026 08:08
Adds the stdlib-only package agent-review/lib/agent_review/ with the shared
helpers the ports will use (runner with per-trust-zone tool lookup and
environment, gh wrapper, workflow-command and output writers, validation,
safe file access), the fixed entry-point template run only as
'/usr/bin/python3 -I -S -B <root>/bin/<name>', and a no-op 'probe' entry
point that the stub harness runs on the host and inside AWF; the self-test's
'check' job asserts both lines. No bin/ script is ported and
agent-review.yml is unchanged.

Tests: a launcher in tests/lib.sh runs each entry point with bash or the
production Python command line, by the file, and the suites call it; pytest
suites for the helpers, the hostile-environment and flag-guard runs, and the
structure checks on crafted inputs; the structure test now enforces call
forms and roots per file, the template and mode, the tree, an AST import
allowlist and the gh wrapper's reach. New 'python' self-test job (pytest +
mypy from hash-pinned requirements); ruff and mypy in pre-commit. ADR 0003
records the runtime rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…state

The call-site cases now run on a small frozen workflow fixture in which any
set of entry points can be ported, so M2-M5 need not edit them (checked by
fake-porting collect-result in a scratch copy: no test edit needed, and the
old call line fails). The launcher's bash case uses temporary scripts.

The AST rule also rejects 'import os as ...' and 'import *', which would hide
os.system and the like; 'pathlib' and 'io' join the standard-library
allowlist. The layout paragraph no longer states the current port state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- workflow.log_lines: the prefix must start with neither whitespace (the
  runner trims it, NBSP included, before matching '::') nor ':', and every
  '##[' in the text is broken up with a zero-width space: the runner's
  legacy parser matches '##[command]' anywhere in a line.
- Structure rules: no '.py' file and no Python shebang outside
  lib/agent_review/ and tests/; the shebang line of a shell file is checked
  too; the Python call must start a command; in shell files the root is
  'ar_root', set from the file's own path by one fixed line.
- AST rules: 'system'/'popen'/'exec*'/'spawn*'/'fork' banned as attributes
  of anything; no getattr on a module, no sys.modules (except the probe), no
  globals()/vars()/locals(), no standard-library module through
  agent_review.*; 'gh' matched by basename; the trusted-host zone only in
  gh.py.
- runner.run caps stdout (16 MiB by default, the command is killed beyond)
  and keeps the tail of stderr, with a selector loop instead of
  subprocess.run.
- The hostile-environment test asserts that the entry point got past its
  flag guard.
- Dependabot: a 'uv' entry for the test requirements, grouped, with a
  cooldown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stub prints '##[warning]agent-review-legacy-probe' on stdout and through
the adapters' 'diag', and the self-test's 'check' job asserts, through the
check-run annotations API (new 'checks: read' on that job only), that
neither became an annotation. Without a fix in the output prefixing this is
expected to fail: the runner's legacy parser finds '##[' anywhere in a line,
so the 'awf| ' prefix does not stop it. The fix follows in the next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…utput

The runner parses the legacy '##[command]' syntax anywhere in a line, so the
'awf| ' prefix (and 'diag''s prefix) did not stop sandbox output from issuing
commands. Verified in self-test run 43572272839: the stub's
'##[warning]agent-review-legacy-probe' lines, on stdout and through 'diag',
became two warning annotations of the keyless review job. A PR could
likewise forge annotations or issue add-mask or add-matcher.

Both 'awf' output filters and 'diag' now break every '##[' up with a
zero-width space (GNU sed '\xe2\x80\x8b'), keeping the prefix. The structure
test checks the exact filters; invariant 11 is updated. Only the
caller-visible log text changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
UnsafeFileError gets a 'reason' ("type", "links", "size" or "grew") and
the fstat result of the open file, so a caller can report each case
without parsing the message. collect-result (M3) keeps its four distinct
warnings this way. Additive: messages and raise sites are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bin/collect-result becomes the fixed Python entry point; the logic is in
lib/agent_review/collect_result.py. It starts no process and reads no
environment, so it needs no runner zone. The workflow's call is the
one-line swap to '/usr/bin/python3 -I -S -B /opt/agent-review/bin/...';
the step keeps its shell and 'PATH: /usr/bin:/bin'.

Same CLI, exit codes and messages. What changes, all fail-closed:

- No check-then-use races. bash compared <out-dir> with its realpath,
  then used the path again; it lstat'ed each file, then 'head' opened it
  by path (following symlinks). Now <out-dir> is opened one component at
  a time from '/' with O_DIRECTORY | O_NOFOLLOW and used only through
  that descriptor; each file is opened relative to it with O_NOFOLLOW |
  O_NONBLOCK and checked with fstat (files.read_bytes), after an lstat
  that keeps FIFOs and devices from being opened at all.
- The destination is written through its descriptor: a new <name>.tmp
  (O_EXCL, no symlink followed), then renamed. bash's '>' wrote through a
  symlink planted at <name>.tmp; a symlinked <dest-dir> is now refused
  (exit 1) instead of followed.
- An unreadable file is skipped with a warning like any refused file;
  bash died (set -e), left an empty .tmp and skipped meta.json.
- Warning data is escaped ('%', CR, LF), so a path cannot start a
  workflow command.

The bash version moves to tests/legacy/ for the differential test
(test_collect_result_differential.py), which runs both on the same
inputs and lists each difference with its reason; the next commit
deletes both. The unchanged test-collect-result.sh runs the Python entry
point through run_entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
authorize checks the repository permission of the actor, which may be a
bot login such as 'dependabot[bot]' (its actor pattern allows the
'[bot]' suffix). The bash version passed the brackets to gh as they are;
gh.ENDPOINT rejected them, so the Python port would have failed for bot
actors. Allow '[' and ']' in the path only, never as the first character
and never in the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The bash authorize captured 'gh api ... 2>&1' and compared the result:
a gh that exits 0 but also writes to stderr gave a value that never
matched (a skip or an invalid sha). Reading stdout only would let such a
run through. With 'stderr_is_error', gh.api raises CommandError instead,
so the caller fails closed. The default is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Shared helper change for the run-review port (M4), flagged for
reconciliation with the other ports.

- 'stdout_fd': the command's stdout goes to an open descriptor instead of
  a pipe, uncapped, and Result.stdout is empty. run-review needs it for
  'git diff > diff.patch' and 'git cat-file > <file>', which can exceed
  the 16 MiB capture cap on large pull requests, and for the harness,
  whose output must reach the step log live (the self-test asserts lines
  the stub prints inside the sandbox).
- Python's own stdout and stderr are flushed before the command starts,
  so its messages stay in order with an inherited stdout or stderr (the
  sandbox output goes through a pipe, where Python block-buffers).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Structure-test table change for the run-review port (M4), flagged for
reconciliation with the other ports. run-review replaces 'rm -rf' on
workspace directories with shutil.rmtree, which on Linux removes a tree
through directory descriptors and never follows a symlink inside it
(shutil.rmtree.avoids_symlink_attacks is true there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…al test

D5: the differential test ran in CI on the previous commit
(https://github.com/GridTools/ci-workflows/actions/runs/43576703740,
green: 31 scenarios, every difference a listed improvement). The bash
script is deleted; test-collect-result.sh and test_collect_result.py
remain the specification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port the sanitiser and the comment upsert of bin/publish-comment from bash
to Python, behaviour-preserving, with the M1 entry-point template:

- agent_review/sanitize.py: the sanitiser, pure functions with no gh in
  its import closure. Invisible characters are the explicit ranges of the
  bash byte pattern (U+E0100-U+E01FF as the bytes matched, not U+E01EF as
  the comment said) plus Unicode category Cf; the same neutralising
  replacements in the same order; strict UTF-8; the 60000-byte cap on a
  character boundary.
- agent_review/publish_comment.py: the CLI (sanitize, render, post) with
  the same arguments, exit codes and output. 'post' keeps the gh --jq
  projection of the comment listing, matches the marker on the first line
  of the bot's own comments only (compared as bytes), validates the
  comment id, and prints gh's errors through workflow.log_lines.
- agent-review.yml: the render and publish steps call
  '/usr/bin/python3 -I -S -B "${RUNNER_TEMP}/trusted/bin/publish-comment"'
  inline (the 'pc=' variable goes: the structure test requires Python call
  sites to name the file inline) and set PATH: /usr/bin:/bin.

Tests: test-publish-comment.sh unchanged, now through the Python entry
point; pytest unit and property tests (an independent oracle on every
code point, seeded random and adversarial inputs); the entry point in a
hostile environment with a fake gh.

D5: the bash script is kept as tests/legacy/publish-comment.sh for the
differential test (test_publish_comment_differential.py), which compares
both on every range of the bash pattern, every code point, hiding tricks,
the size cap, render and post. Documented differences: Cf outside the
bash ranges is dropped; sequences glibc's iconv accepted but that are not
UTF-8 (above U+10FFFF, 5- and 6-byte forms) are rejected with exit 3.
The next commit deletes both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lstat check keeps a FIFO or device found there from being opened; one
swapped in after it is opened non-blocking and refused by fstat (as
test_file_swapped_for_a_fifo_between_check_and_open shows). The docstring
and invariant 3 claimed more than that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…, 1/3)

The first part of the run-review port, as a library with unit tests; the
entry point is still bash until part 3.

- sandbox_git: git on PR content with the same forced GIT_* environment
  and '-c' settings as the bash 'git_safe' (hooks, fsmonitor, filters'
  helpers, file/ext transports and submodule recursion off), in the
  sandbox zone, so an inherited GIT_ALLOW_PROTOCOL still reaches git.
- reset: the caller configuration (rule files, reset patterns, the
  addendum's '{{' rejection and named files), the instruction-file reset,
  and the S4 post-condition, ported as is.
- One glob engine: the pre-fetch check that a reset pattern covers each
  file the addendum names now asks git, with the same
  ':(glob,icase)**/<pattern>' pathspecs as the reset (advisor finding 7).
  'git ls-files' needs an index, so each named path gets a scratch index
  (GIT_INDEX_FILE) in a scratch bare repository under the workspace,
  removed afterwards. Behaviour change, flagged: bash matched with its own
  globs, where '*' crosses '/' and case matters, so a pattern could look
  like it covered a file that the reset then missed (finding S4). Now the
  check and the reset agree, case-insensitively.
- 'ls-tree -z' in the post-condition: bash compared the C-quoted form of
  unusual paths (non-ASCII, quotes) and failed on them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The second part of the run-review port, as a library with unit tests.

- The PR title and body come from pr.json, the raw API response, parsed
  only inside the sandbox (invariant 2 is about the host), and are
  substituted last, so placeholders in them are not expanded; the nonce
  is removed from them, and the delimiters carry it.
- Caps as before: title 512 bytes (first line only), body 16 KiB,
  addendum 8 KiB in the prompt; a cut multi-byte character is dropped.
- Byte-identical to the bash output: the module mirrors '$(...)' (NUL
  bytes and trailing newlines dropped), 'head -c | iconv -c', jq's
  '// "" | tostring' and the sequential literal substitutions in the bash
  order. The tests run the bash pipelines (jq, tr, head, iconv) as the
  oracle on the same pr.json and addendum files.
- Behaviour change, flagged: a lone surrogate escape in pr.json ('\ud800')
  made jq reject the document and the fetch phase fail; it now becomes
  U+FFFD and the review goes on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…it B)

D5: the differential test of the previous commit compared the bash and the
Python publish-comment in CI (run 43577164532, green). Delete the legacy
copy and the differential test; test-publish-comment.sh, the sanitiser's
oracle and property tests and the entry-point tests stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…blish job

The review step's live log shows the agent's output (see 'Live logs');
only in 'publish' does the review never reach a log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bin/run-review becomes the Python entry point (the M1 template), with the
fetch and review phases in lib/agent_review/run_review.py; the AWF
command lines call it as
'/usr/bin/python3 -I -S -B /opt/agent-review/bin/run-review --phase ...',
with the same output filter.

- Fetch phase: the same git calls, argument lists only, with the forced
  GIT_* environment and '-c' settings of sandbox_git; the same
  depth/deepen/unshallow sequence for the merge base, context files,
  reset, post-condition and prompt.
- Review phase: 'timeout --kill-after=30s <N>m bash <adapter>/run.sh' in
  the checkout, stdout and stderr passed through; the harness contract
  (PROMPT_FILE, REPO_DIR, OUT_DIR, CONTEXT_DIR, MODEL, HARNESS_PREFIX,
  PR_NUMBER, STUB_PADDING_KIB, HOME, TMPDIR and the GIT_* variables on
  top of the inherited environment, exit 0 / 2 / other), the status
  mapping and the meta.json schema and layout are unchanged. The review
  file is opened with O_NOFOLLOW and scanned for its first '### '
  heading instead of being read whole.
- Exit code 1 for every failure: bash exited with git's or jq's code
  under 'set -e' (a missing params.json gave 2, 'no review').

D5: the bash script is kept as tests/legacy/run-review.sh, and
tests/python/test_run_review_differential.py runs both on the same
inputs (GridTools/gt4py PR 2983 and commit 64c83aa0 from github.com, and
crafted pull requests served from a local repository: nested and
directory patterns, a symlinked parent, rule files the PR adds, deletes
or modifies, an addendum naming files, a context directory in the PR,
review collection and status cases, configuration and parameter errors).
They leave the same workspace (checkout, index, status, context files,
prompt with the nonce normalised, review, meta.json), exit codes and log
lines. The differences are asserted one by one in 'test_difference_*';
each is an improvement (coverage by git, unusual names, lone surrogates,
code points above U+10FFFF, a heading only after a NUL, a missing
params.json). Both files go in the next D5 commit.

test_run_review.py runs the S4 regressions through the real fetch-phase
entry point, with a 'git' first on PATH that skips the reset's writes:
a rule file left at the PR's version, one the PR adds, one it deletes,
and a symlinked parent directory all stop the run before the prompt
exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BEHAVIOUR CHANGE (decided by the orchestrator; separate from the port).

- The "Truncated to 60000 bytes" note appears if and only if the size cap
  cut content of the sanitised review. Before (bash, and the port): a
  review of exactly 60000 bytes got the note without being cut, and one
  that grew past the cap through escaping was cut without it
  ('xx' + '@A' x 12000, 24002 bytes, became 59998 bytes and no note). A
  cap that removes only trailing newlines (which render drops anyway) is
  not a cut.
- The cap never splits a neutralisation: it backs off before '@' and its
  zero-width joiner, '<', ']' or '--' and their zero-width space, and
  '&amp;' or '&amp;#' and its zero-width space. Before, the cut text could
  end with a bare '@' or '<', or with part of '&amp;' (inert at the very
  end, but not what the sanitiser promises).

Tests: both edges of the note (at the cap, the growth case, dropped
characters only, trailing newlines), every cap of each construct, and a
property test that the cut is the longest legal prefix at every cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Changes one case of a bash suite, a deviation from "do not edit the
suites" approved by the orchestrator for M4.

test-run-review.sh, test_post_condition_catches_a_pattern_that_misses_the_file:
its premise was the two-engine mismatch. With the extra pattern
'gt4py/*.md' and an addendum naming src/gt4py/next/AGENTS.md, bash's own
matching ('*' crosses '/') said the file was covered, git's ':(glob)'
reset missed it, and the post-condition stopped the run. The coverage
check now asks git with the reset's pathspecs, so the same input fails
closed earlier, before anything is fetched.

- Old expected message: "Followed file 'src/gt4py/next/AGENTS.md' is not
  in the base commit but is in the checkout" (the post-condition).
- New expected message: "names 'src/gt4py/next/AGENTS.md', which no reset
  pattern covers" (the coverage check).

The fail-closed assertions stay: the fetch phase exits non-zero and no
prompt exists. The post-condition keeps its regression tests in
tests/python/test_run_review.py, which run the fetch-phase entry point
with the reset subverted (a rule file left at the PR's version, added or
deleted by the PR, a symlinked parent), and in test_reset.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bin/authorize becomes the fixed Python entry point; the logic is in
lib/agent_review/authorize.py. The workflow calls it as
'/usr/bin/python3 -I -S -B "${RUNNER_TEMP}/trusted/bin/authorize"', with
'PATH: /usr/bin:/bin' on the step: it runs in the trusted-host zone, so gh
is found on PATH and inherits the environment, and only agent_review.gh
runs it, with the same '--jq' projections (invariant 2).

Behaviour-preserving: same outputs, same fail (exit 1) and skip (exit 0)
semantics, the checks in the bash order, the same messages. The 47 cases
of tests/test-authorize.sh pass unchanged through the launcher.

Deliberate tightenings, each a denial where bash allowed, or a log-only
difference (see tests/python/test_authorize_differential.py):
- ASCII-only classes and whitespace (bash's C locale); in a UTF-8 locale
  bash trimmed Unicode spaces around list entries, and in en_US.UTF-8 its
  [0-9] matched full-width and Arabic-Indic digits;
- a variable that is not UTF-8 fails;
- gh output is compared as it is: a NUL is kept (bash dropped it), output
  on stderr from a gh that exits 0 is an API failure;
- a repository with a '.' or '..' segment never reaches a gh endpoint;
- an output value with CR or LF (a CRLF api-bases.txt) fails;
- values quoted in notices and errors are escaped ('%', CR, LF) and
  '##[' is broken up, so they cannot start another workflow command;
  NUL from gh is shown as '\x00'.

Commit A of D5: the bash script is kept as tests/legacy/authorize.sh,
and tests/python/test_authorize_differential.py runs both on a generated
matrix (about 35,000 cases: every variable, gh answer and api-bases.txt
variant in every event and action scenario) in a temporary 'differential'
job of the self-test. Commit B deletes both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
'reason' and 'st' get defaults ("other", None), so code that raises
UnsafeFileError with a message only, such as a parallel port written
against M1, does not hit a TypeError. collect-result checks 'st' before
using it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of PR 4:

- The walk to <out-dir> used O_RDONLY directory opens, which need read
  permission; bash's path lookup needed search permission only, so a
  0311 workspace or out/ collected under bash and not here. The walk now
  uses O_PATH | O_DIRECTORY | O_NOFOLLOW descriptors (a local helper:
  files.open_directory stays as it is, because an O_PATH descriptor
  cannot list a directory). A symlink component still fails (ENOTDIR).
- The docstring no longer overstates the race fix: a live process could
  hard-link a host file in and drop the extra link between open and
  fstat. The single-link check relies on no sandbox process being alive,
  which the teardown gate guarantees; the path and type races are closed.
- A failed rename removes the temporary file (when <dest>/<name> is a
  directory).
- Tests: 0311 on the workspace and on out/; out/ at 0444 and 000; the
  lstat pre-check keeps a FIFO from being opened (fails if the check is
  removed); no .tmp left after a failed rename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The structure test now checks that in every review job 'Collect the
result' comes after a step with id 'teardown' and that its 'if:' is a
plain '&&' chain (no '||', no parentheses except 'always()') with
"steps.teardown.outcome == 'success'" as one term. collect-result's
single-link check relies on no sandbox process being alive, which only
this gate guarantees; it was untested. Accept and reject cases are in
test_workflow_structure.py; invariant 3 says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the review of the port (D5 commit A, still with the differential
test):

- out/ is recreated after the harness exits. The harness can write
  anywhere in the workspace; bash overwrote review.md and meta.json with
  '>' (through a symlink, too) and kept anything else there. The
  O_EXCL writes of the first version failed instead (exit 1). Now out/
  holds only run-review's files.
- pr.json: invalid UTF-8 becomes U+FFFD, as jq did (the strict decoding
  of the first version failed the fetch, which jq never did); checked
  against jq in test_prompt.py.
- run-review's own messages escape CR and LF, so a value in a message
  (a parameter, a path from the PR tree) cannot add log lines.

Differential test additions: a history deeper than the first fetch
(the deepen loop runs in both), files planted in out/ by the harness,
and the documented differences for out/, NUL bytes in a configuration
list and a parameter with a trailing newline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ADR 0003 follow-ups for the run-review port: runner.run can send stdout
uncapped to a descriptor the caller opened, and untrusted text that is
only data (the PR title and body in the prompt) is decoded with U+FFFD
replacement, as jq did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t (D5 commit B)

The differential test ran in CI on the commit-A state of this pull
request (legacy bash and Python on the same inputs; every difference
asserted and documented in the PR). With it go tests/legacy/run-review.sh
and the fixtures' option to build a root around it.

The bash suites (test-run-review.sh, test-instruction-coverage.sh) and
the pytest suites stay; test_prompt.py keeps its jq/iconv oracle for the
prompt's shell semantics.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ential test

Commit B removed the only tests of three behaviours along with the
differential test; they return as Python-only tests through the entry
point:

- out/ holds only run-review's files after the harness planted others
  (a review, and 'no review');
- a history deeper than the first fetch: the fetch deepens and the fork
  is the merge base;
- a PR shipping .agent-review-context, as a symlink and as a directory:
  run-review's context directory replaces it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…al test (M5, commit B)

Commit B of D5. The differential test ran in CI on commit A
(https://github.com/GridTools/ci-workflows/actions/runs/43578460274): all
34,911 cases against bash under C.UTF-8 (the runner's LANG), plus a
tenth under C and en_US.UTF-8, with no difference outside the documented
tightenings. This removes tests/legacy/authorize.sh, the differential
test and the temporary 'differential' job; self-test.yml is back to the
base version. tests/test-authorize.sh (unchanged) and
tests/python/test_authorize.py keep testing the Python port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
egparedes and others added 13 commits November 14, 2026 13:39
… rule

Integration review F5: the testing section said the suites' cases were unchanged by the ports; one case in test-run-review.sh changed in M4, with approval. It also lists the new structure rule for PATH on host calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Final security review R1 (pre-existing in bash): a missing instruction-files.txt counted as 'not configured', so a packaging defect in the trusted tree would have left every harness's instruction files unreset with nothing failing. The central list is now read like the other trusted inputs (missing is fatal) and must hold at least one pattern. Tests through the real fetch entry point: missing, empty and comments-only lists stop the fetch before the prompt exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nger blocks the review

Final security review R2: every gitlink where a reset pattern looks was refused, so a base keeping shared skills as a submodule (.claude/skills/<name>) never got a review, and the docs offered no way out. A gitlink now passes only if it is the base commit's own (same path, same commit in the index as in the base tree) and its directory is empty: submodules are never fetched, so it is inert. A PR's added or changed gitlink is replaced by the reset (layer a); with the reset subverted, layer b refuses it. Tests through the real fetch entry point; invariant 6 updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…al's reason

Final security review R3: the base-link exception refused './CLAUDE.md' and '../.agents/skills/' (a trailing slash), and every refusal had the same generic message. '.' parts and one trailing '/' are now dropped lexically; '..' after the start, absolute targets, empty parts ('a//b'), leaving the repository, more than 8 symlinks and cycles are still refused, each with its reason in the message (a refusal on a symlink on the way names that symlink). Tests through the real fetch entry point for both spellings and every reason; condition (2) in invariant 6 updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Final security review R4, the most important missing negative test: in both review jobs, every step after 'id: agent' must hold no GH_TOKEN, github.token or secrets. reference (keys included), use the fixed shell and 'PATH: /usr/bin:/bin' on every run: step, use no action but actions/upload-artifact, and upload the result from exactly ${{ runner.temp }}/result (one such upload). Accept and reject cases; each rule was mutation-checked (every mutant fails 1-4 cases). Invariant 3 says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Final security review R5 (inferred there, now tested): a PR adding 'AGENTS.md text eol=crlf' or 'working-tree-encoding=UTF-16', with AGENTS.md a rule file, makes the restored file differ from its base blob, so the fetch stops (exit 1); for an instruction file that is not a rule file the content is the base text, transformed, with no PR bytes. 'What remains risky' notes that '* -diff' empties diff.patch, which can steer the review but breaks no invariant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Final security review R6, first step: the stub also prints '#\0#[warning]agent-review-legacy-probe' on stdout and through diag, and the check job counts four probe lines (grep -a: the log may hold NUL) and still asserts that no annotation results. This run shows how the runner treats a NUL inside the marker before the filters drop NUL in the next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Final security review R6: '#\0#[' passed the output filters unchanged, safe only as long as the runner matches '##[' byte for byte. Both awf output filters, diag and workflow.log_lines now drop NUL first (GNU sed 's/\x00//g', checked under C and C.UTF-8), then break up '##['. The structure test pins the new filters (with a reject case for each rule); unit tests cover NUL in diag and log_lines; invariant 11 updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Final security review R7: invariants 2 and 5, ADR 0004 and gh.py said no PR object or comment body is parsed on the host, but gh --jq decodes the full JSON there. They now say it is handled only by gh's JSON decoder and our code receives only the projected fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nfo strings

Final security review R8: a steered review can carry command lines for other bots (/approve, bors r+), which the sanitiser passes; whether a bot acts depends on its own author checks. Added under 'What remains risky', with breaking up a line-initial '/' as a v0.2.0 candidate; code-fence info strings join the list of Markdown-level hiding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Final security review R9: a comment where publish-comment post reads BOT_LOGIN from the environment: it is a test hook, the publish step's env: is fixed and does not set it, and a called workflow does not inherit the caller's env:.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The NUL probe run (43599140610) showed that a NUL byte from the sandbox makes grep treat the whole review log as binary: the probe-line extraction got 'Binary file matches' and failed, while the -q checks passed by exit status alone. Every grep on the logs now uses -a. That run also verified that the runner does not take '#\0#[warning]' as a command (no annotation).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts resolved:
- .github/workflows/self-test.yml, header: main's scope (both workflows,
  PR Agent's keyless path) with this branch's Python tests and neutral
  fixture wording. Everything else merged on its own: main's PR Agent
  steps and jobs, 'project_name: Self-test', and this branch's python job,
  check-job assertions and 'grep -a'.
- agent-review/tests/test-publish-comment.sh: this branch's run_entry calls
  (both sides renamed the repository to example-org/example).
- docs/agent-review.md: this branch's text, with main's neutral wording
  ("a test fork", "another repository"). ADR links: 0004 for the Python
  runtime, 0003 for PR Agent's.

Scoping: the ruff hooks are limited to agent-review/. Without that they
linted (and reformatted) pr-agent/tests/*.py, which follow their own rules;
PR Agent stays bash and is not touched by this branch's rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@egparedes egparedes changed the title Port the agent review's host and sandbox scripts to Python (M1–M5) feat(agent-review): port host and sandbox scripts to Python Nov 14, 2026
egparedes and others added 11 commits November 15, 2026 15:17
- post_sandbox_problems also scans the review jobs' own 'env:' and
  'defaults:', which every step after the sandbox inherits: a job-level
  'GH_TOKEN: ${{ github.token }}' passed every check before.
- Each trust zone is pinned to its modules: the sandbox zone to
  run_review.py and sandbox_git.py, the tainted-host zone to runner.py
  alone (collect-result starts no process), as the trusted host already
  was to gh.py.
- getattr/setattr/delattr are refused on an attribute of a module too
  ('getattr(os.path, ...)'), except sys.flags, and a module may not be used
  as a value ('x = os'; except the probe's tuple of its imports).
- Docs: 'result' can be 'rendered' when posting fails; the 256-character
  projection bounds each comment, not the number of comments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A wildcard part of a pattern ('docs/*/RULES.md', '*/x.md', '**/x.md')
makes its container pathspec match every entry there, so an unrelated
base symlink to a file ('docs/logo.png -> ../assets/logo.png') was
resolved and refused, and the whole review stopped with advice to reset
the asset. A link matched only as a directory on the way, not by a
pattern itself, now passes when it leads to a regular file in the
checkout: nothing can lie below a file. If the pull request turns the
target into a directory, the link is checked as before and refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- sanitize.py: name the deliberate differences from the bash version.
- read_review: the scan for a heading reads to the end of the file.
- ADR 0004: only workflow_structure.py's rules are unit-tested; the
  script's job-level checks run against the real workflow only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cked

- reset: a base link matched only as a directory on the way now also
  passes when its target is missing (the pull request deleted or renamed
  it): nothing can lie below it. A target the pull request turns into a
  directory is still refused.
- structure test, after the sandbox: the workflow's own 'env:' and
  'defaults:' are scanned too; token references are matched in every
  expression spelling ("github['token']", "secrets['X']", GITHUB_TOKEN);
  no step of a review job that holds a token may write $GITHUB_ENV or
  $GITHUB_PATH, which would pass the token on to every later step.
- getattr, setattr and delattr may not be used as values ('s = setattr').
- ADR 0004: the code rules are tripwires, not a sandbox; the probe's
  exemption from the module-as-value rule covers the whole file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ssage

- A base link on a wildcard way whose target the base never had passes;
  docs and the reset docstring say so.
- The structure test names a token reference with repr(), so a match that
  ends mid-quote ("github['token") reads unambiguously.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Each awf call must send stderr (2>&1) through the output filter, and
  must have a '-- ' command line; 'diag' must be one pipeline ending in
  its filter, not merely contain the filter text somewhere in common.sh.
- Token and secret checks use an allowlist of context uses: any use of
  'secrets', and any use of 'github' other than a named property other
  than 'token' ('toJSON(github)', 'github', 'github.*' are refused). The
  invariant-1 check for jobs without an environment uses the same rule.
- The reset's link check refuses a base link whose target lies below a
  regular file with its reason, instead of stopping on 'Not a directory'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The workflow names awf only as '"${AWF_BIN}"', plus the one line
  that finds it; '$AWF_BIN', '${AWF_BIN}' or a bare 'awf' fail.
- After an awf call's filter line only comments and the lines that
  report its status may follow, so nothing prints unfiltered output.
- 'diag' must be defined exactly once across the harness shell files,
  in common.sh: bash runs the last definition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The awf call's lines, up to the final ' 2>&1 \', may hold no
  redirection, pipe, list or command substitution: '1>&2 2>&1' or a
  '$(…)' argument would write around the filter.
- Before the call, its step may hold only the lines that choose the
  key variable: the fetch sandbox has written the workspace by then,
  and printing from it there would be unfiltered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bash reads BASH_ENV before a non-interactive script despite
'--noprofile --norc', so a BASH_ENV pointing into the workspace would
run sandbox-written code on the tainted host, or in the step that holds
the key. The structure test now rejects BASH_ENV, ENV, SHELLOPTS,
BASHOPTS, BASH_FUNC_* and the LD_* loader variables as 'env:' keys of
the workflow, the review jobs and their steps, and in any step of those
jobs that writes $GITHUB_ENV or $GITHUB_PATH.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A 'shell:' or 'defaults: run: shell:' of the workflow, a review job or
  one of its steps may not name a startup variable: a default shell
  ('env BASH_ENV=… bash {0}') reaches the agent step, which holds the
  key after the fetch sandbox has written the workspace.
- NODE_OPTIONS is a startup variable too: '--require' would load a
  sandbox-written module into actions/upload-artifact after the sandbox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- One home for the structure test's checks: the workflow_structure.py
  docstring, now complete; the docs, the ADR and the PR body state each
  invariant and its reason and point there.
- Invariants 3 and 6 become a rule plus a short list of exceptions; the
  link rule's full statement is verify_no_linked_directories.
- The tainted-host zone is described as unused today, kept for any future
  process there; the probe says which modules it imports and why.
- Review labels and references to the deleted bash scripts are replaced
  by the scenarios and contracts they stood for; the .sh suites stay the
  black-box specification of each entry point.
- The coverage-check test in test-run-review.sh is renamed to what it
  checks; tool lists point to requirements.in; ragged wraps fixed.

No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@egparedes egparedes changed the title feat(agent-review): port host and sandbox scripts to Python feat(agent-review): port the scripts to Python and fix four security gaps Nov 16, 2026
egparedes and others added 2 commits November 16, 2026 13:57
…reason

- Test comments and docstrings describe the rule under test, not what
  the deleted bash scripts did; the bash oracles stay. One test is
  renamed to drop "bash" from its name (test_read_two_fields).
- runner.py, ADR 0004 and the collect step's comment now agree with
  invariant 3: AWF mounts ~/.local/bin read-only, and the fixed PATH on
  the tainted host is there because the host is treated as tainted.
- authorize.py: gh output is compared exactly as text, not byte for
  byte; read_review states the final-newline rule; a ragged wrap fixed.

No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Item 3.10: a PR from a fork by a non-writer, labelled by a writer,
  reviewed with the key under 'pull_request_target', reset intact,
  comment posted, nothing from the fork run on the host.
- Item 3.3: the real post goes through /usr/bin/gh under the publish
  steps' fixed PATH.
- The test caller's prerequisites: admins not exempt from the
  environment rule, an event policy for its workflow file (without it
  'pull_request_target' is blocked from 2 December 2026), and no forced
  dry run left in its workflow file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@egparedes
egparedes merged commit fa528bd into main Nov 16, 2026
16 checks passed
@egparedes
egparedes deleted the m1-python-foundation branch November 16, 2026 13:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant