diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7de8fed..44b7d39 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -14,3 +14,15 @@ updates: # the routine group. ignore: - dependency-name: github/gh-aw-firewall + # The self-test's test-only tools (requirements.in): uv re-runs the + # 'uv pip compile --generate-hashes' recorded in requirements.txt, so the + # hashes stay. A week of cooldown before a new release is proposed. + - package-ecosystem: uv + directory: /agent-review/tests + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + python-test-tools: + patterns: ["*"] diff --git a/.github/workflows/agent-review.yml b/.github/workflows/agent-review.yml index 428bef6..d28af3b 100644 --- a/.github/workflows/agent-review.yml +++ b/.github/workflows/agent-review.yml @@ -266,7 +266,11 @@ jobs: TRUSTED_SHA: ${{ job.workflow_sha }} CALLER_WF_SHA: ${{ github.workflow_sha }} HAS_SHARED_KEY: ${{ secrets.inference_api_key != '' }} - run: bash "${RUNNER_TEMP}/trusted/bin/authorize" + # 'gh' is found on PATH (docs/adr/0004-python-runtime.md): only the + # system directories, never the home directories the runner's + # default PATH searches first. + PATH: /usr/bin:/bin + run: /usr/bin/python3 -I -S -B "${RUNNER_TEMP}/trusted/bin/authorize" prepare: needs: authorize @@ -524,9 +528,12 @@ jobs: # No key and no agent: only 'run-review' runs, and git on the PR with # hooks, filters and submodules disabled. Its output is prefixed (and # carriage returns dropped), so no line can start a workflow command - # ('::...::'); no '::stop-commands::', whose token would be printed to - # the live log first. 'sudo -E' passes the environment to AWF, which - # forwards none of it to the sandbox except what it sets itself. + # ('::...::'); NUL bytes are dropped and every '##[' is then broken up + # with a zero-width space, because the runner finds the legacy + # '##[command]' anywhere in a line. No '::stop-commands::', whose token + # would be printed to the live log first. 'sudo -E' passes the + # environment to AWF, which forwards none of it to the sandbox except + # what it sets itself. - &fetch-pr name: Fetch the pull request in the sandbox id: fetch @@ -543,8 +550,8 @@ jobs: --proxy-logs-dir "${RUNNER_TEMP}/awf-fetch-logs" \ --image-tag "${IMAGE_TAG}" \ --container-workdir "${WS}" \ - -- /opt/agent-review/bin/run-review --phase fetch "${WS}" 2>&1 \ - | /usr/bin/sed -u -e 's/\r//g' -e 's/^/awf| /' + -- /usr/bin/python3 -I -S -B /opt/agent-review/bin/run-review --phase fetch "${WS}" 2>&1 \ + | /usr/bin/sed -u -e 's/\r//g' -e 's/\x00//g' -e 's/##\[/#\xe2\x80\x8b#[/g' -e 's/^/awf| /' # The default shell has no pipefail: report awf's status, not sed's. exit "${PIPESTATUS[0]}" @@ -582,8 +589,8 @@ jobs: --proxy-logs-dir "${RUNNER_TEMP}/awf-logs" \ --image-tag "${IMAGE_TAG}" \ --container-workdir "${WS}" \ - -- /opt/agent-review/bin/run-review --phase review "${WS}" 2>&1 \ - | /usr/bin/sed -u -e 's/\r//g' -e 's/^/awf| /' + -- /usr/bin/python3 -I -S -B /opt/agent-review/bin/run-review --phase review "${WS}" 2>&1 \ + | /usr/bin/sed -u -e 's/\r//g' -e 's/\x00//g' -e 's/##\[/#\xe2\x80\x8b#[/g' -e 's/^/awf| /' rc=${PIPESTATUS[0]} # The sandbox could write only to the workspace; still, treat the # host as tainted from here on: shell builtins only. @@ -614,15 +621,15 @@ jobs: fi # Absolute paths and a fixed PATH: the runner's default PATH searches - # home directories such as ~/.local/bin before /usr/bin, and the sandbox - # could write there. + # home directories such as ~/.local/bin before /usr/bin. AWF mounts them + # read-only, but after the sandbox ran the host is treated as tainted. - &collect name: Collect the result if: always() && steps.key.outputs.skipped != 'true' && steps.teardown.outcome == 'success' shell: /usr/bin/bash --noprofile --norc -e -o pipefail {0} env: PATH: /usr/bin:/bin - run: /usr/bin/bash /opt/agent-review/bin/collect-result "${WS}/out" "${RUNNER_TEMP}/result" + run: /usr/bin/python3 -I -S -B /opt/agent-review/bin/collect-result "${WS}/out" "${RUNNER_TEMP}/result" - &upload-result name: Upload the result @@ -765,8 +772,8 @@ jobs: DRY_RUN: ${{ needs.authorize.outputs.dry_run }} SKIPPED: ${{ needs.review.outputs.skipped || needs.review-keyless.outputs.skipped }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + PATH: /usr/bin:/bin run: | - pc="${RUNNER_TEMP}/trusted/bin/publish-comment" review="${RUNNER_TEMP}/result/review.md" if [ "${SKIPPED}" = true ]; then echo "result=skipped" >> "$GITHUB_OUTPUT" @@ -777,7 +784,8 @@ jobs: exit 0 fi rc=0 - bash "${pc}" render --harness "${HARNESS}" --version "${VERSION}" --model "${MODEL}" \ + /usr/bin/python3 -I -S -B "${RUNNER_TEMP}/trusted/bin/publish-comment" render \ + --harness "${HARNESS}" --version "${VERSION}" --model "${MODEL}" \ --head-sha "${HEAD_SHA}" --run-url "${RUN_URL}" --review "${review}" > "${RUNNER_TEMP}/body.md" || rc=$? case "${rc}" in 0) ;; @@ -806,8 +814,9 @@ jobs: REPO: ${{ github.repository }} PR: ${{ needs.authorize.outputs.pr }} HARNESS: ${{ needs.authorize.outputs.harness }} + PATH: /usr/bin:/bin run: | - url=$(bash "${RUNNER_TEMP}/trusted/bin/publish-comment" post --repo "${REPO}" --pr "${PR}" \ + url=$(/usr/bin/python3 -I -S -B "${RUNNER_TEMP}/trusted/bin/publish-comment" post --repo "${REPO}" --pr "${PR}" \ --harness "${HARNESS}" --body-file "${RUNNER_TEMP}/body.md") echo "::notice::Posted the agent review: ${url}" { echo "result=posted"; echo "comment_url=${url}"; } >> "$GITHUB_OUTPUT" @@ -824,7 +833,7 @@ jobs: run: | case "${RESULT}" in missing) reason="the agent produced no review (fetch outcome '${FETCH_OUTCOME}', review outcome '${OUTCOME}', exit code '${EXIT_CODE}')" ;; - invalid) reason="the review was rejected as invalid (not UTF-8, or empty)" ;; + invalid) reason="the review was rejected as invalid (not UTF-8, empty, or not a regular file within the size cap)" ;; esac echo "::warning title=Agent review failed::No review was posted: ${reason}. See the 'Fetch the pull request in the sandbox' and 'Run the review in the sandbox' logs." { diff --git a/.github/workflows/self-test.yml b/.github/workflows/self-test.yml index eac17c2..dc6b7d0 100644 --- a/.github/workflows/self-test.yml +++ b/.github/workflows/self-test.yml @@ -1,14 +1,14 @@ name: Self-test # This repository's own CI: lint, zizmor, the script and structure tests of -# both workflows, PR Agent's keyless path (dry run), and the whole agent -# review pipeline end to end with the -# 'stub' harness (the keyless job: no environment, no key, no model call, -# nothing posted) through a LOCAL call, so the commit under test is exactly -# the one whose files the pipeline fetches. The fixed fixture is a -# merged public pull request of another repository whose head is in a fork -# and which changes AGENTS.md at two depths, so the cross-repository fetch by sha and the instruction-file -# reset run for real. +# both workflows, the agent review's Python tests, PR Agent's keyless path +# (dry run), and the whole agent review pipeline end to end with the 'stub' +# harness (the keyless job: no environment, no key, no model call, nothing +# posted) through a LOCAL call, so the commit under test is exactly the one +# whose files the pipeline fetches. The fixture is a fixed, merged public +# pull request of another repository whose head is in a fork and which +# changes AGENTS.md at two depths, so the cross-repository fetch by sha and +# the instruction-file reset run for real. on: pull_request: @@ -125,6 +125,32 @@ jobs: echo "::warning::Tag '${tag}' now points to '${now}', not the pinned '${digest}'." fi + # The agent review's Python code (docs/adr/0004-python-runtime.md): unit + # tests, the entry points under the production command line in a hostile + # environment, the structure checks on crafted inputs, and mypy. The test + # tools come from the hash-pinned agent-review/tests/requirements.txt, in a + # virtual environment; the runtime code never imports them. + python: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + env: + PYTHONDONTWRITEBYTECODE: "1" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install the test tools + run: | + /usr/bin/python3 -m venv "${RUNNER_TEMP}/venv" + "${RUNNER_TEMP}/venv/bin/pip" install --require-hashes --no-deps --only-binary :all: \ + -r agent-review/tests/requirements.txt + - name: pytest + run: '"${RUNNER_TEMP}/venv/bin/python" -B -m pytest' + - name: mypy + run: '"${RUNNER_TEMP}/venv/bin/python" -m mypy' + # The model-calling adapters' installers, as the 'prepare' job runs them: # pinned versions with integrity checks, no install scripts, no harness # code executed (the version check runs inside the sandbox). @@ -248,10 +274,11 @@ jobs: if: always() runs-on: ubuntu-24.04 timeout-minutes: 5 - # Reads this run's jobs and the keyless review's log, and the commit's - # deployments; nothing is written. + # Reads this run's jobs, the keyless review's log and annotations, and + # the commit's deployments; nothing is written. permissions: actions: read + checks: read deployments: read steps: - name: The stub review of the fixture was rendered, not posted @@ -264,6 +291,18 @@ jobs: echo "e2e='${E2E}' result='${RESULT}' head_sha='${HEAD_SHA}' comment_url='${COMMENT_URL}'" [ "${E2E}" = success ] && [ "${RESULT}" = dry-run ] && [ "${HEAD_SHA}" = "${FIXTURE_HEAD_SHA}" ] && [ -z "${COMMENT_URL}" ] + # 'Publish the review' in agent-review.yml runs only for a real post, + # which the self-test never makes: check on the same runner image that + # its fixed PATH finds the runner's gh. + - name: The publish step's fixed PATH finds gh + env: + PATH: /usr/bin:/bin + run: | + gh_path=$(command -v gh) + echo "gh under PATH=${PATH}: ${gh_path}" + [ "${gh_path}" = /usr/bin/gh ] + gh --version + - name: The keyless job ran the sandbox as configured env: GH_TOKEN: ${{ github.token }} @@ -286,21 +325,54 @@ jobs: expect "the keyless job succeeded" test "$(job 'e2e / review-keyless' conclusion)" = success expect "nothing was posted" test "$(step 'e2e / publish' 'Publish the review')" = skipped - # The raw log, through curl: it holds escape sequences, which 'gh' + # The raw logs, through curl: they hold escape sequences, which 'gh' # refuses to print. curl drops the token on the redirect to storage. - id=$(job 'e2e / review-keyless' id) - [[ "${id}" =~ ^[0-9]+$ ]] || { echo "::error::No keyless review job."; exit 1; } - for i in 1 2 3 4 5; do - curl -fsSL -H "Authorization: Bearer ${GH_TOKEN}" \ - "https://api.github.com/repos/${REPO}/actions/jobs/${id}/logs" | tr -d '\r' > "${RUNNER_TEMP}/review.log" && break - sleep $((i * 5)) - done + fetch_log() { # job-name file + local id + id=$(job "$1" id) + [[ "${id}" =~ ^[0-9]+$ ]] || { echo "::error::No job '$1'."; exit 1; } + for i in 1 2 3 4 5; do + curl -fsSL -H "Authorization: Bearer ${GH_TOKEN}" \ + "https://api.github.com/repos/${REPO}/actions/jobs/${id}/logs" | tr -d '\r' > "$2" && break + sleep $((i * 5)) + done + } + # 'grep -a' throughout: the sandbox's output may put any byte (NUL + # included) in the log, which would make grep print 'Binary file matches'. log="${RUNNER_TEMP}/review.log" - expect "fetch run allows only github.com" grep -qE '^[^ ]+ awf\| \[INFO\] Allowed domains: github\.com$' "${log}" - expect "review run allows no domain" grep -qE '^[^ ]+ awf\| \[INFO\] Allowed domains: ?$' "${log}" - expect "caps clamped" grep -qF '{"rateLimiting":{"requestsPerMinute":30,"requestsPerHour":10},"maxTurns":5,"agentTimeout":10}' "${log}" - expect "no key reached AWF" test "$(grep -c 'API proxy enabled: OpenAI=true' "${log}")" -eq 0 - expect "the reset was verified" grep -qF 'are their base versions.' "${log}" + prepare_log="${RUNNER_TEMP}/prepare.log" + fetch_log 'e2e / review-keyless' "${log}" + fetch_log 'e2e / prepare' "${prepare_log}" + expect "fetch run allows only github.com" grep -aqE '^[^ ]+ awf\| \[INFO\] Allowed domains: github\.com$' "${log}" + expect "review run allows no domain" grep -aqE '^[^ ]+ awf\| \[INFO\] Allowed domains: ?$' "${log}" + expect "caps clamped" grep -aqF '{"rateLimiting":{"requestsPerMinute":30,"requestsPerHour":10},"maxTurns":5,"agentTimeout":10}' "${log}" + expect "no key reached AWF" test "$(grep -ac 'API proxy enabled: OpenAI=true' "${log}")" -eq 0 + expect "the reset was verified" grep -aqF 'are their base versions.' "${log}" + + # The Python runtime (bin/probe, run by the stub harness): on the + # host in 'prepare' and inside the sandbox, the same interpreter, + # with the production flags and the standard library only. + probe='agent-review-probe python=3\.12\.[0-9]+ executable=/usr/bin/python3 isolated=1 ignore_environment=1' + probe+=' no_user_site=1 no_site=1 dont_write_bytecode=1 safe_path=1 site=0 stdlib_only=1' + host=$(grep -aE "^[^ ]+ ${probe} lib=/[^ ]+/trusted/lib$" "${prepare_log}" | cut -d' ' -f2- || true) + sandbox=$(grep -aE "^[^ ]+ awf\| ${probe} lib=/opt/agent-review/lib$" "${log}" | cut -d' ' -f3- || true) + echo "host: ${host}" + echo "sandbox: ${sandbox}" + expect "Python on the host (prepare)" test "$(wc -l <<< "${host}")" -eq 1 -a -n "${host}" + expect "Python in the sandbox" test "$(wc -l <<< "${sandbox}")" -eq 1 -a -n "${sandbox}" + expect "the same Python version on both" test "$(cut -d' ' -f2 <<< "${host}")" = "$(cut -d' ' -f2 <<< "${sandbox}")" + + # Sandbox output issues no workflow command in the legacy syntax + # either (invariant 11): the stub prints the probe on stdout and + # through 'diag'; neither may become an annotation of the job. + expect "the legacy-command probe ran (stdout and diag, with and without NUL)" \ + test "$(grep -a -c 'agent-review-legacy-probe' "${log}")" -ge 4 + check_run=$(job 'e2e / review-keyless' check_run_url) + [[ "${check_run}" =~ ^https://api\.github\.com/(repos/[^/]+/[^/]+/check-runs/[0-9]+)$ ]] || + { echo "::error::No check run for the keyless job."; exit 1; } + n=$(gh api --paginate "${BASH_REMATCH[1]}/annotations" \ + --jq '.[] | select(.message | contains("agent-review-legacy-probe")) | .message' | wc -l) + expect "no annotation from the legacy-command probe (${n})" test "${n}" -eq 0 # The keyless job requests no environment, so no deployment. n=$(gh api "repos/${REPO}/deployments?sha=${COMMIT}" --jq length) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a057558 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# Local tool caches; never commit bytecode (the structure test forbids it). +__pycache__/ +*.py[co] +.mypy_cache/ +.pytest_cache/ +.ruff_cache/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 02d7c85..e6ed3f5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,3 +18,23 @@ repos: # Info-level notes (quoting in test assertions, sourced helpers) are # not failures. args: [--severity=warning] + # The agent review's Python code (agent-review/lib/, tests). Entry points in + # bin/ have no '.py' suffix and are checked against their fixed template + # by the structure test instead. Scoped to agent-review/: PR Agent + # (pr-agent/) stays bash, and its test scripts follow their own rules. + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: ef6cf06c079dd6b299dfc720b0f14400c9d168e1 # frozen: v0.17.5 + hooks: + - id: ruff-check + files: ^agent-review/ + - id: ruff-format + files: ^agent-review/ + # The runtime code only, which has no dependency; the self-test's 'python' + # job also checks the tests, with the hash-pinned requirements. + - repo: https://github.com/pre-commit/mirrors-mypy + rev: ad26ebfa797fcb9b8f83275937c1c1d6e126719c # frozen: v2.4.1 + hooks: + - id: mypy + files: ^agent-review/lib/ + pass_filenames: false + args: [--config-file=pyproject.toml, agent-review/lib] diff --git a/agent-review/bin/authorize b/agent-review/bin/authorize old mode 100755 new mode 100644 index 997eeeb..0b5a954 --- a/agent-review/bin/authorize +++ b/agent-review/bin/authorize @@ -1,262 +1,15 @@ -#!/usr/bin/env bash -# The 'authorize' job of the agent review: validates the caller's inputs, -# decides whether this event may run a review and with which key mode, checks -# the actor's permission and pins the pull request's head and base sha. -# -# Usage: authorize (configuration in the environment, see below) -# -# Runs on the host, before anything from the pull request is read. It needs -# 'gh' (with GH_TOKEN) for the permission check and to resolve a pull request -# number, and writes its outputs to $GITHUB_OUTPUT. It fails closed: an -# invalid input or an API failure is an error ('allowed=false', exit 1); a -# denied actor or an event that is not for us is a notice ('allowed=false', -# exit 0). -# -# Environment (all from the workflow; IN_* are the caller's inputs, which come -# from the caller's workflow file): -# REPO EVENT ACTION AUTHOR SENDER ACTOR EVENT_PR EVENT_HEAD_SHA -# EVENT_BASE_SHA EVENT_DRAFT EVENT_LABEL github context, event payload -# IN_PR IN_HARNESS IN_MODEL IN_DRY_RUN IN_LABEL IN_PROJECT IN_RULES -# IN_PATTERNS IN_ADDENDUM IN_API_BASE IN_RPH IN_RPM IN_TURNS IN_TIMEOUT -# IN_ENVIRONMENT IN_TEST_REPO the caller's inputs -# TRUSTED_REPO TRUSTED_SHA job.workflow_repository/_sha -# CALLER_WF_SHA the caller's github.workflow_sha -# HAS_SHARED_KEY 'true' if 'secrets.inference_api_key' is non-empty in this -# job, which declares no environment -# -# Event and harness matrix ('keyed' harnesses call a model with the key): -# pull_request_target any harness; actions 'labeled' (with the configured -# label), 'opened', 'reopened', 'ready_for_review'; -# writer check on the labeller or the author -# workflow_dispatch any harness; writer check on the actor -# pull_request 'stub' only, forced dry run, no writer check: the -# caller test mode (any caller) and the self-test -# push, schedule 'stub' only, forced dry run, no writer check; the -# self-test of the workflow's own repository only +# agent-review Python entry point: run only as '/usr/bin/python3 -I -S -B /bin/'. +# The fixed template of agent-review/tests/workflow_structure.py; the code is in lib/agent_review/. +import sys -set -euo pipefail +if not (sys.flags.isolated and sys.flags.no_site and sys.flags.dont_write_bytecode and sys.flags.safe_path): + sys.stderr.write("agent-review entry points run only as '/usr/bin/python3 -I -S -B /bin/'.\n") + sys.exit(2) -readonly DOCS="See https://github.com/GridTools/ci-workflows/blob/main/docs/agent-review.md#inputs." -TRUSTED_ROOT=$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd) +import os # noqa: E402 -: "${GITHUB_OUTPUT:?}" -for v in REPO EVENT ACTION AUTHOR SENDER ACTOR EVENT_PR EVENT_HEAD_SHA EVENT_BASE_SHA EVENT_DRAFT \ - EVENT_LABEL IN_PR IN_HARNESS IN_MODEL IN_DRY_RUN IN_LABEL IN_PROJECT IN_RULES IN_PATTERNS \ - IN_ADDENDUM IN_API_BASE IN_RPH IN_RPM IN_TURNS IN_TIMEOUT IN_ENVIRONMENT IN_TEST_REPO \ - TRUSTED_REPO TRUSTED_SHA CALLER_WF_SHA HAS_SHARED_KEY; do - declare -g "${v}=${!v-}" -done +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "lib")) -fail() { - echo "allowed=false" >>"${GITHUB_OUTPUT}" - echo "::error::$1 ${DOCS}" - exit 1 -} -skip() { - echo "::notice::$1" - echo "allowed=false" >>"${GITHUB_OUTPUT}" - exit 0 -} -resolve_pr() { # number - [[ "$1" =~ ^[1-9][0-9]{0,9}$ ]] || fail "Invalid pull request number '$1'." - local shas - if ! shas=$(gh api "repos/${source_repo}/pulls/$1" --jq '[.head.sha, .base.sha] | @tsv' 2>&1); then - fail "Could not resolve pull request ${source_repo}#$1: '${shas}'." - fi - read -r head_sha base_sha <<<"${shas}" -} -int_in() { # name value max - if ! [[ "$2" =~ ^[1-9][0-9]{0,3}$ ]] || [ "$2" -gt "$3" ]; then - fail "Input $1 must be an integer in 1..$3, got '$2'." - fi -} -# One repository path or pattern: no absolute path, no '..' anywhere (as -# 'run-review' checks), no empty or '.' segment. A pattern may end in '/' -# (a directory, see instruction-files.txt); a path may not. -check_path() { # name entry plain|glob - local re='^[A-Za-z0-9_.][A-Za-z0-9_./-]{0,199}$' p=$2 - if [ "$3" = glob ]; then - re='^[A-Za-z0-9_.*][A-Za-z0-9_.*/-]{0,199}$' - p=${p%/} - fi - [[ "$2" =~ ${re} ]] || fail "Invalid entry in $1: '$2'." - case "/${p}/" in *..* | */./* | *//*) fail "Invalid entry in $1: '$2'." ;; esac -} -# A list, one entry per line; blank lines and '#' comments are skipped, as -# 'run-review' reads these lists. -check_list() { # name list plain|glob - local line - while IFS= read -r line; do - line=${line#"${line%%[![:space:]]*}"} - line=${line%"${line##*[![:space:]]}"} - case "${line}" in '' | '#'*) continue ;; esac - check_path "$1" "${line}" "$3" - done <<<"$2" -} +from agent_review.authorize import main # noqa: E402 -# --- This workflow's own commit, from which every trusted file is read ------ -[[ "${TRUSTED_REPO}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || fail "No job.workflow_repository ('${TRUSTED_REPO}')." -[[ "${TRUSTED_SHA}" =~ ^[0-9a-f]{40}$ ]] || fail "No job.workflow_sha ('${TRUSTED_SHA}')." -[[ "${REPO}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || fail "Invalid repository '${REPO}'." -echo "::notice::Agent review workflow ${TRUSTED_REPO}@${TRUSTED_SHA}; caller ${REPO}@${CALLER_WF_SHA}." - -# --- Harness and key mode ----------------------------------------------------- -# The allowlist decides whether the run is keyed: only keyed runs get the -# job with the caller's environment, and so the key. -harness=${IN_HARNESS} -case "${harness}" in - stub) keyed=false ;; - opencode | pi) keyed=true ;; - '') fail "No harness given (input 'harness')." ;; - *) fail "Unknown harness '${harness}'." ;; -esac - -# The key must be an environment secret: here, in a job without an -# environment, the caller's mapping yields a repository or organization -# secret of that name, which every job of this workflow would then receive. -case "${HAS_SHARED_KEY}" in - false) ;; - true) fail "Secret 'inference_api_key' is readable in a job without an environment: the caller maps a repository or organization secret. Map it only from the environment's own secret, and delete the shared one." ;; - *) fail "Invalid HAS_SHARED_KEY '${HAS_SHARED_KEY}'." ;; -esac - -# --- Static inputs ------------------------------------------------------------ -# Validated before any API call, so a misconfigured caller fails visibly. -[[ "${IN_LABEL}" =~ ^[A-Za-z0-9][A-Za-z0-9\ ._:/-]{0,49}$ ]] || fail "Invalid label '${IN_LABEL}'." -case "${IN_DRY_RUN}" in true | false) ;; *) fail "Invalid dry-run flag '${IN_DRY_RUN}'." ;; esac -# The stub calls no model. The others have no default model on purpose. -if [ "${keyed}" = false ]; then - model=none -else - model=${IN_MODEL} - [ -n "${model}" ] || fail "No model given for harness '${harness}' (input 'model')." - [[ "${model}" =~ ^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$ ]] || fail "Invalid model id '${model}'." -fi -project=${IN_PROJECT:-${REPO#*/}} -[[ "${project}" =~ ^[A-Za-z0-9][A-Za-z0-9._\ -]{0,63}$ ]] || fail "Invalid project name '${project}'." -check_list rule_files "${IN_RULES}" plain -check_list instruction_files "${IN_PATTERNS}" glob -# One path, no comment syntax: the value becomes part of an API path. -if [ -n "${IN_ADDENDUM}" ]; then - [ "$(grep -c . <<<"${IN_ADDENDUM}")" -le 1 ] || fail "Input prompt_addendum takes one path." - addendum=${IN_ADDENDUM#"${IN_ADDENDUM%%[![:space:]]*}"} - addendum=${addendum%"${addendum##*[![:space:]]}"} - check_path prompt_addendum "${addendum}" plain -fi -# Where the key is sent: an exact entry of the central allowlist. -api_base=${IN_API_BASE} -mapfile -t api_bases < <(grep -v -e '^#' -e '^$' "${TRUSTED_ROOT}/api-bases.txt") -[ "${#api_bases[@]}" -gt 0 ] || fail "No allowed inference endpoint in api-bases.txt." -[ -n "${api_base}" ] || api_base=${api_bases[0]} -allowed_base=false -for b in "${api_bases[@]}"; do [ "${api_base}" != "${b}" ] || allowed_base=true; done -[ "${allowed_base}" = true ] || fail "Input api_base '${api_base}' is not an allowed inference endpoint (agent-review/api-bases.txt)." -[[ "${IN_ENVIRONMENT}" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$ ]] || fail "Invalid environment '${IN_ENVIRONMENT}'." -# Ceilings: a caller can lower the caps, never raise them. The review job -# also clamps them to agent-review/awf.yaml. -int_in requests_per_hour "${IN_RPH}" 100 -int_in requests_per_minute "${IN_RPM}" 30 -int_in max_turns "${IN_TURNS}" 80 -int_in harness_timeout_minutes "${IN_TIMEOUT}" 20 - -# --- Event ---------------------------------------------------------------------- -# The self-test: this repository calling its own workflow with the stub. -self_test=false -[ "${TRUSTED_REPO}" != "${REPO}" ] || [ "${keyed}" = true ] || self_test=true - -# The repository whose pull request is reviewed: the caller's, or (self-test -# only) another public repository, read-only. -source_repo=${REPO} -if [ -n "${IN_TEST_REPO}" ]; then - [ "${self_test}" = true ] || fail "Input test_repository is for the self-test of ${TRUSTED_REPO} with the 'stub' harness only." - [ "${EVENT}" != pull_request_target ] || fail "Input test_repository is not supported under 'pull_request_target'." - [[ "${IN_TEST_REPO}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || fail "Invalid test_repository '${IN_TEST_REPO}'." - source_repo=${IN_TEST_REPO} -fi - -dry_run=${IN_DRY_RUN} -check_writer=true -case "${EVENT}" in - pull_request_target) - # Only these actions; a caller listing other 'types' (or none, which - # means every push to a PR) gets no keyed run from them. - case "${ACTION}" in - labeled) - [ "${EVENT_LABEL}" = "${IN_LABEL}" ] || skip "Label '${EVENT_LABEL}' does not request a review." - actor=${SENDER} - ;; - opened | reopened | ready_for_review) - [ "${EVENT_DRAFT}" != true ] || skip "Draft pull request; add the '${IN_LABEL}' label to request a review." - actor=${AUTHOR} - ;; - *) skip "Action '${ACTION}' of 'pull_request_target' does not start a review (allowed: labeled, opened, reopened, ready_for_review)." ;; - esac - pr=${EVENT_PR} - head_sha=${EVENT_HEAD_SHA} - base_sha=${EVENT_BASE_SHA} - ;; - workflow_dispatch) - pr=${IN_PR} - resolve_pr "${pr}" - actor=${ACTOR} - ;; - pull_request | push | schedule) - # Nothing to spend and nothing to post, so no writer check (fork and - # Dependabot PRs can run it). The dry run follows from the event name. - [ "${keyed}" = false ] || fail "Event '${EVENT}' runs the 'stub' harness only, not '${harness}'." - if [ "${EVENT}" != pull_request ]; then - [ "${self_test}" = true ] || fail "Event '${EVENT}' is for the self-test of ${TRUSTED_REPO} only." - elif [ "${self_test}" = false ]; then - echo "::notice::Caller test mode (event 'pull_request', harness 'stub', dry run): the caller's workflow file, inputs, rule files and prompt addendum are pull request content here. This run proves the plumbing only, never the reset of the rule files." - fi - pr=${IN_PR:-${EVENT_PR}} - resolve_pr "${pr}" - actor=${ACTOR} - check_writer=false - dry_run=true - ;; - *) fail "Unexpected event '${EVENT}'." ;; -esac -# Never comment on a pull request of the caller that merely has the same -# number as the reviewed one. -[ "${source_repo}" = "${REPO}" ] || dry_run=true - -if [ "${check_writer}" = true ]; then - [[ "${actor}" =~ ^[A-Za-z0-9][A-Za-z0-9-]{0,38}(\[bot\])?$ ]] || fail "Invalid actor '${actor}'." - if ! level=$(gh api "repos/${REPO}/collaborators/${actor}/permission" --jq '.permission' 2>&1); then - fail "Could not resolve repository permission for '${actor}', denying: '${level}'." - fi - # 'permission' reports the 'maintain' role as 'write', and 'triage' as - # 'read'. - case "${level}" in - admin | write) echo "::notice::${actor} has '${level}' permission; running the agent review." ;; - *) skip "${actor} has '${level}' permission; skipping the agent review." ;; - esac -else - echo "::notice::Event '${EVENT}' with harness 'stub': forced dry run, no permission check." -fi - -[[ "${pr}" =~ ^[1-9][0-9]{0,9}$ ]] || fail "Invalid pull request number '${pr}'." -[[ "${head_sha}" =~ ^[0-9a-f]{40}$ ]] || fail "Invalid head sha '${head_sha}'." -[[ "${base_sha}" =~ ^[0-9a-f]{40}$ ]] || fail "Invalid base sha '${base_sha}'." - -# Distinguishes this call's artifacts from another call's in the same run. -call_id=$(head -c 8 /dev/urandom | od -An -tx1 | tr -d ' \n') - -{ - echo "allowed=true" - echo "keyed=${keyed}" - echo "pr=${pr}" - echo "head_sha=${head_sha}" - echo "base_sha=${base_sha}" - echo "harness=${harness}" - echo "model=${model}" - echo "dry_run=${dry_run}" - echo "project=${project}" - echo "api_base=${api_base}" - echo "source_repo=${source_repo}" - echo "call_id=${call_id}" - echo "trusted_repo=${TRUSTED_REPO}" - echo "trusted_sha=${TRUSTED_SHA}" -} >>"${GITHUB_OUTPUT}" -echo "::notice::Reviewing ${source_repo}#${pr} at ${head_sha} with harness '${harness}' (keyed ${keyed}), model '${model}', dry run '${dry_run}'." +sys.exit(main()) diff --git a/agent-review/bin/collect-result b/agent-review/bin/collect-result index bd50b3e..44f5b90 100644 --- a/agent-review/bin/collect-result +++ b/agent-review/bin/collect-result @@ -1,60 +1,15 @@ -#!/usr/bin/bash -# Copies the review out of the sandbox workspace; runs on the TAINTED host. -# -# Usage: collect-result -# -# After 'awf' returns, everything the sandbox could write is attacker- -# controlled: , its parents, and the home and /tmp trees. So this -# script uses only absolute paths to /usr/bin tools (/usr is read-only in the -# sandbox), must be called with a fixed PATH, and copies only the expected -# files, only if each is a regular file with a single link, and at most -# MAX_BYTES of it. Everything else the agent wrote is ignored. The files are -# validated again in the 'publish' job, which never trusts this copy either. +# agent-review Python entry point: run only as '/usr/bin/python3 -I -S -B /bin/'. +# The fixed template of agent-review/tests/workflow_structure.py; the code is in lib/agent_review/. +import sys -set -euo pipefail -export PATH=/usr/bin:/bin LC_ALL=C +if not (sys.flags.isolated and sys.flags.no_site and sys.flags.dont_write_bytecode and sys.flags.safe_path): + sys.stderr.write("agent-review entry points run only as '/usr/bin/python3 -I -S -B /bin/'.\n") + sys.exit(2) -readonly MAX_BYTES=65536 -readonly EXPECTED=(review.md meta.json) +import os # noqa: E402 -warn() { echo "::warning title=Agent review result::$*"; } +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "lib")) -[ $# -eq 2 ] || { echo "Usage: collect-result " >&2; exit 1; } -src=$1 -dest=$2 +from agent_review.collect_result import main # noqa: E402 -/usr/bin/mkdir -p -- "${dest}" - -# Any symlink in the path (including itself or a parent replaced by -# the agent) would make the canonical path differ. -if ! canonical=$(/usr/bin/realpath -e -- "${src}" 2>/dev/null) || [ "${canonical}" != "${src}" ] || [ ! -d "${src}" ]; then - warn "'${src}' is missing, not a directory, or reached through a symlink; nothing collected." - exit 0 -fi - -for name in "${EXPECTED[@]}"; do - path="${src}/${name}" - if [ -L "${path}" ] || [ ! -f "${path}" ]; then - warn "'${name}' is missing or not a regular file; skipped." - continue - fi - # A hard link could expose a host file the agent cannot read itself. - read -r links size < <(/usr/bin/stat -c '%h %s' -- "${path}") - if [ "${links}" != 1 ]; then - warn "'${name}' has ${links} hard links; skipped." - continue - fi - if [ "${size}" -gt "${MAX_BYTES}" ]; then - warn "'${name}' is ${size} bytes, over the ${MAX_BYTES}-byte limit; skipped." - continue - fi - # Bounded read: the size check above is advisory, this is the limit. - /usr/bin/head -c "$((MAX_BYTES + 1))" -- "${path}" >"${dest}/${name}.tmp" - if [ "$(/usr/bin/stat -c %s -- "${dest}/${name}.tmp")" -gt "${MAX_BYTES}" ]; then - /usr/bin/rm -f -- "${dest}/${name}.tmp" - warn "'${name}' grew over the ${MAX_BYTES}-byte limit while reading; skipped." - continue - fi - /usr/bin/mv -f -- "${dest}/${name}.tmp" "${dest}/${name}" - echo "Collected '${name}' (${size} bytes)." -done +sys.exit(main()) diff --git a/agent-review/bin/probe b/agent-review/bin/probe new file mode 100644 index 0000000..0815e39 --- /dev/null +++ b/agent-review/bin/probe @@ -0,0 +1,15 @@ +# agent-review Python entry point: run only as '/usr/bin/python3 -I -S -B /bin/'. +# The fixed template of agent-review/tests/workflow_structure.py; the code is in lib/agent_review/. +import sys + +if not (sys.flags.isolated and sys.flags.no_site and sys.flags.dont_write_bytecode and sys.flags.safe_path): + sys.stderr.write("agent-review entry points run only as '/usr/bin/python3 -I -S -B /bin/'.\n") + sys.exit(2) + +import os # noqa: E402 + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "lib")) + +from agent_review.probe import main # noqa: E402 + +sys.exit(main()) diff --git a/agent-review/bin/publish-comment b/agent-review/bin/publish-comment index b8ead42..bed6b42 100644 --- a/agent-review/bin/publish-comment +++ b/agent-review/bin/publish-comment @@ -1,191 +1,15 @@ -#!/usr/bin/env bash -# Validates the agent's review and upserts it as a PR comment. -# -# Usage: -# publish-comment sanitize < review > safe-review -# publish-comment render --harness H --version V --model M --head-sha SHA --run-url U --review FILE -# publish-comment post --repo R --pr N --harness H --body-file FILE -# -# Runs in the 'publish' job: a fresh VM with a write-capable token, no model -# and no PR code. The review is model output steered by untrusted PR content, -# so it is treated as hostile text: -# - it must be valid UTF-8; control characters are dropped, and so are -# invisible format characters (zero-width, bidirectional controls, -# variation selectors, tag characters), which could hide or reorder text; -# - markup that GitHub renders as nothing is broken up with a zero-width -# space: HTML comments (so the review cannot imitate the marker that -# identifies this workflow's comment either), processing instructions -# ('/bin/'. +# The fixed template of agent-review/tests/workflow_structure.py; the code is in lib/agent_review/. +import sys -set -euo pipefail -shopt -u patsub_replacement 2>/dev/null || true -export LC_ALL=C +if not (sys.flags.isolated and sys.flags.no_site and sys.flags.dont_write_bytecode and sys.flags.safe_path): + sys.stderr.write("agent-review entry points run only as '/usr/bin/python3 -I -S -B /bin/'.\n") + sys.exit(2) -readonly REVIEW_MAX_BYTES=60000 -# GitHub rejects comment bodies over 65536 characters. -readonly BODY_MAX_BYTES=65536 -readonly ZWSP=$'\xe2\x80\x8b' # zero-width space -readonly ZWJ=$'\xe2\x80\x8d' # zero-width joiner -# Invisible format characters, as UTF-8 byte patterns (matched under LC_ALL=C): -# U+00AD, U+061C, U+180E, U+200B-U+200F, U+202A-U+202E, U+2060-U+206F, -# U+FE00-U+FE0F, U+FEFF, U+E0000-U+E007F (tags), U+E0100-U+E01EF (selectors). -readonly INVISIBLE=$'\xc2\xad|\xd8\x9c|\xe1\xa0\x8e|\xe2\x80[\x8b-\x8f\xaa-\xae]|\xe2\x81[\xa0-\xaf]|\xef\xb8[\x80-\x8f]|\xef\xbb\xbf|\xf3\xa0[\x80\x81][\x80-\xbf]|\xf3\xa0[\x84-\x87][\x80-\xbf]' -BOT_LOGIN=${BOT_LOGIN:-github-actions[bot]} +import os # noqa: E402 -die() { - echo "publish-comment: $*" >&2 - exit 1 -} +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "lib")) -# Byte truncation can split a multi-byte character at the end; 'iconv -c' -# drops it, and exits 1 when it does. -drop_partial_chars() { iconv -f UTF-8 -t UTF-8 -c 2>/dev/null || true; } +from agent_review.publish_comment import main # noqa: E402 -marker() { printf '' "$1"; } - -# Exit code 3: the input is not valid UTF-8 (the caller posts nothing). -cmd_sanitize() { - local input cleaned - input=$(mktemp) - cleaned=$(mktemp) - # shellcheck disable=SC2064 # expand now: the locals are gone on return - trap "rm -f '${input}' '${cleaned}'" RETURN - cat >"${input}" - iconv -f UTF-8 -t UTF-8 <"${input}" >/dev/null 2>&1 || { - echo "publish-comment: the review is not valid UTF-8." >&2 - return 3 - } - # Keep tab and newline; drop other C0 controls and DEL (CR included). - # Invisible characters go first, so removing them cannot join a delimiter - # that the later replacements would miss ('<' U+200B '!--'). The later - # replacements cannot create new matches: none inserts '<', '>', '&', ']' - # or '@', and the named-reference rule runs before the numeric one. - tr -d '\000-\010\013-\037\177' <"${input}" | - sed -E -e "s/${INVISIBLE}//g" | - sed -e "s/<\([!?]\)/<${ZWSP}\1/g" \ - -e "s/-->/--${ZWSP}>/g" \ - -e "s/\]:/]${ZWSP}:/g" \ - -e "s/@\([A-Za-z0-9]\)/@${ZWJ}\1/g" \ - -e 's/&\([A-Za-z][A-Za-z0-9]*;\)/\&\1/g' \ - -e "s/&#/\\&#${ZWSP}/g" >"${cleaned}" - # Truncated from a file, not in the pipeline: 'head' closing the pipe early - # would kill the writer with SIGPIPE, which 'pipefail' reports as a failure. - head -c "${REVIEW_MAX_BYTES}" "${cleaned}" | drop_partial_chars -} - -check_label() { # name value - [[ "$2" =~ ^[A-Za-z0-9][A-Za-z0-9._:/+-]{0,127}$ ]] || die "Invalid $1 '$2'." -} - -cmd_render() { - local harness="" version="" model="" head_sha="" run_url="" review="" - while [ $# -gt 0 ]; do - case "$1" in - --harness) harness=$2 ;; - --version) version=$2 ;; - --model) model=$2 ;; - --head-sha) head_sha=$2 ;; - --run-url) run_url=$2 ;; - --review) review=$2 ;; - *) die "Unknown option '$1'." ;; - esac - shift 2 - done - # These come from the workflow's trusted job outputs, never from the - # sandbox; validated because they are interpolated into Markdown. - check_label harness "${harness}" - check_label version "${version}" - check_label model "${model}" - [[ "${head_sha}" =~ ^[0-9a-f]{40}$ ]] || die "Invalid head sha '${head_sha}'." - [[ "${run_url}" =~ ^https://github\.com/[A-Za-z0-9_./-]+$ ]] || die "Invalid run URL '${run_url}'." - [ -f "${review}" ] || die "No review file '${review}'." - - local safe - safe=$(cmd_sanitize <"${review}") || return $? - [ -n "${safe//[[:space:]]/}" ] || { echo "publish-comment: the review is empty." >&2; return 3; } - local original_bytes - original_bytes=$(stat -c %s -- "${review}") - - marker "${harness}" - printf '\n> [!NOTE]\n' - # shellcheck disable=SC2016 # the backticks are Markdown - printf '> Advisory review by **%s** %s (`%s`) of commit %s, produced in a sandbox. ' \ - "${harness}" "${version}" "${model}" "${head_sha}" - printf 'Later pushes are not reviewed. Not a required check: it may be wrong, and the content of the pull request can steer it. ' - printf '[Workflow run](%s).\n\n' "${run_url}" - printf '%s\n' "${safe}" - if [ "${#safe}" -ge "${REVIEW_MAX_BYTES}" ] || [ "${original_bytes}" -gt "${REVIEW_MAX_BYTES}" ]; then - printf '\n_[Truncated to %d bytes.]_\n' "${REVIEW_MAX_BYTES}" - fi -} - -cmd_post() { - local repo="" pr="" harness="" body_file="" - while [ $# -gt 0 ]; do - case "$1" in - --repo) repo=$2 ;; - --pr) pr=$2 ;; - --harness) harness=$2 ;; - --body-file) body_file=$2 ;; - *) die "Unknown option '$1'." ;; - esac - shift 2 - done - [[ "${repo}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || die "Invalid repo '${repo}'." - [[ "${pr}" =~ ^[1-9][0-9]{0,9}$ ]] || die "Invalid PR number '${pr}'." - check_label harness "${harness}" - [ -f "${body_file}" ] || die "No body file '${body_file}'." - [ "$(stat -c %s -- "${body_file}")" -le "${BODY_MAX_BYTES}" ] || die "The comment body exceeds ${BODY_MAX_BYTES} bytes." - - local want - want=$(marker "${harness}") - [ "$(head -n 1 -- "${body_file}")" = "${want}" ] || die "The body does not start with the marker." - - # The marker is matched only on this workflow's own comments, and on the - # first line only: never 'gh pr comment --edit-last', since PR Agent posts - # as the same bot. The sanitiser keeps the review from containing it. - # Listed into a file, not a process substitution, so a failed listing - # stops the script instead of posting a second comment. - local id="" cid login first listing - listing=$(mktemp) - # shellcheck disable=SC2064 # expand now: the local is gone on return - trap "rm -f '${listing}'" RETURN - gh api --paginate "repos/${repo}/issues/${pr}/comments?per_page=100" \ - --jq '.[] | [.id, .user.login, (.body | split("\n") | .[0])] | @tsv' >"${listing}" || - die "Could not list the comments of #${pr}." - # '|| [ -n ... ]' also handles a last line without a newline. - while IFS=$'\t' read -r cid login first || [ -n "${cid}" ]; do - if [ "${login}" = "${BOT_LOGIN}" ] && [ "${first}" = "${want}" ]; then - id=${cid} - break - fi - done <"${listing}" - - if [ -n "${id}" ]; then - jq -Rsc '{body: .}' <"${body_file}" | - gh api -X PATCH "repos/${repo}/issues/comments/${id}" --input - --jq '.html_url' - else - jq -Rsc '{body: .}' <"${body_file}" | - gh api -X POST "repos/${repo}/issues/${pr}/comments" --input - --jq '.html_url' - fi -} - -[ $# -ge 1 ] || die "Usage: publish-comment sanitize|render|post [options]" -command=$1 -shift -case "${command}" in - sanitize) cmd_sanitize "$@" ;; - render) cmd_render "$@" ;; - post) cmd_post "$@" ;; - *) die "Unknown command '${command}'." ;; -esac +sys.exit(main()) diff --git a/agent-review/bin/run-review b/agent-review/bin/run-review old mode 100755 new mode 100644 index f8980f9..eea2487 --- a/agent-review/bin/run-review +++ b/agent-review/bin/run-review @@ -1,416 +1,15 @@ -#!/usr/bin/env bash -# In-sandbox driver of the agent review; harness-agnostic. -# -# Usage: run-review [--phase fetch|review|all] -# -# Runs INSIDE the AWF sandbox (see docs/agent-review.md), -# in two sandbox runs, so that the agent never has network access: -# fetch fetches the PR from github.com (the only allowed domain), with -# every object it needs, prepares the checkout and renders the -# prompt; no inference key, no harness; -# review runs the harness with no allowed domain (only the inference -# listener) and collects its review. -# 'all' (the default) does both in one run, for local tests. -# Everything it fetches from the pull request is untrusted: git runs with -# hooks, global/system config, submodules and LFS disabled, and nothing from -# the checkout is executed here. The harness adapter is the only component -# that acts on the content, and it holds no secret. -# -# Inputs, written by the trusted host before the sandbox starts: -# /in/params.json validated parameters (repo, pr, shas, harness, ...) -# /in/pr.json raw GitHub API response for the PR (untrusted) -# Outputs: -# /out/review.md the review, at most REVIEW_MAX_BYTES -# /out/meta.json status of the run -# -# Exit codes: 0 review written (or, for 'fetch', the checkout prepared), -# 2 the harness ran but produced no review, 1 anything else. +# agent-review Python entry point: run only as '/usr/bin/python3 -I -S -B /bin/'. +# The fixed template of agent-review/tests/workflow_structure.py; the code is in lib/agent_review/. +import sys -set -euo pipefail -shopt -u patsub_replacement 2>/dev/null || true +if not (sys.flags.isolated and sys.flags.no_site and sys.flags.dont_write_bytecode and sys.flags.safe_path): + sys.stderr.write("agent-review entry points run only as '/usr/bin/python3 -I -S -B /bin/'.\n") + sys.exit(2) -# Leaves room for the comment header under GitHub's 65536-character limit and -# under the 64 KiB 'collect-result' cap on the host. -readonly REVIEW_MAX_BYTES=60000 -readonly PR_BODY_MAX_BYTES=16384 -readonly PR_TITLE_MAX_BYTES=512 +import os # noqa: E402 -die() { - echo "run-review: $*" >&2 - exit 1 -} +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "lib")) -# Byte truncation can split a multi-byte character; 'iconv -c' drops it (and -# drops invalid bytes), exiting 1 when it does. Used by both phases, which run -# as separate processes. -clip() { head -c "$1" | { iconv -f UTF-8 -t UTF-8 -c 2>/dev/null || true; }; } +from agent_review.run_review import main # noqa: E402 -PHASE=all -if [ "${1:-}" = --phase ]; then - PHASE=${2:-} - shift 2 || die "Usage: run-review [--phase fetch|review|all] " -fi -case "${PHASE}" in fetch | review | all) ;; *) die "Invalid phase '${PHASE}'." ;; esac -[ $# -eq 1 ] || die "Usage: run-review [--phase fetch|review|all] " -WS=$1 -case "${WS}" in /*) ;; *) die "The workspace must be an absolute path, got '${WS}'." ;; esac - -TRUSTED_ROOT=$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd) -IN_DIR="${WS}/in" -REPO_DIR="${WS}/repo" -CONTEXT_DIR="${REPO_DIR}/.agent-review-context" -HARNESS_OUT="${WS}/harness-out" -RESULT_DIR="${WS}/out" -SCRATCH_HOME="${WS}/scratch-home" -SCRATCH_TMP="${WS}/scratch-tmp" - -# --- Parameters ----------------------------------------------------------- -param() { jq -er --arg k "$1" '.[$k] | tostring' "${IN_DIR}/params.json"; } - -REPO=$(param repo) -PR_NUMBER=$(param pr) -HEAD_SHA=$(param head_sha) -BASE_SHA=$(param base_sha) -HARNESS=$(param harness) -MODEL=$(param model) -HARNESS_TIMEOUT_MINUTES=$(param harness_timeout_minutes) -STUB_PADDING_KIB=$(jq -r '.stub_padding_kib // 0 | tostring' "${IN_DIR}/params.json") -PROJECT=$(jq -r '.project // "" | tostring' "${IN_DIR}/params.json") -[ -n "${PROJECT}" ] || PROJECT=${REPO#*/} - -# Validated in the 'authorize' job already; checked again because these become -# paths, URLs and command arguments. -[[ "${REPO}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || die "Invalid repo '${REPO}'." -[[ "${PR_NUMBER}" =~ ^[1-9][0-9]{0,9}$ ]] || die "Invalid PR number '${PR_NUMBER}'." -[[ "${HEAD_SHA}" =~ ^[0-9a-f]{40}$ ]] || die "Invalid head sha '${HEAD_SHA}'." -[[ "${BASE_SHA}" =~ ^[0-9a-f]{40}$ ]] || die "Invalid base sha '${BASE_SHA}'." -[[ "${HARNESS}" =~ ^[a-z][a-z0-9-]{0,31}$ ]] || die "Invalid harness '${HARNESS}'." -[[ "${MODEL}" =~ ^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$ ]] || die "Invalid model '${MODEL}'." -[[ "${HARNESS_TIMEOUT_MINUTES}" =~ ^[1-9][0-9]{0,2}$ ]] || die "Invalid timeout '${HARNESS_TIMEOUT_MINUTES}'." -[[ "${STUB_PADDING_KIB}" =~ ^[0-9]{1,5}$ ]] || die "Invalid stub padding '${STUB_PADDING_KIB}'." -[[ "${PROJECT}" =~ ^[A-Za-z0-9][A-Za-z0-9._\ -]{0,63}$ ]] || die "Invalid project '${PROJECT}'." - -# Caller configuration (trusted: the caller's validated inputs and its -# addendum file at the caller's workflow commit), next to this script's own -# files. Missing files mean "not configured". -CONFIG_DIR="${TRUSTED_ROOT}/config" -read_list() { # file -> non-comment, trimmed lines on stdout - [ -f "$1" ] || return 0 - sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' "$1" | grep -v -e '^$' -e '^#' || true -} -check_entry() { # entry - case "$1" in /* | :* | *..*) die "Invalid configured path or pattern: '$1'." ;; esac -} -mapfile -t RULE_FILES < <(read_list "${CONFIG_DIR}/rule-files.txt") -for f in "${RULE_FILES[@]}"; do check_entry "${f}"; done -# Reset patterns: the central list (every harness's files), the caller's -# extra patterns, and every rule file the prompt tells the agent to follow. -mapfile -t RESET_PATTERNS < <( - read_list "${TRUSTED_ROOT}/instruction-files.txt" - read_list "${CONFIG_DIR}/extra-instruction-files.txt" - printf '%s\n' "${RULE_FILES[@]}" -) -for f in "${RESET_PATTERNS[@]}"; do [ -z "${f}" ] || check_entry "${f}"; done - -# True if repository path $1 is reset by some pattern (same semantics as the -# pathspecs below: 'E' matches E at any depth, 'D/' anything under D). -covered() { - local path=$1 entry - for entry in "${RESET_PATTERNS[@]}"; do - [ -n "${entry}" ] || continue - if [[ "${entry}" == */ ]]; then - case "/${path}/" in */"${entry%/}"/*) return 0 ;; esac - else - # shellcheck disable=SC2053,SC2254 # entries may be globs - [[ "${path}" == ${entry} || "${path}" == */${entry} ]] && return 0 - fi - done - return 1 -} -# Fail closed: a file the addendum names as a rule must be reset too, or a PR -# could rewrite it and have the agent follow the PR's version. This early -# check uses bash matching, where '*' also crosses '/', unlike the git -# pathspecs of the reset; the post-condition after the reset -# ('verify_followed_files') is what enforces it. -ADDENDUM_FILE="${CONFIG_DIR}/prompt-addendum.md" -ADDENDUM_NAMED=() -if [ -s "${ADDENDUM_FILE}" ]; then - # The addendum is substituted into the prompt before the untrusted PR - # title and body; a placeholder in it would be expanded with them, outside - # their delimiters. - if grep -qF '{{' "${ADDENDUM_FILE}"; then - die "The prompt addendum contains '{{'; placeholders are not allowed there." - fi - mapfile -t ADDENDUM_NAMED < <(grep -oE '`[^`[:space:]]+\.(md|mdc|txt|toml|ya?ml|json|jsonc)`' "${ADDENDUM_FILE}" | tr -d '`' | sort -u) - for named in "${ADDENDUM_NAMED[@]}"; do - # A path from the repository root, which the post-condition can check. - case "/${named}/" in */../* | */./* | *//* | *[*?[]*) - die "The prompt addendum names '${named}', which is not a plain repository path." ;; - esac - covered "${named}" || die "The prompt addendum names '${named}', which no reset pattern covers; add it to rule_files." - done -fi - -ADAPTER_DIR="${TRUSTED_ROOT}/harnesses/${HARNESS}" -HARNESS_PREFIX="${TRUSTED_ROOT}/harness/${HARNESS}" -[ -f "${ADAPTER_DIR}/run.sh" ] || die "No adapter for harness '${HARNESS}'." -[ -d "${HARNESS_PREFIX}" ] || die "Harness '${HARNESS}' is not installed at '${HARNESS_PREFIX}'." - -write_meta() { # status harness_exit truncated review_bytes - mkdir -p "${RESULT_DIR}" - jq -n \ - --arg harness "${HARNESS}" --arg model "${MODEL}" --arg status "$1" \ - --argjson harness_exit "$2" --argjson truncated "$3" --argjson review_bytes "$4" \ - '{harness: $harness, model: $model, status: $status, harness_exit: $harness_exit, - truncated: $truncated, review_bytes: $review_bytes}' >"${RESULT_DIR}/meta.json" -} - -# --- Fetch the pull request ------------------------------------------------ -# No user or system git config: the host's may enable LFS filters or other -# helpers. Hooks and fsmonitor are disabled on every call since '.git' could -# otherwise be influenced by repository content. -export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_TERMINAL_PROMPT=0 -export GIT_LFS_SKIP_SMUDGE=1 GIT_NO_REPLACE_OBJECTS=1 -git_safe() { - git -c core.hooksPath=/dev/null -c core.fsmonitor=false -c core.symlinks=true \ - -c protocol.file.allow=never -c protocol.ext.allow=never \ - -c submodule.recurse=false -c diff.external= -c advice.detachedHead=false \ - -C "${REPO_DIR}" "$@" -} - -PROMPT_FILE="${WS}/prompt.md" - -# Post-condition of the reset: every file the prompt tells the agent to -# follow (each rule file, and each file the addendum names, as a path from -# the repository root) is exactly its base version, or absent in both the -# base and the checkout. Checked on the result rather than on the patterns, -# so a pattern that does not match what it seems to cannot let the PR's -# version through. No leading directory may be a symlink, so the path in the -# checkout is the path git wrote. -verify_followed_files() { - local path entry mode type id rest dir - for path in "${RULE_FILES[@]}" "${ADDENDUM_NAMED[@]}"; do - [ -n "${path}" ] || continue - case "/${path}/" in */../* | */./* | *//* | *[*?[]*) die "Invalid followed file '${path}': not a plain path." ;; esac - dir=${path} - while [[ "${dir}" == */* ]]; do - dir=${dir%/*} - [ ! -L "${REPO_DIR}/${dir}" ] || die "Followed file '${path}': '${dir}' is a symlink in the checkout." - done - entry=$(git_safe ls-tree --full-tree "${BASE_SHA}" -- "${path}") - if [ -z "${entry}" ]; then - if [ -e "${REPO_DIR}/${path}" ] || [ -L "${REPO_DIR}/${path}" ]; then - die "Followed file '${path}' is not in the base commit but is in the checkout: the reset missed it." - fi - continue - fi - read -r mode type id rest <<<"${entry}" - [ "${rest}" = "${path}" ] || die "Followed file '${path}': unexpected base entry '${entry}'." - case "${mode}:${type}" in - 100644:blob | 100755:blob) - [ -f "${REPO_DIR}/${path}" ] && [ ! -L "${REPO_DIR}/${path}" ] && - [ "$(git_safe hash-object --no-filters -- "${path}")" = "${id}" ] || - die "Followed file '${path}' is not its base version in the checkout: the reset missed it." - ;; - 120000:blob) - [ -L "${REPO_DIR}/${path}" ] && [ "$(readlink -- "${REPO_DIR}/${path}")" = "$(git_safe cat-file blob "${id}")" ] || - die "Followed file '${path}' is not its base version in the checkout: the reset missed it." - ;; - *) die "Followed file '${path}' is not a file in the base commit (mode ${mode})." ;; - esac - done - echo "run-review: ${#RULE_FILES[@]} rule file(s) and ${#ADDENDUM_NAMED[@]} file(s) named by the addendum are their base versions." -} - -fetch_phase() { - rm -rf "${REPO_DIR}" "${PROMPT_FILE}" "${HARNESS_OUT}" "${RESULT_DIR}" "${SCRATCH_HOME}" "${SCRATCH_TMP}" - mkdir -p "${REPO_DIR}" "${SCRATCH_HOME}" "${SCRATCH_TMP}" - # Everything stays in the workspace, the only directory the sandbox may - # write to ('filesystem.allowWrite'). - export HOME="${SCRATCH_HOME}" TMPDIR="${SCRATCH_TMP}" - git_safe init -q - git_safe remote add origin "https://github.com/${REPO}.git" - - # Fetch by sha so the reviewed commit is exactly the one authorized; never - # fall back to the moving 'refs/pull/N/head'. Full objects, no partial clone: - # the review phase has no network, so nothing can be fetched lazily there. - git_safe fetch -q --no-tags --depth=50 origin "${HEAD_SHA}" "${BASE_SHA}" - [ "$(git_safe rev-parse --verify "${HEAD_SHA}^{commit}")" = "${HEAD_SHA}" ] || - die "Fetched head does not match ${HEAD_SHA}." - [ "$(git_safe rev-parse --verify "${BASE_SHA}^{commit}")" = "${BASE_SHA}" ] || - die "Fetched base does not match ${BASE_SHA}." - - # A three-dot diff needs the merge base, which a shallow fetch may lack. - MERGE_BASE="" - for deepen in 200 1000 5000; do - if MERGE_BASE=$(git_safe merge-base "${BASE_SHA}" "${HEAD_SHA}" 2>/dev/null); then - break - fi - git_safe fetch -q --no-tags --deepen="${deepen}" origin "${HEAD_SHA}" "${BASE_SHA}" - done - if [ -z "${MERGE_BASE}" ]; then - git_safe fetch -q --no-tags --unshallow origin "${HEAD_SHA}" "${BASE_SHA}" - MERGE_BASE=$(git_safe merge-base "${BASE_SHA}" "${HEAD_SHA}") || die "No merge base between base and head." - fi - - git_safe checkout -q --detach "${HEAD_SHA}" - - # --- Context files ----------------------------------------------------------- - # The PR may itself contain '.agent-review-context'; git removes it safely - # (it does not follow symlinks), then the directory is created fresh. - git_safe rm -r -q -f --ignore-unmatch -- .agent-review-context - rm -rf "${CONTEXT_DIR}" - mkdir -p "${CONTEXT_DIR}/pr-instruction-files" - printf '/.agent-review-context/\n' >>"${REPO_DIR}/.git/info/exclude" - - git_safe diff --no-ext-diff --no-textconv "${MERGE_BASE}" "${HEAD_SHA}" >"${CONTEXT_DIR}/diff.patch" - git_safe diff --no-ext-diff --name-status "${MERGE_BASE}" "${HEAD_SHA}" >"${CONTEXT_DIR}/changed-files.txt" - - # --- Reset agent instruction files to the base version ----------------------- - # Every pattern applies at any depth (see instruction-files.txt), and - # case-insensitively, since a harness may not care about case either. - SPECS=() - for pattern in "${RESET_PATTERNS[@]}"; do - case "${pattern}" in - '') continue ;; - */) SPECS+=(":(glob,icase)**/${pattern}**") ;; - *) SPECS+=(":(glob,icase)**/${pattern}") ;; - esac - done - [ "${#SPECS[@]}" -gt 0 ] || die "No reset patterns." - # 'ls-files', not 'ls-tree', which rejects the ':(glob)' magic. The index - # holds the head tree after the checkout; the base tree goes into a scratch - # index. Listed into files so a git failure stops the run (set -e). - git_safe ls-files -z -- "${SPECS[@]}" >"${WS}/pr-paths" - GIT_INDEX_FILE="${WS}/base.index" git_safe read-tree "${BASE_SHA}" - GIT_INDEX_FILE="${WS}/base.index" git_safe ls-files -z -- "${SPECS[@]}" >"${WS}/base-paths" - mapfile -d '' -t PR_PATHS <"${WS}/pr-paths" - mapfile -d '' -t BASE_PATHS <"${WS}/base-paths" - rm -f "${WS}/pr-paths" "${WS}/base-paths" "${WS}/base.index" - - for path in "${PR_PATHS[@]}"; do - # Git refuses such paths in trees, but they become filesystem paths here. - case "/${path}/" in */../* | */./* | *//*) die "Unexpected path in PR tree: '${path}'." ;; esac - # Only what the PR adds or changes is kept, so the review can comment on it. - head_id=$(git_safe rev-parse "${HEAD_SHA}:${path}") - base_id=$(git_safe rev-parse -q --verify "${BASE_SHA}:${path}" || true) - [ "${head_id}" != "${base_id}" ] || continue - dest="${CONTEXT_DIR}/pr-instruction-files/${path}.txt" - mkdir -p "$(dirname "${dest}")" - git_safe cat-file -p "${HEAD_SHA}:${path}" >"${dest}" - done - if [ "${#PR_PATHS[@]}" -gt 0 ]; then - # Git removes paths without following symlinks in leading components. - git_safe --literal-pathspecs rm -r -q -f --ignore-unmatch -- "${PR_PATHS[@]}" - fi - if [ "${#BASE_PATHS[@]}" -gt 0 ]; then - git_safe --literal-pathspecs checkout -q "${BASE_SHA}" -- "${BASE_PATHS[@]}" - fi - verify_followed_files - - # --- Render the prompt ------------------------------------------------------- - PR_TITLE=$(jq -r '.title // "" | tostring' "${IN_DIR}/pr.json" | tr -d '\r' | head -n 1 | clip "${PR_TITLE_MAX_BYTES}") - PR_BODY=$(jq -r '.body // "" | tostring' "${IN_DIR}/pr.json" | tr -d '\r' | clip "${PR_BODY_MAX_BYTES}") - NONCE=$(head -c 12 /dev/urandom | od -An -tx1 | tr -d ' \n') - # The PR cannot know the nonce, but strip it anyway so the delimiters stay unique. - PR_TITLE=${PR_TITLE//"${NONCE}"/} - PR_BODY=${PR_BODY//"${NONCE}"/} - - if [ "${#RULE_FILES[@]}" -gt 0 ]; then - RULES=$(i=0; for f in "${RULE_FILES[@]}"; do i=$((i + 1)); printf '%d. `%s`, if it exists.\n' "${i}" "${f}"; done) - else - RULES="No project rule files are configured." - fi - ADDENDUM="" - if [ -s "${ADDENDUM_FILE}" ]; then - ADDENDUM=$(printf '### Project notes\n\n%s\n' "$(clip 8192 <"${ADDENDUM_FILE}")") - fi - - prompt=$(<"${TRUSTED_ROOT}/prompt.md.tmpl") - # Trusted caller text first, so that placeholders inside it are expanded - # like the template's own; untrusted values last. - prompt=${prompt//"{{ADDENDUM}}"/"${ADDENDUM}"} - prompt=${prompt//"{{RULES}}"/"${RULES}"} - prompt=${prompt//"{{PROJECT}}"/"${PROJECT}"} - prompt=${prompt//"{{REPO}}"/"${REPO}"} - prompt=${prompt//"{{PR_NUMBER}}"/"${PR_NUMBER}"} - prompt=${prompt//"{{HEAD_SHA}}"/"${HEAD_SHA}"} - prompt=${prompt//"{{BASE_SHA}}"/"${BASE_SHA}"} - prompt=${prompt//"{{MERGE_BASE}}"/"${MERGE_BASE}"} - prompt=${prompt//"{{CONTEXT_DIR}}"/".agent-review-context"} - prompt=${prompt//"{{NONCE}}"/"${NONCE}"} - # Untrusted values last, so placeholders inside them are not expanded. - prompt=${prompt//"{{PR_TITLE}}"/"${PR_TITLE}"} - prompt=${prompt//"{{PR_BODY}}"/"${PR_BODY}"} - printf '%s\n' "${prompt}" >"${PROMPT_FILE}" - echo "run-review: fetched ${REPO}#${PR_NUMBER} at ${HEAD_SHA} (merge base ${MERGE_BASE})." -} - -review_phase() { - # The checkout and prompt come from the fetch phase, which ran no agent. - [ -f "${PROMPT_FILE}" ] && [ -d "${REPO_DIR}/.git" ] || die "No prepared checkout in '${WS}'; run the fetch phase first." - rm -rf "${HARNESS_OUT}" "${RESULT_DIR}" "${SCRATCH_HOME}" "${SCRATCH_TMP}" - mkdir -p "${HARNESS_OUT}" "${RESULT_DIR}" "${SCRATCH_HOME}" "${SCRATCH_TMP}" - export HOME="${SCRATCH_HOME}" TMPDIR="${SCRATCH_TMP}" - - # --- Run the harness ----------------------------------------------------------- - echo "run-review: running harness '${HARNESS}' on ${REPO}#${PR_NUMBER} at ${HEAD_SHA}." - harness_exit=0 - ( - cd "${REPO_DIR}" - export PROMPT_FILE REPO_DIR MODEL HARNESS_PREFIX PR_NUMBER CONTEXT_DIR STUB_PADDING_KIB - # The harness writes to its own directory; only this script writes the result. - OUT_DIR="${HARNESS_OUT}" exec timeout --kill-after=30s "${HARNESS_TIMEOUT_MINUTES}m" bash "${ADAPTER_DIR}/run.sh" - ) || harness_exit=$? - - case "${harness_exit}" in - 0) status=ok ;; - 2) status=no-review ;; - 124 | 137) status=timeout ;; - *) status=failed ;; - esac - - # --- Collect the review ---------------------------------------------------------- - # The harness output is agent-controlled: accept only a regular file. The host - # re-checks this ('collect-result'); this check keeps the failure readable. - candidate="${HARNESS_OUT}/review.md" - if [ "${status}" != ok ] || [ -L "${candidate}" ] || [ ! -f "${candidate}" ] || [ ! -s "${candidate}" ]; then - [ "${status}" = ok ] && status=no-review - write_meta "${status}" "${harness_exit}" false 0 - echo "run-review: no review produced (status '${status}', harness exit ${harness_exit})." >&2 - [ "${status}" = no-review ] && exit 2 - exit 1 - fi - - # Models often open their answer with a note ("Writing the final review - # now.", "Maximum steps ... reached") although the prompt asks them to start - # with '### Summary'. Keep the review from its first '### ' heading, if any. - body="${RESULT_DIR}/review.body" - if grep -q '^### ' <"${candidate}"; then - awk 'f || /^### /{f = 1} f' <"${candidate}" >"${body}" - else - cat <"${candidate}" >"${body}" - fi - - size=$(stat -c %s -- "${body}") - truncated=false - if [ "${size}" -gt "${REVIEW_MAX_BYTES}" ]; then - truncated=true - clip "$((REVIEW_MAX_BYTES - 100))" <"${body}" >"${RESULT_DIR}/review.md" - printf '\n\n_[Review truncated: it exceeded %d bytes.]_\n' "${REVIEW_MAX_BYTES}" >>"${RESULT_DIR}/review.md" - else - { iconv -f UTF-8 -t UTF-8 -c 2>/dev/null || true; } <"${body}" >"${RESULT_DIR}/review.md" - fi - rm -f "${body}" - write_meta ok "${harness_exit}" "${truncated}" "$(stat -c %s -- "${RESULT_DIR}/review.md")" - echo "run-review: review written ($(stat -c %s -- "${RESULT_DIR}/review.md") bytes, truncated=${truncated})." -} - -case "${PHASE}" in - fetch) fetch_phase ;; - review) review_phase ;; - all) - fetch_phase - review_phase - ;; -esac +sys.exit(main()) diff --git a/agent-review/harnesses/README.md b/agent-review/harnesses/README.md index f3a625e..85a9891 100644 --- a/agent-review/harnesses/README.md +++ b/agent-review/harnesses/README.md @@ -13,7 +13,8 @@ the pull request or the calling repository. | `README.md` | Pinned version, how to upgrade it, the paths it reads as instructions or configuration (add them to `../instruction-files.txt`), and any outbound calls it tries to make. | The harness name must also be added to the harness allowlist in -`agent-review/bin/authorize`, as keyed (`wire` `openai-chat`: it runs in the +`agent-review/lib/agent_review/authorize.py` (`KEYED_HARNESSES` or +`KEYLESS_HARNESSES`), as keyed (`wire` `openai-chat`: it runs in the `review` job, with the caller's environment and key) or keyless (`wire` `none`: the `review-keyless` job); both jobs check that the `wire` agrees. Callers that offer it add it to their `workflow_dispatch` choice. diff --git a/agent-review/harnesses/common.sh b/agent-review/harnesses/common.sh index dabe080..d7ffdc0 100644 --- a/agent-review/harnesses/common.sh +++ b/agent-review/harnesses/common.sh @@ -29,9 +29,12 @@ adapter_init() { # name } # Prints stdin to stderr with every line prefixed and clipped, at most -# DIAG_MAX_LINES lines. +# DIAG_MAX_LINES lines; NUL bytes are dropped and every '##[' is broken up +# with a zero-width space, since the runner finds a legacy '##[command]' +# anywhere in a line. diag() { - head -n "${DIAG_MAX_LINES:-40}" | cut -c1-400 | sed "s/^/${ADAPTER_NAME:-harness}| /" >&2 + head -n "${DIAG_MAX_LINES:-40}" | cut -c1-400 | + sed -e 's/\x00//g' -e 's/##\[/#\xe2\x80\x8b#[/g' -e "s/^/${ADAPTER_NAME:-harness}| /" >&2 } # A bounded summary of a run that produced no review: the harness exit code, diff --git a/agent-review/harnesses/stub/install.sh b/agent-review/harnesses/stub/install.sh index 5614cf4..1ed8c9d 100755 --- a/agent-review/harnesses/stub/install.sh +++ b/agent-review/harnesses/stub/install.sh @@ -12,3 +12,9 @@ set -euo pipefail [ $# -eq 1 ] || { echo "Usage: install.sh " >&2; exit 1; } mkdir -p "$1" echo "stub-1" >"$1/VERSION" + +# The Python runtime on the host, as the trusted entry points get it +# (bin/probe, one line; docs/adr/0004-python-runtime.md). run.sh prints the +# same line from inside the sandbox; the self-test compares the two. +ar_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +/usr/bin/python3 -I -S -B "${ar_root}/bin/probe" diff --git a/agent-review/harnesses/stub/run.sh b/agent-review/harnesses/stub/run.sh index 1e8ab7d..dda992f 100755 --- a/agent-review/harnesses/stub/run.sh +++ b/agent-review/harnesses/stub/run.sh @@ -22,6 +22,24 @@ diff_bytes=$(wc -c <"${CONTEXT_DIR}/diff.patch") prompt_bytes=$(wc -c <"${PROMPT_FILE}") head_sha=$(git -c core.hooksPath=/dev/null -C "${REPO_DIR}" rev-parse HEAD) +# The Python runtime inside the sandbox, from the PR checkout as working +# directory (bin/probe; install.sh prints the host's line). +ar_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +/usr/bin/python3 -I -S -B "${ar_root}/bin/probe" + +# Sandbox output must not issue workflow commands in the legacy syntax +# either, which the runner finds anywhere in a line (invariant 11): one line +# on stdout and one through 'diag'. The self-test's 'check' job asserts +# that neither became an annotation. +# shellcheck source=../common.sh +. "${ar_root}/harnesses/common.sh" +echo "stub: ##[warning]agent-review-legacy-probe (stdout)" +echo "##[warning]agent-review-legacy-probe (diag)" | ADAPTER_NAME=stub diag +# The same with a NUL byte between the two '#', which a filter matching +# only the literal '##[' would let through. +printf 'stub: #\0#[warning]agent-review-legacy-probe (stdout, NUL)\n' +printf '#\0#[warning]agent-review-legacy-probe (diag, NUL)\n' | ADAPTER_NAME=stub diag + # Names only, never values: confirms in the log that no credential-like # variable other than AWF's placeholders reaches the sandbox. echo "stub: credential-like variables in the sandbox environment:" diff --git a/agent-review/instruction-files.txt b/agent-review/instruction-files.txt index d457d9f..45c2d5c 100644 --- a/agent-review/instruction-files.txt +++ b/agent-review/instruction-files.txt @@ -10,8 +10,12 @@ # files in subdirectories too (opencode attaches a nested AGENTS.md to every # file it reads in that directory). A pattern ending in '/' matches a # directory and everything below it. Blank lines and lines starting with '#' -# are ignored. Each pattern becomes the git pathspec ':(glob)**/' -# (or ':(glob)**/**' for directories), so '*' does not cross '/'. +# are ignored. Each pattern becomes the git pathspec +# ':(glob,icase)**/' (or ':(glob,icase)**/**' for +# directories), so '*' does not cross '/' and case does not matter. A +# symlink or a gitlink where a directory pattern names a directory, or at a +# directory leading to a pattern with '/', is reset too (see +# docs/agent-review.md, invariant 6). # # This is the union over all harnesses: extend it when adding an adapter # (see harnesses/README.md). diff --git a/agent-review/lib/agent_review/__init__.py b/agent-review/lib/agent_review/__init__.py new file mode 100644 index 0000000..e4e4934 --- /dev/null +++ b/agent-review/lib/agent_review/__init__.py @@ -0,0 +1,9 @@ +"""The agent review's trusted Python code (standard library only). + +Run only through an entry point in ``agent-review/bin/``, as +``/usr/bin/python3 -I -S -B /bin/`` (docs/adr/0004-python-runtime.md). + +This file imports no submodule: an entry point's import closure must hold +only what it uses, so that the structure test can tell which entry points +reach the ``gh`` wrapper (and with it a token). +""" diff --git a/agent-review/lib/agent_review/authorize.py b/agent-review/lib/agent_review/authorize.py new file mode 100644 index 0000000..6d92954 --- /dev/null +++ b/agent-review/lib/agent_review/authorize.py @@ -0,0 +1,581 @@ +"""The 'authorize' job of the agent review: ``bin/authorize``. + +Validates the caller's inputs, decides whether this event may run a review +and with which key mode, checks the actor's permission and pins the pull +request's head and base sha. + +Runs on the host, before anything from the pull request is read, in the +trusted-host zone: ``gh`` (with ``GH_TOKEN``) is found on ``PATH`` and +inherits the environment; only ``agent_review.gh`` runs it, with ``--jq`` +projections, so this module never parses a pull request object +(invariant 2). It writes its outputs to ``$GITHUB_OUTPUT``. It fails +closed: an invalid input or an API failure is an error (``allowed=false``, +exit 1); a denied actor or an event that is not for us is a notice +(``allowed=false``, exit 0). + +Environment (all from the workflow; ``IN_*`` are the caller's inputs, which +come from the caller's workflow file); an unset variable is the same as an +empty one: + +- ``REPO EVENT ACTION AUTHOR SENDER ACTOR EVENT_PR EVENT_HEAD_SHA + EVENT_BASE_SHA EVENT_DRAFT EVENT_LABEL``: the github context and the event + payload; +- ``IN_PR IN_HARNESS IN_MODEL IN_DRY_RUN IN_LABEL IN_PROJECT IN_RULES + IN_PATTERNS IN_ADDENDUM IN_API_BASE IN_RPH IN_RPM IN_TURNS IN_TIMEOUT + IN_ENVIRONMENT IN_TEST_REPO``: the caller's inputs; +- ``TRUSTED_REPO TRUSTED_SHA``: ``job.workflow_repository`` and ``_sha``; +- ``CALLER_WF_SHA``: the caller's ``github.workflow_sha``; +- ``HAS_SHARED_KEY``: ``true`` if ``secrets.inference_api_key`` is non-empty + in this job, which declares no environment. + +Event and harness matrix ('keyed' harnesses call a model with the key): + +- ``pull_request_target``: any harness; actions ``labeled`` (with the + configured label), ``opened``, ``reopened``, ``ready_for_review``; writer + check on the labeller or the author; +- ``workflow_dispatch``: any harness; writer check on the actor; +- ``pull_request``: ``stub`` only, forced dry run, no writer check: the + caller test mode (any caller) and the self-test; +- ``push``, ``schedule``: ``stub`` only, forced dry run, no writer check; + the self-test of the workflow's own repository only. + +The checks run in a fixed order, which tests/test-authorize.sh pins, so +the same input always stops at the same first error. Values are read +strictly (docs/agent-review.md, "Inputs"): ASCII-only classes and +whitespace, values that are not UTF-8 are rejected, and ``gh`` output is +compared exactly as text: a NUL is kept, so such a value never matches, and +output on stderr is a failure. +""" + +import os +import re +import secrets +from collections.abc import Callable, Mapping, Sequence + +from agent_review import files, gh, runner, validate, workflow + +DOCS = "See https://github.com/GridTools/ci-workflows/blob/main/docs/agent-review.md#inputs." +VARIABLES = ( + "REPO", + "EVENT", + "ACTION", + "AUTHOR", + "SENDER", + "ACTOR", + "EVENT_PR", + "EVENT_HEAD_SHA", + "EVENT_BASE_SHA", + "EVENT_DRAFT", + "EVENT_LABEL", + "IN_PR", + "IN_HARNESS", + "IN_MODEL", + "IN_DRY_RUN", + "IN_LABEL", + "IN_PROJECT", + "IN_RULES", + "IN_PATTERNS", + "IN_ADDENDUM", + "IN_API_BASE", + "IN_RPH", + "IN_RPM", + "IN_TURNS", + "IN_TIMEOUT", + "IN_ENVIRONMENT", + "IN_TEST_REPO", + "TRUSTED_REPO", + "TRUSTED_SHA", + "CALLER_WF_SHA", + "HAS_SHARED_KEY", +) + +# The harness allowlist decides whether the run is keyed: only keyed runs +# get the job with the caller's environment, and so the key. +KEYLESS_HARNESSES = ("stub",) +KEYED_HARNESSES = ("opencode", "pi") + +# Ceilings: a caller can lower the caps, never raise them. The review job +# also clamps them to agent-review/awf.yaml. (input name, variable, maximum) +CAPS = ( + ("requests_per_hour", "IN_RPH", 100), + ("requests_per_minute", "IN_RPM", 30), + ("max_turns", "IN_TURNS", 80), + ("harness_timeout_minutes", "IN_TIMEOUT", 20), +) + +PR_ACTIONS_BY_AUTHOR = ("opened", "reopened", "ready_for_review") +STUB_EVENTS = ("pull_request", "push", "schedule") +WRITER_LEVELS = ("admin", "write") + +# ASCII whitespace. Never str.strip() without arguments, which also removes +# Unicode spaces and \x1c-\x1f, so an entry padded with them would pass. +SPACE = " \t\n\v\f\r" +# What separates two fields on one line: blanks, not CR, VT or FF. +IFS_BLANKS = " \t" +API_BASES_FILE = "api-bases.txt" +API_BASES_MAX_BYTES = 64 * 1024 + +# Applied with fullmatch and ASCII classes (validate.pattern). +LABEL = validate.pattern(r"[A-Za-z0-9][A-Za-z0-9 ._:/-]{0,49}") +ENVIRONMENT = validate.pattern(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}") +CAP = validate.pattern(r"[1-9][0-9]{0,3}") +ACTOR = validate.pattern(r"[A-Za-z0-9][A-Za-z0-9-]{0,38}(?:\[bot\])?") +# A plain path, and a pattern, which may also hold '*'. +PLAIN_PATH = validate.pattern(r"[A-Za-z0-9_.][A-Za-z0-9_./-]{0,199}") +GLOB_PATH = validate.pattern(r"[A-Za-z0-9_.*][A-Za-z0-9_.*/-]{0,199}") +REPO = validate.REPO +SHA = validate.SHA +PR_NUMBER = validate.POSITIVE_INT +MODEL = validate.MODEL +PROJECT = validate.PROJECT + +PR_SHAS_JQ = "[.head.sha, .base.sha] | @tsv" +PERMISSION_JQ = ".permission" + + +class Fail(Exception): + """An invalid input or an API failure: an error, exit 1.""" + + def __init__(self, message: str) -> None: + super().__init__(message) + self.message = message + + +class Skip(Exception): + """Not for us, or a denied actor: a notice, exit 0.""" + + def __init__(self, message: str) -> None: + super().__init__(message) + self.message = message + + +# --- Reading the environment --------------------------------------------------- + + +def read_environment(environb: Mapping[bytes, bytes]) -> dict[str, str]: + """The variables of VARIABLES as strict UTF-8; unset is empty. + + Values that are not UTF-8 cannot come from the workflow (its contexts + are JSON strings), so they are rejected here. + """ + env = {} + for name in VARIABLES: + raw = environb.get(name.encode("ascii"), b"") + try: + env[name] = raw.decode("utf-8", errors="strict") + except UnicodeDecodeError: + raise Fail(f"Variable {name} is not valid UTF-8.") from None + return env + + +# --- Splitting inputs and command output ------------------------------------------- +# +# Exact rules, pinned by tests/test-authorize.sh: what counts as a line, a +# blank or a separator decides which entries are checked. + + +def trim(text: str) -> str: + """``text`` without ASCII whitespace at either end (see SPACE).""" + return text.strip(SPACE) + + +def heredoc_lines(text: str) -> list[str]: + """The lines of a multi-line input, the last one too. + + Only LF separates lines: a CR stays part of its line, where the entry's + pattern rejects it. + """ + return text.split("\n") + + +def count_nonempty_lines(text: str) -> int: + """The number of lines with at least one character.""" + return sum(1 for line in text.split("\n") if line) + + +def command_output(stdout: bytes) -> str: + """A command's stdout as text, without trailing newlines. + + NUL bytes are kept, so a value with a NUL never compares equal to a + valid one. Bytes that are not UTF-8 become U+FFFD, which no pattern or + allowed value contains. + """ + return stdout.decode("utf-8", errors="replace").rstrip("\n") + + +def read_two_fields(text: str) -> tuple[str, str]: + """Two blank-separated fields of ``text``. + + The first line only; leading and trailing blanks (space, tab) removed; + ``a`` is the first field, ``b`` the rest of the line. Other whitespace + (CR, VT, FF) is not a separator and stays in the fields. + """ + line = text.split("\n", 1)[0].strip(IFS_BLANKS) + m = re.fullmatch(r"([^ \t]*)[ \t]*(.*)", line, re.ASCII | re.DOTALL) + assert m is not None # noqa: S101 (the pattern matches every string) + return m.group(1), m.group(2) + + +# --- Validators ---------------------------------------------------------------- + + +def check_path(name: str, entry: str, glob: bool) -> None: + """One repository path or pattern. + + No absolute path, no '..' anywhere (as 'run-review' checks), no empty or + '.' segment. A pattern may end in '/' (a directory, see + instruction-files.txt); a path may not. + """ + compiled = GLOB_PATH if glob else PLAIN_PATH + stem = entry[:-1] if glob and entry.endswith("/") else entry + wrapped = f"/{stem}/" + if not validate.matches(compiled, entry) or ".." in wrapped or "/./" in wrapped or "//" in wrapped: + raise Fail(f"Invalid entry in {name}: '{entry}'.") + + +def check_list(name: str, text: str, glob: bool) -> None: + """A list, one entry per line; blank lines and '#' comments are skipped, + as 'run-review' reads these lists.""" + for line in heredoc_lines(text): + entry = trim(line) + if entry == "" or entry.startswith("#"): + continue + check_path(name, entry, glob) + + +def check_addendum(text: str) -> None: + """One path, no comment syntax: the value becomes part of an API path.""" + if text == "": + return + if count_nonempty_lines(text) > 1: + raise Fail("Input prompt_addendum takes one path.") + check_path("prompt_addendum", trim(text), False) + + +def check_cap(name: str, value: str, maximum: int) -> None: + """An integer in 1..maximum; validated by pattern before int().""" + if not validate.matches(CAP, value) or int(value, 10) > maximum: + raise Fail(f"Input {name} must be an integer in 1..{maximum}, got '{value}'.") + + +def key_mode(harness: str) -> bool: + """True if the harness is keyed (calls a model with the key).""" + if harness in KEYLESS_HARNESSES: + return False + if harness in KEYED_HARNESSES: + return True + if harness == "": + raise Fail("No harness given (input 'harness').") + raise Fail(f"Unknown harness '{harness}'.") + + +def check_shared_key(flag: str) -> None: + """The key must be an environment secret. + + Here, in a job without an environment, the caller's mapping yields a + repository or organization secret of that name, which every job of this + workflow would then receive. + """ + if flag == "false": + return + if flag == "true": + raise Fail( + "Secret 'inference_api_key' is readable in a job without an environment: the caller maps a repository" + " or organization secret. Map it only from the environment's own secret, and delete the shared one." + ) + raise Fail(f"Invalid HAS_SHARED_KEY '{flag}'.") + + +def choose_model(keyed: bool, model: str, harness: str) -> str: + """The stub calls no model. The others have no default model on purpose.""" + if not keyed: + return "none" + if model == "": + raise Fail(f"No model given for harness '{harness}' (input 'model').") + if not validate.matches(MODEL, model): + raise Fail(f"Invalid model id '{model}'.") + return model + + +def parse_api_bases(text: str) -> list[str]: + """``grep -v -e '^#' -e '^$'``, one entry per line.""" + return [line for line in text.split("\n") if line != "" and not line.startswith("#")] + + +def choose_api_base(value: str, allowed: Sequence[str]) -> str: + """Where the key is sent: an exact entry of the central allowlist.""" + if not allowed: + raise Fail("No allowed inference endpoint in api-bases.txt.") + api_base = value or allowed[0] + if api_base not in allowed: + raise Fail(f"Input api_base '{api_base}' is not an allowed inference endpoint (agent-review/api-bases.txt).") + return api_base + + +# --- GitHub lookups -------------------------------------------------------------- + + +def _gh_message(e: Exception) -> str: + """What to show of a failed ``gh`` call: its stderr, else the error.""" + if isinstance(e, runner.CommandError) and e.stderr: + return command_output(e.stderr) + return str(e) + + +def lookup_pr_shas(repo: str, number: str) -> tuple[str, str]: + """(head sha, base sha) of a pull request, unvalidated.""" + try: + out = gh.api(f"repos/{repo}/pulls/{number}", jq=PR_SHAS_JQ, stderr_is_error=True) + except (runner.CommandError, ValueError) as e: + raise Fail(f"Could not resolve pull request {repo}#{number}: '{_gh_message(e)}'.") from None + return read_two_fields(command_output(out)) + + +def lookup_permission(repo: str, actor: str) -> str: + """The actor's 'permission' field, unvalidated.""" + try: + out = gh.api(f"repos/{repo}/collaborators/{actor}/permission", jq=PERMISSION_JQ, stderr_is_error=True) + except (runner.CommandError, ValueError) as e: + raise Fail(f"Could not resolve repository permission for '{actor}', denying: '{_gh_message(e)}'.") from None + return command_output(out) + + +# --- The decision ---------------------------------------------------------------- + + +def decide( + env: Mapping[str, str], + api_bases: Callable[[], list[str]], + notice: Callable[[str], None], + pr_shas: Callable[[str, str], tuple[str, str]] = lookup_pr_shas, + permission: Callable[[str, str], str] = lookup_permission, +) -> list[tuple[str, str]]: + """The outputs of an allowed run, in order; raises Fail or Skip. + + The checks run in a fixed order, which tests/test-authorize.sh pins, so + that the same input stops at the same check. + """ + # This workflow's own commit, from which every trusted file is read. + trusted_repo, trusted_sha, repo = env["TRUSTED_REPO"], env["TRUSTED_SHA"], env["REPO"] + if not validate.matches(REPO, trusted_repo): + raise Fail(f"No job.workflow_repository ('{trusted_repo}').") + if not validate.matches(SHA, trusted_sha): + raise Fail(f"No job.workflow_sha ('{trusted_sha}').") + if not validate.matches(REPO, repo): + raise Fail(f"Invalid repository '{repo}'.") + notice(f"Agent review workflow {trusted_repo}@{trusted_sha}; caller {repo}@{env['CALLER_WF_SHA']}.") + + # Harness and key mode. + harness = env["IN_HARNESS"] + keyed = key_mode(harness) + check_shared_key(env["HAS_SHARED_KEY"]) + + # Static inputs, validated before any API call, so a misconfigured + # caller fails visibly. + label = env["IN_LABEL"] + if not validate.matches(LABEL, label): + raise Fail(f"Invalid label '{label}'.") + if env["IN_DRY_RUN"] not in ("true", "false"): + raise Fail(f"Invalid dry-run flag '{env['IN_DRY_RUN']}'.") + model = choose_model(keyed, env["IN_MODEL"], harness) + project = env["IN_PROJECT"] or repo.split("/", 1)[1] + if not validate.matches(PROJECT, project): + raise Fail(f"Invalid project name '{project}'.") + check_list("rule_files", env["IN_RULES"], False) + check_list("instruction_files", env["IN_PATTERNS"], True) + check_addendum(env["IN_ADDENDUM"]) + api_base = choose_api_base(env["IN_API_BASE"], api_bases()) + if not validate.matches(ENVIRONMENT, env["IN_ENVIRONMENT"]): + raise Fail(f"Invalid environment '{env['IN_ENVIRONMENT']}'.") + for name, variable, maximum in CAPS: + check_cap(name, env[variable], maximum) + + # The self-test: this repository calling its own workflow with the stub. + self_test = trusted_repo == repo and not keyed + + # The repository whose pull request is reviewed: the caller's, or + # (self-test only) another public repository, read-only. + event = env["EVENT"] + source_repo = repo + test_repo = env["IN_TEST_REPO"] + if test_repo != "": + if not self_test: + raise Fail(f"Input test_repository is for the self-test of {trusted_repo} with the 'stub' harness only.") + if event == "pull_request_target": + raise Fail("Input test_repository is not supported under 'pull_request_target'.") + if not validate.matches(REPO, test_repo): + raise Fail(f"Invalid test_repository '{test_repo}'.") + source_repo = test_repo + + dry_run = env["IN_DRY_RUN"] + check_writer = True + if event == "pull_request_target": + # Only these actions; a caller listing other 'types' (or none, which + # means every push to a PR) gets no keyed run from them. + action = env["ACTION"] + if action == "labeled": + if env["EVENT_LABEL"] != label: + raise Skip(f"Label '{env['EVENT_LABEL']}' does not request a review.") + actor = env["SENDER"] + elif action in PR_ACTIONS_BY_AUTHOR: + if env["EVENT_DRAFT"] == "true": + raise Skip(f"Draft pull request; add the '{label}' label to request a review.") + actor = env["AUTHOR"] + else: + raise Skip( + f"Action '{action}' of 'pull_request_target' does not start a review" + " (allowed: labeled, opened, reopened, ready_for_review)." + ) + pr, head_sha, base_sha = env["EVENT_PR"], env["EVENT_HEAD_SHA"], env["EVENT_BASE_SHA"] + elif event == "workflow_dispatch": + pr = env["IN_PR"] + head_sha, base_sha = resolve_pr(source_repo, pr, pr_shas) + actor = env["ACTOR"] + elif event in STUB_EVENTS: + # Nothing to spend and nothing to post, so no writer check (fork and + # Dependabot PRs can run it). The dry run follows from the event name. + if keyed: + raise Fail(f"Event '{event}' runs the 'stub' harness only, not '{harness}'.") + if event != "pull_request": + if not self_test: + raise Fail(f"Event '{event}' is for the self-test of {trusted_repo} only.") + elif not self_test: + notice( + "Caller test mode (event 'pull_request', harness 'stub', dry run): the caller's workflow file," + " inputs, rule files and prompt addendum are pull request content here. This run proves the" + " plumbing only, never the reset of the rule files." + ) + pr = env["IN_PR"] or env["EVENT_PR"] + head_sha, base_sha = resolve_pr(source_repo, pr, pr_shas) + actor = env["ACTOR"] + check_writer = False + dry_run = "true" + else: + raise Fail(f"Unexpected event '{event}'.") + # Never comment on a pull request of the caller that merely has the same + # number as the reviewed one. + if source_repo != repo: + dry_run = "true" + + if check_writer: + if not validate.matches(ACTOR, actor): + raise Fail(f"Invalid actor '{actor}'.") + level = permission(repo, actor) + # 'permission' reports the 'maintain' role as 'write', and 'triage' + # as 'read'. + if level not in WRITER_LEVELS: + raise Skip(f"{actor} has '{level}' permission; skipping the agent review.") + notice(f"{actor} has '{level}' permission; running the agent review.") + else: + notice(f"Event '{event}' with harness 'stub': forced dry run, no permission check.") + + if not validate.matches(PR_NUMBER, pr): + raise Fail(f"Invalid pull request number '{pr}'.") + if not validate.matches(SHA, head_sha): + raise Fail(f"Invalid head sha '{head_sha}'.") + if not validate.matches(SHA, base_sha): + raise Fail(f"Invalid base sha '{base_sha}'.") + + keyed_flag = "true" if keyed else "false" + return [ + ("allowed", "true"), + ("keyed", keyed_flag), + ("pr", pr), + ("head_sha", head_sha), + ("base_sha", base_sha), + ("harness", harness), + ("model", model), + ("dry_run", dry_run), + ("project", project), + ("api_base", api_base), + ("source_repo", source_repo), + # Distinguishes this call's artifacts from another call's in the same run. + ("call_id", secrets.token_hex(8)), + ("trusted_repo", trusted_repo), + ("trusted_sha", trusted_sha), + ] + + +def resolve_pr(repo: str, number: str, pr_shas: Callable[[str, str], tuple[str, str]]) -> tuple[str, str]: + """The pull request's (head, base) sha, after checking its number.""" + if not validate.matches(PR_NUMBER, number): + raise Fail(f"Invalid pull request number '{number}'.") + return pr_shas(repo, number) + + +def reviewing(outputs: Sequence[tuple[str, str]]) -> str: + o = dict(outputs) + return ( + f"Reviewing {o['source_repo']}#{o['pr']} at {o['head_sha']} with harness '{o['harness']}'" + f" (keyed {o['keyed']}), model '{o['model']}', dry run '{o['dry_run']}'." + ) + + +# --- I/O ------------------------------------------------------------------------------ + + +def trusted_root() -> str: + """The directory holding bin/, lib/ and api-bases.txt.""" + return os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) + + +def load_api_bases(root: str) -> list[str]: + """The entries of api-bases.txt; none if it cannot be read as UTF-8.""" + try: + text = files.read_text(os.path.join(root, API_BASES_FILE), API_BASES_MAX_BYTES) + except (OSError, UnicodeDecodeError): + return [] + return parse_api_bases(text) + + +def shown(message: str) -> str: + """A message for the log: values may hold '##[' (the legacy command + marker) or a NUL (from gh, shown as '\\x00'); workflow.* escapes '%', CR + and LF.""" + return workflow.neutralise(message.replace("\0", "\\x00")) + + +def write_outputs(path: str, outputs: Sequence[tuple[str, str]]) -> None: + """Appends all outputs at once; a CR or LF in a value raises ValueError.""" + if not path.startswith("/"): + raise ValueError("GITHUB_OUTPUT is not an absolute path") + data = "".join(workflow.output_line(name, value) for name, value in outputs) + files.append_bytes(path, data.encode("utf-8", errors="strict")) + + +def main() -> int: + output = os.environ.get("GITHUB_OUTPUT", "") + if output == "": + workflow.error("GITHUB_OUTPUT is not set.") + return 1 + + def notice(message: str) -> None: + workflow.notice(shown(message)) + + def write_denied() -> bool: + """``allowed=false``; False (with an error) if it cannot be written.""" + try: + write_outputs(output, [("allowed", "false")]) + except (OSError, ValueError) as e: + workflow.error(shown(f"Could not write the outputs: {e}")) + return False + return True + + try: + env = read_environment(os.environb) + root = trusted_root() + outputs = decide(env, lambda: load_api_bases(root), notice) + write_outputs(output, outputs) + except Skip as e: + notice(e.message) + return 0 if write_denied() else 1 + except Fail as e: + write_denied() + workflow.error(shown(f"{e.message} {DOCS}")) + return 1 + except Exception as e: # fail closed on anything unexpected + write_denied() + workflow.error(shown(f"authorize failed: {type(e).__name__}: {e}")) + return 1 + notice(reviewing(outputs)) + return 0 diff --git a/agent-review/lib/agent_review/collect_result.py b/agent-review/lib/agent_review/collect_result.py new file mode 100644 index 0000000..9975d0d --- /dev/null +++ b/agent-review/lib/agent_review/collect_result.py @@ -0,0 +1,195 @@ +"""Copies the review out of the sandbox workspace: ``bin/collect-result``. + +Usage: ``collect-result `` + +Runs on the TAINTED host, after the sandbox. Everything the sandbox could +write is attacker-controlled from here on: ````, the workspace +around it, and the home and ``/tmp`` trees. So this module starts no +process and reads nothing from the environment; it only opens files, and +every open is relative to a directory descriptor, with ``O_NOFOLLOW``: + +- ```` must be an absolute path without ``.``, ``..``, empty + components or a trailing slash, so that the path walked is the path + given. It is opened one component at a time from ``/``, each a + directory and none a symlink, and is then used only through that + descriptor: swapping it or a parent for a symlink afterwards changes + nothing. The walk uses ``O_PATH`` descriptors, which need only search + permission, like an ordinary path lookup (a search-only ``0311`` + workspace still works). +- Only ``review.md`` and ``meta.json`` are copied, each only if it is a + regular file with a single link, at most ``MAX_BYTES``. The type is + checked with ``lstat`` first, so a FIFO or a device found there is not + opened. Whatever is opened (also something swapped in after that check) + is opened non-blocking and checked again with ``fstat`` on the descriptor + (``files.read_bytes``), which also caps the bytes read: a file that grows + while it is read is refused. +- What this does not close: a process that is still running could + hard-link a host file (of at most ``MAX_BYTES``) in as ``review.md`` and + remove the extra link between the open and the ``fstat``, so that + ``st_nlink`` reads 1. No link-count check can prevent that; the + single-link check relies on no sandbox process being alive, which the + workflow's ``Stop the sandbox`` step guarantees (``Collect the result`` + runs only if it succeeded). The path and type races are closed + regardless. +- The content is copied as bytes; the ``publish`` job validates it again + and never trusts this copy. +- ```` (under ``$RUNNER_TEMP``, outside the sandbox's reach) is + created if needed and must not be a symlink itself. Each file is read + completely before anything is written, then written to a new + ``.tmp`` (``O_EXCL``, no symlink followed) and renamed into place; + the temporary file is removed if the rename fails. + +Everything else the agent wrote is ignored. A missing or refused file is a +``::warning`` and exit 0; a wrong argument count, or a destination that +cannot be used, exits 1. +""" + +import contextlib +import errno +import os +import stat +import sys + +from agent_review import files, workflow + +MAX_BYTES = 65536 +EXPECTED = ("review.md", "meta.json") +TITLE = "Agent review result" +USAGE = "Usage: collect-result \n" + +# A directory used only as ``dir_fd`` and for path lookup: needs search +# permission only. With O_DIRECTORY | O_NOFOLLOW a symlink fails (ENOTDIR). +# Not files.open_directory: an O_PATH descriptor cannot list the directory. +_PATH_DIR_FLAGS = os.O_PATH | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC + +# Open errors that mean "not a regular file we may read": absent, a symlink +# (O_NOFOLLOW), a socket. +_NOT_REGULAR = frozenset({errno.ENOENT, errno.ELOOP, errno.ENXIO, errno.ENOTDIR}) + + +def _display(path: str) -> str: + """``path`` as printable UTF-8 (arguments may hold undecodable bytes).""" + return os.fsencode(path).decode("utf-8", errors="backslashreplace") + + +def _warn(message: str) -> None: + workflow.warning(message, title=TITLE) + + +def _say(line: str) -> None: + sys.stdout.buffer.write((line + "\n").encode("utf-8", errors="strict")) + sys.stdout.buffer.flush() + + +def open_path_directory(name: str, *, dir_fd: int | None = None) -> int: + """An ``O_PATH`` descriptor of the directory ``name``, which must not be a symlink.""" + return os.open(name, _PATH_DIR_FLAGS, dir_fd=dir_fd) + + +def open_source(src: str) -> int | None: + """An ``O_PATH`` descriptor of the directory ``src``, or None. + + None if ``src`` is not absolute and canonical, or if it or any parent + is missing, not a directory, or a symlink. + """ + if not src.startswith("/"): + return None + parts = [] if src == "/" else src[1:].split("/") + if any(part in ("", ".", "..") for part in parts): + return None + try: + fd = open_path_directory("/") + except OSError: + return None + try: + for part in parts: + child = open_path_directory(part, dir_fd=fd) + os.close(fd) + fd = child + except OSError: + os.close(fd) + return None + return fd + + +def open_dest(dest: str) -> int: + """Creates ``dest`` if needed; a descriptor of it (not through a symlink).""" + os.makedirs(dest, exist_ok=True) + return files.open_directory(dest) + + +def read_expected(name: str, src_fd: int) -> bytes | None: + """The content of ``name`` in the directory ``src_fd``, or None after a warning.""" + try: + st = os.stat(name, dir_fd=src_fd, follow_symlinks=False) + if not stat.S_ISREG(st.st_mode): + _warn(f"'{name}' is missing or not a regular file; skipped.") + return None + return files.read_bytes(name, MAX_BYTES, dir_fd=src_fd, single_link=True) + except files.UnsafeFileError as e: + if e.reason == "links" and e.st is not None: + # A hard link could expose a host file the agent cannot read itself. + _warn(f"'{name}' has {e.st.st_nlink} hard links; skipped.") + elif e.reason == "size" and e.st is not None: + _warn(f"'{name}' is {e.st.st_size} bytes, over the {MAX_BYTES}-byte limit; skipped.") + elif e.reason == "grew": + _warn(f"'{name}' grew over the {MAX_BYTES}-byte limit while reading; skipped.") + else: + _warn(f"'{name}' is missing or not a regular file; skipped.") + except OSError as e: + if e.errno in _NOT_REGULAR: + _warn(f"'{name}' is missing or not a regular file; skipped.") + else: + _warn(f"'{name}' could not be read ({e.strerror}); skipped.") + return None + + +def write_result(name: str, data: bytes, dest_fd: int) -> None: + """Writes ``data`` to ``name`` in ``dest_fd``, through a new temporary file.""" + tmp = f"{name}.tmp" + with contextlib.suppress(FileNotFoundError): + os.unlink(tmp, dir_fd=dest_fd) + files.write_new(tmp, data, dir_fd=dest_fd) + try: + os.rename(tmp, name, src_dir_fd=dest_fd, dst_dir_fd=dest_fd) + except OSError: + with contextlib.suppress(OSError): + os.unlink(tmp, dir_fd=dest_fd) + raise + + +def collect(src: str, dest: str) -> int: + try: + dest_fd = open_dest(dest) + except OSError as e: + sys.stderr.write(f"collect-result: cannot use '{_display(dest)}' as the destination: {e.strerror}\n") + return 1 + try: + src_fd = open_source(src) + if src_fd is None: + _warn(f"'{_display(src)}' is missing, not a directory, or reached through a symlink; nothing collected.") + return 0 + try: + for name in EXPECTED: + data = read_expected(name, src_fd) + if data is None: + continue + try: + write_result(name, data, dest_fd) + except OSError as e: + sys.stderr.write(f"collect-result: cannot write '{name}' to '{_display(dest)}': {e.strerror}\n") + return 1 + _say(f"Collected '{name}' ({len(data)} bytes).") + finally: + os.close(src_fd) + finally: + os.close(dest_fd) + return 0 + + +def main(argv: list[str] | None = None) -> int: + args = sys.argv[1:] if argv is None else argv + if len(args) != 2: + sys.stderr.write(USAGE) + return 1 + return collect(args[0], args[1]) diff --git a/agent-review/lib/agent_review/files.py b/agent-review/lib/agent_review/files.py new file mode 100644 index 0000000..d2ba4ad --- /dev/null +++ b/agent-review/lib/agent_review/files.py @@ -0,0 +1,109 @@ +"""File access that does not follow symlinks, block on FIFOs or read unbounded. + +Every open uses ``O_NOFOLLOW | O_NONBLOCK | O_NOCTTY | O_CLOEXEC``; the type +and size are then checked with ``fstat`` on the open descriptor (never on +the path, which could be swapped in between), and reads stop at a cap. +``O_NOFOLLOW`` covers the last path component only: where a parent +directory may be hostile, open it with ``open_directory`` and pass its +descriptor as ``dir_fd`` with a single-component name. + +Contents are bytes; ``read_text`` decodes strict UTF-8, never in the +locale's encoding. +""" + +import os +import stat + +_FLAGS = os.O_NOFOLLOW | os.O_NONBLOCK | os.O_NOCTTY | os.O_CLOEXEC + + +class UnsafeFileError(OSError): + """A file is not a regular file, is too large, or has extra links. + + ``reason`` says which check failed, so that callers need not parse the + message: ``"type"`` (not a regular file), ``"links"`` (more than one + hard link), ``"size"`` (``fstat`` size over the cap) or ``"grew"`` (the + read went past the cap); ``"other"`` if the raiser did not say. ``st`` is + the ``fstat`` result of the open file, if there was one. + """ + + def __init__(self, message: str, reason: str = "other", st: os.stat_result | None = None) -> None: + super().__init__(message) + self.reason = reason + self.st = st + + +def open_directory(path: str, *, dir_fd: int | None = None) -> int: + """A descriptor of the directory ``path``, which must not be a symlink.""" + return os.open(path, os.O_RDONLY | os.O_DIRECTORY | _FLAGS, dir_fd=dir_fd) + + +def _check_regular(fd: int, path: str, max_bytes: int, single_link: bool) -> os.stat_result: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + raise UnsafeFileError(f"{path}: not a regular file", "type", st) + if single_link and st.st_nlink != 1: + raise UnsafeFileError(f"{path}: has {st.st_nlink} hard links", "links", st) + if st.st_size > max_bytes: + raise UnsafeFileError(f"{path}: {st.st_size} bytes, more than {max_bytes}", "size", st) + return st + + +def read_bytes(path: str, max_bytes: int, *, dir_fd: int | None = None, single_link: bool = False) -> bytes: + """The contents of the regular file ``path``, at most ``max_bytes``. + + Fails on a symlink, a FIFO, a device or a directory, on a file larger + than the cap (also one that grows while it is read), and with + ``single_link`` on a file with more than one hard link. + """ + if max_bytes < 0: + raise ValueError("max_bytes must not be negative") + fd = os.open(path, os.O_RDONLY | _FLAGS, dir_fd=dir_fd) + try: + st = _check_regular(fd, path, max_bytes, single_link) + chunks = [] + remaining = max_bytes + 1 + while remaining > 0: + chunk = os.read(fd, min(remaining, 1 << 16)) + if not chunk: + break + chunks.append(chunk) + remaining -= len(chunk) + finally: + os.close(fd) + data = b"".join(chunks) + if len(data) > max_bytes: + raise UnsafeFileError(f"{path}: more than {max_bytes} bytes", "grew", st) + return data + + +def read_text(path: str, max_bytes: int, *, dir_fd: int | None = None, single_link: bool = False) -> str: + """``read_bytes`` decoded as strict UTF-8 (UnicodeDecodeError otherwise).""" + return read_bytes(path, max_bytes, dir_fd=dir_fd, single_link=single_link).decode("utf-8", errors="strict") + + +def _write_all(fd: int, data: bytes) -> None: + view = memoryview(data) + while view: + view = view[os.write(fd, view) :] + + +def append_bytes(path: str, data: bytes, *, dir_fd: int | None = None) -> None: + """Appends to the regular file ``path``, creating it (mode 0644) if needed.""" + fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | _FLAGS, 0o644, dir_fd=dir_fd) + try: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + raise UnsafeFileError(f"{path}: not a regular file", "type", st) + _write_all(fd, data) + finally: + os.close(fd) + + +def write_new(path: str, data: bytes, *, mode: int = 0o644, dir_fd: int | None = None) -> None: + """Creates ``path``, which must not exist yet (not even as a symlink).""" + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _FLAGS, mode, dir_fd=dir_fd) + try: + _write_all(fd, data) + finally: + os.close(fd) diff --git a/agent-review/lib/agent_review/gh.py b/agent-review/lib/agent_review/gh.py new file mode 100644 index 0000000..a93fe57 --- /dev/null +++ b/agent-review/lib/agent_review/gh.py @@ -0,0 +1,65 @@ +"""Thin wrapper around ``gh api``, run as a subprocess. + +The only module that runs ``gh``, so the structure test can check that only +``authorize`` and ``publish-comment`` reach it (and with it the job token, +which ``gh`` reads from ``GH_TOKEN``; it never passes through Python). +``gh`` rather than ``urllib``: the token stays out of this process, proxy +variables are not honoured by accident, and the tests' fake ``gh`` on +``PATH`` keeps working. + +Keep the projections in ``gh --jq``: a PR object or a comment body is +untrusted, so it is handled only by gh's JSON decoder and our code never +parses it (invariant 2 in docs/agent-review.md). Python receives only the +projected fields. + +The argument order is fixed: ``gh api [--paginate] [-X METHOD] +[--input -] [--jq FILTER]``: the fake ``gh`` in tests/test-authorize.sh +and tests/test-publish-comment.sh matches on it. +""" + +from agent_review import runner, validate + +METHODS = ("GET", "POST", "PATCH", "PUT", "DELETE") +# A relative API path with an optional query: never an option ('-...'), a +# URL or a host. '[' and ']' only in the path, for bot logins such as +# 'dependabot[bot]', which gh takes as they are. +ENDPOINT = validate.pattern(r"[A-Za-z0-9][A-Za-z0-9._~/%\[\]-]*(?:\?[A-Za-z0-9._~%=&-]*)?") + + +def api( + endpoint: str, + *, + method: str = "GET", + jq: str | None = None, + paginate: bool = False, + body: bytes | None = None, + timeout: float | None = 120, + stderr_is_error: bool = False, +) -> bytes: + """Runs ``gh api`` on the trusted host and returns its stdout. + + ``jq`` must be a constant of the calling code, never data. ``body`` is + sent on stdin (``--input -``). A failure raises runner.CommandError, + whose stderr holds gh's message. With ``stderr_is_error``, output on + stderr is a failure even if gh exits 0, for callers that compare the + answer exactly: a warning on stderr means it may not be what they asked. + """ + validate.require(ENDPOINT, endpoint, "API endpoint") + if method not in METHODS: + raise ValueError(f"unsupported method {method!r}") + if "//" in endpoint or "/../" in f"/{endpoint}/" or "/./" in f"/{endpoint}/": + raise ValueError(f"invalid API endpoint {endpoint!r}") + argv = ["gh", "api"] + if paginate: + argv.append("--paginate") + if method != "GET": + argv += ["-X", method] + argv.append(endpoint) + if body is not None: + argv += ["--input", "-"] + if jq is not None: + argv += ["--jq", jq] + result = runner.run(runner.Zone.TRUSTED_HOST, argv, stdin=body, timeout=timeout) + if stderr_is_error and result.stderr: + raise runner.CommandError("gh", "output on stderr", result.returncode, result.stderr) + return result.stdout diff --git a/agent-review/lib/agent_review/probe.py b/agent-review/lib/agent_review/probe.py new file mode 100644 index 0000000..a0de346 --- /dev/null +++ b/agent-review/lib/agent_review/probe.py @@ -0,0 +1,71 @@ +"""No-op probe of the Python runtime: ``bin/probe``. + +Prints one line, so the self-test can compare the host and the AWF sandbox: + + agent-review-probe python=3.12.3 executable=/usr/bin/python3 isolated=1 ignore_environment=1 + no_user_site=1 no_site=1 dont_write_bytecode=1 safe_path=1 site=0 stdlib_only=1 lib=/lib + +(one line in the output). ``site=0``: neither ``site`` nor +``sitecustomize`` is loaded. ``stdlib_only=1``: ``sys.path`` holds the +trusted ``lib`` and the standard library's own entries only, and ``json`` +and this package were loaded from them. + +It imports the shared modules the entry points build on (``files``, +``runner``, ``validate``, ``workflow``), so the self-test shows that their +standard-library imports (``subprocess``, ``selectors``, ``stat``, ...) +resolve under these flags on both sides. Not ``gh``: only the +``authorize`` and ``publish-comment`` entry points may reach the module +that runs the token-holding program (the structure test's token-reach +check). The stub harness runs it on the host (``install.sh``, in +``prepare``) and in the sandbox (``run.sh``). +""" + +import json +import os +import sys + +import agent_review +from agent_review import files, runner, validate, workflow + +# Imported only to show that they import here (see the module docstring). +MODULES = (files, runner, validate, workflow) +FLAGS = ("isolated", "ignore_environment", "no_user_site", "no_site", "dont_write_bytecode", "safe_path") + + +def lib_dir() -> str: + return os.path.dirname(os.path.dirname(os.path.realpath(agent_review.__file__))) + + +def stdlib_paths() -> list[str]: + major, minor = sys.version_info[:2] + base = os.path.join(sys.base_prefix, "lib") + return [ + os.path.join(base, f"python{major}{minor}.zip"), + os.path.join(base, f"python{major}.{minor}"), + os.path.join(base, f"python{major}.{minor}", "lib-dynload"), + ] + + +def stdlib_only(lib: str) -> bool: + stdlib = stdlib_paths() + origins_ok = os.path.realpath(json.__file__).startswith(stdlib[1] + os.sep) and os.path.realpath( + agent_review.__file__ + ).startswith(lib + os.sep) + return origins_ok and sys.path == [lib, *stdlib] + + +def line() -> str: + lib = lib_dir() + flags = " ".join(f"{name}={int(getattr(sys.flags, name))}" for name in FLAGS) + site = int("site" in sys.modules or "sitecustomize" in sys.modules) + version = "{}.{}.{}".format(*sys.version_info[:3]) + return ( + f"agent-review-probe python={version} executable={sys.executable} {flags}" + f" site={site} stdlib_only={int(stdlib_only(lib))} lib={lib}" + ) + + +def main() -> int: + sys.stdout.buffer.write((line() + "\n").encode("utf-8", errors="strict")) + sys.stdout.buffer.flush() + return 0 diff --git a/agent-review/lib/agent_review/prompt.py b/agent-review/lib/agent_review/prompt.py new file mode 100644 index 0000000..896088d --- /dev/null +++ b/agent-review/lib/agent_review/prompt.py @@ -0,0 +1,154 @@ +"""The review prompt (``run-review``, fetch phase, inside the sandbox). + +The template and the caller's addendum are trusted (``load_config`` +rejects ``{{`` in the addendum). The pull request's title and body are +untrusted data: they come from ``pr.json``, the raw API response, parsed +only here inside the sandbox (invariant 2 is about the host), and land +between delimiters that carry a random nonce the PR cannot know (and which +is removed from them anyway). + +Every placeholder is substituted in ONE pass over the template: a value is +never scanned again, so a placeholder inside any value (a ``{{PR_BODY}}`` +in the title, say) stays as it is, and the prompt is at most the template +plus each value once per placeholder in the template. + +The values are prepared on bytes, and the test suites pin the result: + +- ``substituted`` drops NUL bytes and every trailing newline, so a value + never adds blank lines before the text that follows its placeholder; +- ``clip`` caps a value in bytes, then drops invalid or cut multi-byte + sequences, so the prompt is valid UTF-8; +- ``jq_text`` turns a JSON value into text: null and false become empty, + strings are themselves, other values their compact JSON. A newline is + added after the value before the cap, and counts towards it. +""" + +import json +import re +import secrets +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +from agent_review import files +from agent_review.reset import CONTEXT_NAME +from agent_review.review_errors import Fatal + +PR_TITLE_MAX_BYTES = 512 +PR_BODY_MAX_BYTES = 16384 +ADDENDUM_PROMPT_MAX_BYTES = 8192 +# pr.json is the API response for one pull request; GitHub caps the body +# at 65536 characters, so this cap is far above any real response. +PR_JSON_MAX_BYTES = 8 << 20 +_SURROGATE = re.compile("[\ud800-\udfff]") +PLACEHOLDER = re.compile(rb"\{\{([A-Z_]+)\}\}", re.ASCII) + + +def substituted(data: bytes) -> bytes: + """``data`` without NUL bytes and trailing newlines.""" + return data.replace(b"\0", b"").rstrip(b"\n") + + +def clip(data: bytes, max_bytes: int) -> bytes: + """The first ``max_bytes`` bytes, without invalid or cut UTF-8 sequences.""" + return data[:max_bytes].decode("utf-8", errors="ignore").encode("utf-8") + + +def jq_text(value: Any) -> str: + """A parsed JSON value as text: empty for null and false, a string as is, else compact JSON.""" + if value is None or value is False: + return "" + if isinstance(value, str): + return value + return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=True) + + +def _utf8(text: str) -> bytes: + # A lone surrogate escape ('\ud800') parses in Python but cannot be + # encoded. Replace it, as decoders do: the review goes on. + return _SURROGATE.sub("\ufffd", text).encode("utf-8") + + +def title_bytes(title: str) -> bytes: + """The title's first line, without CR, clipped to PR_TITLE_MAX_BYTES (one line for the prompt).""" + data = (_utf8(title) + b"\n").replace(b"\r", b"") + first_line = data[: data.index(b"\n") + 1] + return substituted(clip(first_line, PR_TITLE_MAX_BYTES)) + + +def body_bytes(body: str) -> bytes: + """The body without CR, clipped to PR_BODY_MAX_BYTES.""" + data = (_utf8(body) + b"\n").replace(b"\r", b"") + return substituted(clip(data, PR_BODY_MAX_BYTES)) + + +def read_pr(path: str) -> tuple[bytes, bytes]: + """The PR's title and body from the raw API response, as prompt bytes.""" + try: + data = files.read_bytes(path, PR_JSON_MAX_BYTES) + # Invalid UTF-8 becomes U+FFFD: the title and body are data for the + # prompt, and an odd byte must not stop the review. + pr = json.loads(data.decode("utf-8", errors="replace")) + except (OSError, ValueError, RecursionError) as e: + raise Fatal(f"Cannot read the pull request from '{path}': {e}") from e + if not isinstance(pr, dict): + raise Fatal(f"'{path}' does not hold a JSON object.") + return title_bytes(jq_text(pr.get("title"))), body_bytes(jq_text(pr.get("body"))) + + +def rules_bytes(rule_files: Sequence[str]) -> bytes: + if not rule_files: + return b"No project rule files are configured." + lines = (f"{i}. `{f}`, if it exists." for i, f in enumerate(rule_files, start=1)) + return substituted("\n".join(lines).encode("utf-8")) + + +def addendum_bytes(addendum: bytes) -> bytes: + """'### Project notes', a blank line and the clipped addendum; empty without an addendum.""" + if not addendum: + return b"" + inner = substituted(clip(addendum, ADDENDUM_PROMPT_MAX_BYTES)) + return substituted(b"### Project notes\n\n" + inner + b"\n") + + +def new_nonce() -> str: + return secrets.token_hex(12) + + +@dataclass(frozen=True) +class PromptValues: + project: str + repo: str + pr_number: str + head_sha: str + base_sha: str + merge_base: str + rules: bytes + addendum: bytes + title: bytes + body: bytes + + +def render(template: bytes, values: PromptValues, nonce: str) -> bytes: + """The prompt file's contents (with its final newline).""" + marker = nonce.encode("ascii") + # The PR cannot know the nonce, but strip it anyway so the delimiters stay unique. + title = values.title.replace(marker, b"") + body = values.body.replace(marker, b"") + replacements = { + b"ADDENDUM": values.addendum, + b"RULES": values.rules, + b"PROJECT": values.project.encode("utf-8"), + b"REPO": values.repo.encode("utf-8"), + b"PR_NUMBER": values.pr_number.encode("utf-8"), + b"HEAD_SHA": values.head_sha.encode("utf-8"), + b"BASE_SHA": values.base_sha.encode("utf-8"), + b"MERGE_BASE": values.merge_base.encode("utf-8"), + b"CONTEXT_DIR": CONTEXT_NAME.encode("utf-8"), + b"NONCE": marker, + b"PR_TITLE": title, + b"PR_BODY": body, + } + # One pass: values are never scanned again (a placeholder in them stays). + prompt = PLACEHOLDER.sub(lambda m: replacements.get(m.group(1), m.group(0)), substituted(template)) + return prompt + b"\n" diff --git a/agent-review/lib/agent_review/publish_comment.py b/agent-review/lib/agent_review/publish_comment.py new file mode 100644 index 0000000..24065fd --- /dev/null +++ b/agent-review/lib/agent_review/publish_comment.py @@ -0,0 +1,291 @@ +"""``bin/publish-comment``: validates the agent's review and upserts it as a PR comment. + +Usage:: + + publish-comment sanitize < review > safe-review + publish-comment render --harness H --version V --model M --head-sha SHA --run-url U --review FILE + publish-comment post --repo R --pr N --harness H --body-file FILE + +Runs in the ``publish`` job: a fresh VM with a write-capable token, no model +and no PR code. The review is hostile text (agent_review.sanitize). +``sanitize`` and ``render`` read only stdin and files and write stdout; the +workflow runs ``render`` in a step without a token. Only ``post`` runs +``gh`` (agent_review.gh), with the token of its step. + +Exit codes: 0 on success; 3 if the review is not valid UTF-8, is empty, or +its file is not a regular file (a symlink, a FIFO, ...) within the size cap +(the workflow then posts nothing and warns); 1 on any other error, +including a missing review file (the workflow checks for it first). + +The comment is found by a marker on its first line, among this workflow's +own comments only (``BOT_LOGIN``), never with ``gh pr comment --edit-last``: +other tools (PR Agent) post as the same bot. The comment listing is a +``gh --jq`` projection (id, login, and the first 256 characters of the +body's first line, as TSV), so this host never parses a comment body +(invariant 2); only the first line is compared, as bytes, with the marker. +""" + +import json +import os +import sys +from collections.abc import Sequence + +from agent_review import files, gh, runner, sanitize, validate, workflow + +# GitHub rejects comment bodies over 65536 characters. +BODY_MAX_BYTES = 65536 +# The review read by 'sanitize' and 'render': far above the review job's +# 64 KiB cap on review.md, only so that a broken input cannot exhaust memory. +INPUT_MAX_BYTES = 16 * 1024 * 1024 +DEFAULT_BOT_LOGIN = "github-actions[bot]" +EXIT_INVALID = 3 + +# The harness, version and model in the comment's header. +LABEL = validate.pattern(r"[A-Za-z0-9][A-Za-z0-9._:/+-]{0,127}") +RUN_URL = validate.pattern(r"https://github\.com/[A-Za-z0-9_./-]+") +COMMENT_ID = validate.pattern(r"[1-9][0-9]{0,19}") +# The projection of the comment listing; a constant, never data. Only the +# first FIRST_LINE_CHARS characters of each first line, so that a long +# comment adds at most about 1 KB to the listing (300 comments with 60 KB +# first lines would otherwise pass runner's output cap). Many thousands of +# comments still can, or hit the time limit: 'post' then fails. Longer +# than any marker (at most 150 characters), so the comparison stays exact. +FIRST_LINE_CHARS = 256 +LISTING_JQ = f'.[] | [.id, .user.login, (.body | split("\\n") | .[0] | .[0:{FIRST_LINE_CHARS}])] | @tsv' +ASCII_WHITESPACE = " \t\n\v\f\r" + +RENDER_OPTIONS = ("--harness", "--version", "--model", "--head-sha", "--run-url", "--review") +POST_OPTIONS = ("--repo", "--pr", "--harness", "--body-file") + + +class Failure(Exception): + """An error that ends the command with a message and an exit code.""" + + def __init__(self, message: str, code: int = 1) -> None: + super().__init__(message) + self.code = code + + +def _stderr_line(message: str) -> None: + # One line that cannot start or contain a workflow command: it starts + # with 'publish-comment: ', has no line break, and no '##['. + text = message.replace("\r", "\\r").replace("\n", "\\n") + sys.stderr.buffer.write(workflow.neutralise(f"publish-comment: {text}\n").encode("utf-8", errors="replace")) + sys.stderr.buffer.flush() + + +def marker(harness: str) -> str: + return f"" + + +def parse_options(args: Sequence[str], known: Sequence[str]) -> dict[str, str]: + """``--name value`` pairs; the last one wins, and a missing option is empty.""" + values = dict.fromkeys(known, "") + rest = list(args) + while rest: + name = rest.pop(0) + if name not in known: + raise Failure(f"Unknown option '{name}'.") + if not rest: + raise Failure(f"Option '{name}' needs a value.") + values[name] = rest.pop(0) + return values + + +def check_label(what: str, value: str) -> str: + if not validate.matches(LABEL, value): + raise Failure(f"Invalid {what} '{value}'.") + return value + + +def sanitize_review(data: bytes) -> tuple[bytes, bool]: + """(the sanitised review, whether the cap cut it), or Failure(code 3) if it is not valid UTF-8.""" + try: + return sanitize.sanitize_and_report(data) + except sanitize.InvalidReviewError as e: + raise Failure(str(e), EXIT_INVALID) from e + + +def cmd_sanitize() -> bytes: + data = sys.stdin.buffer.read(INPUT_MAX_BYTES + 1) + if len(data) > INPUT_MAX_BYTES: + raise Failure(f"The review exceeds {INPUT_MAX_BYTES} bytes.", EXIT_INVALID) + return sanitize_review(data)[0] + + +def render(*, harness: str, version: str, model: str, head_sha: str, run_url: str, review: bytes) -> bytes: + """The comment body for ``review`` (raw bytes), as UTF-8.""" + # Trailing newlines dropped: the comment's layout adds its own. + safe_bytes, cut = sanitize_review(review) + safe = safe_bytes.rstrip(b"\n").decode("utf-8", errors="strict") + if not safe.strip(ASCII_WHITESPACE): + raise Failure("the review is empty.", EXIT_INVALID) + lines = [ + marker(harness), + "> [!NOTE]", + f"> Advisory review by **{harness}** {version} (`{model}`) of commit {head_sha}, produced in a sandbox. " + "Later pushes are not reviewed. Not a required check: it may be wrong, and the content of the pull request " + f"can steer it. [Workflow run]({run_url}).", + "", + safe, + ] + body = "\n".join(lines) + "\n" + # Noted if and only if the cap cut the sanitised text (also when escaping + # made it grow past the cap; not when only dropped characters made the + # input larger than the cap). + if cut: + body += f"\n_[Truncated to {sanitize.REVIEW_MAX_BYTES} bytes.]_\n" + return body.encode("utf-8", errors="strict") + + +def cmd_render(args: Sequence[str]) -> bytes: + o = parse_options(args, RENDER_OPTIONS) + # These come from the workflow's trusted job outputs, never from the + # sandbox; validated because they are interpolated into Markdown. + harness = check_label("harness", o["--harness"]) + version = check_label("version", o["--version"]) + model = check_label("model", o["--model"]) + if not validate.matches(validate.SHA, o["--head-sha"]): + raise Failure(f"Invalid head sha '{o['--head-sha']}'.") + if not validate.matches(RUN_URL, o["--run-url"]): + raise Failure(f"Invalid run URL '{o['--run-url']}'.") + path = o["--review"] + try: + review = files.read_bytes(path, INPUT_MAX_BYTES) if path else None + except FileNotFoundError: + review = None + except OSError as e: + # A symlink, a FIFO, a directory or a file over the cap: an invalid + # result (a warning), not an error (a red run); the check is advisory. + raise Failure(f"Unusable review file '{path}': {e}", EXIT_INVALID) from e + if review is None: + raise Failure(f"No review file '{path}'.") + return render( + harness=harness, version=version, model=model, head_sha=o["--head-sha"], run_url=o["--run-url"], review=review + ) + + +def find_comment(listing: bytes, login: str, want: str) -> str | None: + """The id of the first comment by ``login`` whose first line is ``want``. + + ``listing``: lines of 'id TAB login TAB first line' (jq's @tsv, which + escapes tabs and line breaks inside fields), compared as bytes. + """ + login_b, want_b = login.encode("utf-8"), want.encode("utf-8") + for line in listing.split(b"\n"): + fields = line.split(b"\t") + if len(fields) == 3 and fields[1] == login_b and fields[2] == want_b: + cid = fields[0].decode("ascii", errors="replace") + if not validate.matches(COMMENT_ID, cid): + raise Failure(f"Invalid comment id '{cid}' in the listing.") + return cid + return None + + +def _gh( + what: str, endpoint: str, *, method: str = "GET", jq: str, paginate: bool = False, body: bytes | None = None +) -> bytes: + """``gh.api``; a failure becomes Failure(``what``), with gh's message in the log.""" + try: + return gh.api(endpoint, method=method, jq=jq, paginate=paginate, body=body) + except runner.CommandError as e: + if e.stderr: + # gh's own messages, which may quote API responses: prefixed and + # with '##[' broken up, like any untrusted log text. + workflow.log_lines(e.stderr.decode("utf-8", errors="replace"), "gh| ", stream=sys.stderr.buffer) + raise Failure(f"{what} ({e}).") from e + except ValueError as e: + raise Failure(f"{what} ({e}).") from e + + +def cmd_post(args: Sequence[str]) -> bytes: + o = parse_options(args, POST_OPTIONS) + repo, pr = o["--repo"], o["--pr"] + if not validate.matches(validate.REPO, repo): + raise Failure(f"Invalid repo '{repo}'.") + if not validate.matches(validate.POSITIVE_INT, pr): + raise Failure(f"Invalid PR number '{pr}'.") + harness = check_label("harness", o["--harness"]) + path = o["--body-file"] + try: + body_bytes = files.read_bytes(path, BODY_MAX_BYTES) if path else None + except FileNotFoundError: + body_bytes = None + except files.UnsafeFileError as e: + raise Failure(f"The comment body exceeds {BODY_MAX_BYTES} bytes or is not a regular file ({e}).") from e + except OSError as e: + raise Failure(f"Cannot read the body file '{path}': {e}") from e + if body_bytes is None: + raise Failure(f"No body file '{path}'.") + want = marker(harness) + if len(want) >= FIRST_LINE_CHARS: + raise Failure(f"The marker is not shorter than the {FIRST_LINE_CHARS} characters the listing keeps.") + if body_bytes.split(b"\n", 1)[0] != want.encode("utf-8"): + raise Failure("The body does not start with the marker.") + try: + body = body_bytes.decode("utf-8", errors="strict") + except UnicodeDecodeError as e: + raise Failure("The comment body is not valid UTF-8.") from e + + # A failed listing stops here, so it can never post a second comment. + listing = _gh( + f"Could not list the comments of #{pr}", + f"repos/{repo}/issues/{pr}/comments?per_page=100", + paginate=True, + jq=LISTING_JQ, + ) + # BOT_LOGIN is a test hook (the suite's fake listing uses another bot), + # read in the step that holds the write token. That is safe: the + # 'Publish the review' step's env: in agent-review.yml is fixed and does + # not set it, and a called workflow does not inherit the caller's env:, + # so neither a caller nor a pull request can choose which comments + # count as ours. + cid = find_comment(listing, os.environ.get("BOT_LOGIN") or DEFAULT_BOT_LOGIN, want) + # Our own body, encoded as compact JSON (never parsing anything). + payload = (json.dumps({"body": body}, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8") + if cid is not None: + url = _gh( + f"Could not update comment {cid}", + f"repos/{repo}/issues/comments/{cid}", + method="PATCH", + body=payload, + jq=".html_url", + ) + else: + url = _gh( + "Could not post the comment", + f"repos/{repo}/issues/{pr}/comments", + method="POST", + body=payload, + jq=".html_url", + ) + # The workflow writes it to GITHUB_OUTPUT: exactly one line. + text = url.decode("utf-8", errors="replace").removesuffix("\n") + if not text or "\n" in text or "\r" in text: + raise Failure("gh returned no single-line comment URL.") + return (text + "\n").encode("utf-8") + + +def run(argv: Sequence[str]) -> bytes: + if not argv: + raise Failure("Usage: publish-comment sanitize|render|post [options]") + command, args = argv[0], argv[1:] + if command == "sanitize": + # Extra arguments are ignored (part of the CLI contract). + return cmd_sanitize() + if command == "render": + return cmd_render(args) + if command == "post": + return cmd_post(args) + raise Failure(f"Unknown command '{command}'.") + + +def main(argv: Sequence[str] | None = None) -> int: + try: + out = run(sys.argv[1:] if argv is None else argv) + except Failure as e: + _stderr_line(str(e)) + return e.code + sys.stdout.buffer.write(out) + sys.stdout.buffer.flush() + return 0 diff --git a/agent-review/lib/agent_review/reset.py b/agent-review/lib/agent_review/reset.py new file mode 100644 index 0000000..ada3ee6 --- /dev/null +++ b/agent-review/lib/agent_review/reset.py @@ -0,0 +1,654 @@ +"""Caller configuration, the instruction-file reset and its post-condition. + +Part of ``run-review``, inside the sandbox. A pull request must not rewrite +the rules it is reviewed by, so before the harness runs every file in the +PR tree that matches a reset pattern is removed, and the ones that exist at +the base commit are restored (the PR's own versions stay as data). + +**One glob engine.** Whether a pattern matches a path is always decided by +git, through the pathspec ``:(glob,icase)**/`` (``**`` appended +for a directory pattern ending in ``/``): in the reset, and in the +pre-fetch check that a reset pattern covers every file the prompt addendum +names. Nothing here matches globs in Python: a second matcher would +disagree with git somewhere (a shell glob's ``*`` crosses ``/``, git's +does not), and a pattern could then look like it covered a file that the +reset misses. + +**Scratch index.** ``git ls-files`` matches pathspecs against an index, and +the coverage check runs before anything is fetched. ``Coverage`` therefore +creates a scratch bare repository in a temporary directory in the workspace +(the only place the sandbox may write) and, for each named path, an index +(``GIT_INDEX_FILE``) holding only that path, pointing at the empty blob, +which need not exist; one index per path, so that two named paths cannot +conflict as file and directory. The directory is removed afterwards. + +**Post-conditions.** Whatever the matching does, after the reset every +file the prompt tells the agent to follow (each rule file, and each file +the addendum names, as a path from the repository root) must be its base +version, or absent in both the base and the checkout, and no leading +directory may be a symlink (``verify_followed_files``); and no symlink or +gitlink may leave files the reset does not cover reachable +(``verify_no_linked_directories``). +""" + +import os +import re +import shutil +import stat +import tempfile +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass + +from agent_review import files, runner +from agent_review.review_errors import Fatal +from agent_review.sandbox_git import Git + +# Caps on the trusted configuration files, so a broken one cannot exhaust memory. +LIST_MAX_BYTES = 1 << 20 +ADDENDUM_MAX_BYTES = 1 << 20 +TEMPLATE_MAX_BYTES = 1 << 20 +# The whitespace trimmed from each list line: ASCII only, the lists are bytes. +ASCII_SPACE = b" \t\n\v\f\r" +# A file the addendum names: a path in backticks, without whitespace, with one of these extensions. +NAMED_FILE = re.compile(rb"`[^`\s]+\.(?:md|mdc|txt|toml|ya?ml|json|jsonc)`", re.ASCII) +EMPTY_BLOB = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391" +CONTEXT_NAME = ".agent-review-context" + + +def _decode(data: bytes, where: str) -> str: + try: + return data.decode("utf-8", errors="strict") + except UnicodeDecodeError as e: + raise Fatal(f"'{where}' is not valid UTF-8.") from e + + +def read_config_file(path: str, max_bytes: int) -> bytes: + try: + data = files.read_bytes(path, max_bytes) + except OSError as e: + raise Fatal(f"Cannot read '{path}': {e}") from e + if b"\0" in data: + raise Fatal(f"'{path}' contains a NUL byte.") + return data + + +def read_list(path: str) -> list[str]: + """Non-comment, trimmed lines of ``path``; none if it is not a file.""" + if not os.path.isfile(path): + return [] + return _list_entries(path) + + +def read_central_list(path: str) -> list[str]: + """The central reset patterns: the file must exist and hold at least one pattern. + + Unlike the caller's optional lists, a missing or empty central list is + a defect of the trusted tree, and treating it as "nothing configured" + would leave every harness's instruction files unreset (fail open). + """ + entries = _list_entries(path) + if not entries: + raise Fatal(f"'{path}' holds no reset pattern.") + return entries + + +def _list_entries(path: str) -> list[str]: + entries = [] + for raw in read_config_file(path, LIST_MAX_BYTES).split(b"\n"): + line = raw.strip(ASCII_SPACE) + if line and not line.startswith(b"#"): + entries.append(_decode(line, path)) + return entries + + +def check_entry(entry: str) -> None: + if entry.startswith(("/", ":")) or ".." in entry: + raise Fatal(f"Invalid configured path or pattern: '{entry}'.") + + +def is_tree_path(path: str) -> bool: + """Whether ``path`` has no '.', '..' or empty component: git never writes such a path.""" + wrapped = f"/{path}/" + return not ("/../" in wrapped or "/./" in wrapped or "//" in wrapped) + + +def is_plain_path(path: str) -> bool: + """A path from the repository root without glob characters.""" + return is_tree_path(path) and not any(c in path for c in "*?[") + + +def pathspecs(patterns: Iterable[str]) -> list[str]: + """The git pathspec of each pattern; every pattern applies at any depth, case-insensitively.""" + return [f":(glob,icase)**/{p}**" if p.endswith("/") else f":(glob,icase)**/{p}" for p in patterns if p] + + +@dataclass(frozen=True) +class Config: + """The caller configuration, from ``/config`` and ``/instruction-files.txt``.""" + + rule_files: tuple[str, ...] + reset_patterns: tuple[str, ...] + addendum: bytes # empty when not configured; valid UTF-8 + addendum_named: tuple[str, ...] # sorted bytewise, unique + template: bytes = b"" # the prompt template; valid UTF-8 + + +def load_config(root: str) -> Config: + """Reads and checks the caller configuration (coverage is checked by ``check_coverage``).""" + config_dir = os.path.join(root, "config") + rule_files = read_list(os.path.join(config_dir, "rule-files.txt")) + for entry in rule_files: + check_entry(entry) + # The central list (every harness's files), the caller's extra patterns, + # and every rule file the prompt tells the agent to follow. + patterns = [ + *read_central_list(os.path.join(root, "instruction-files.txt")), + *read_list(os.path.join(config_dir, "extra-instruction-files.txt")), + *rule_files, + ] + for entry in patterns: + check_entry(entry) + addendum = b"" + named: list[str] = [] + addendum_path = os.path.join(config_dir, "prompt-addendum.md") + if os.path.isfile(addendum_path) and os.path.getsize(addendum_path) > 0: + addendum = read_config_file(addendum_path, ADDENDUM_MAX_BYTES) + # The prompt is rendered in one pass, so a placeholder here is never + # expanded; refusing it is defence in depth (expanded, '{{PR_BODY}}' + # would put untrusted text outside its delimiters) and tells the + # caller early. The check runs on strictly decoded text: invalid + # bytes between two braces ('{\xff{') are dropped when the addendum + # is clipped into the prompt, and would form '{{' there. + text = _decode(addendum, addendum_path) + if "{{" in text: + raise Fatal("The prompt addendum contains '{{'; placeholders are not allowed there.") + found = sorted({m.group()[1:-1] for m in NAMED_FILE.finditer(addendum)}) + named = [_decode(n, addendum_path) for n in found] + template_path = os.path.join(root, "prompt.md.tmpl") + template = read_config_file(template_path, TEMPLATE_MAX_BYTES) + _decode(template, template_path) + return Config(tuple(rule_files), tuple(patterns), addendum, tuple(named), template) + + +class Coverage: + """Which paths some pathspec matches, decided by git on a scratch index (see the module docstring).""" + + def __init__(self, parent_dir: str, env: Mapping[str, str], patterns: Sequence[str]) -> None: + self.specs = pathspecs(patterns) + self.dir = tempfile.mkdtemp(prefix=".agent-review-coverage.", dir=parent_dir) + self.index = os.path.join(self.dir, "index") + repo = os.path.join(self.dir, "repo") + os.mkdir(repo) + self.git = Git(repo, env) + self.git.run("init", "-q", "--bare", "--template=") + + def __enter__(self) -> "Coverage": + return self + + def __exit__(self, *exc: object) -> None: + shutil.rmtree(self.dir, ignore_errors=True) + + def matching(self, paths: Sequence[str], specs: Sequence[str]) -> list[str]: + """The ``paths`` that some pathspec in ``specs`` matches. + + The paths must not conflict as file and directory. A path git + refuses to index ('Ignoring path') would silently drop out, so the + index is checked to hold every path: otherwise CommandError. + """ + if not specs or not paths: + return [] + if os.path.lexists(self.index): + os.unlink(self.index) + index = {"GIT_INDEX_FILE": self.index} + entries = b"".join(b"100644 " + EMPTY_BLOB.encode() + b"\t" + os.fsencode(p) + b"\0" for p in paths) + self.git.run("update-index", "-z", "--add", "--index-info", env=index, stdin=entries) + indexed = set(self.git.output("ls-files", "-z", env=index).split(b"\0")) - {b""} + if indexed != {os.fsencode(p) for p in paths}: + raise runner.CommandError("git", "the scratch index does not hold every path") + listed = set(self.git.output("ls-files", "-z", "--", *specs, env=index).split(b"\0")) + return [p for p in paths if os.fsencode(p) in listed] + + def covers(self, path: str) -> bool: + """Whether some reset pattern matches ``path`` (False for a path git refuses).""" + try: + return bool(self.matching([path], self.specs)) + except runner.CommandError: + return False + + +def check_coverage(config: Config, scratch_parent: str, env: Mapping[str, str]) -> None: + """Fails closed unless each file the addendum names is a plain path that a reset pattern covers. + + Otherwise a PR could rewrite such a file and have the agent follow its + version. The post-condition after the reset checks the result again. + """ + if not config.addendum_named: + return + with Coverage(scratch_parent, env, config.reset_patterns) as coverage: + for named in config.addendum_named: + # A path from the repository root, which the post-condition can check. + if not is_plain_path(named): + raise Fatal(f"The prompt addendum names '{named}', which is not a plain repository path.") + if not coverage.covers(named): + raise Fatal( + f"The prompt addendum names '{named}', which no reset pattern covers; add it to rule_files." + ) + + +def _paths(listing: bytes) -> list[str]: + """NUL-separated git paths; non-UTF-8 bytes survive as surrogate escapes.""" + return [os.fsdecode(p) for p in listing.split(b"\0") if p] + + +def _write_from_git(git: Git, dest: str, *args: str) -> None: + fd = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o644) + try: + git.run(*args, stdout_fd=fd) + finally: + os.close(fd) + + +LINK_MODES = ("120000", "160000") # symlink, gitlink (submodule) + + +def container_specs(patterns: Iterable[str]) -> list[str]: + """Pathspecs of the directories the patterns go through, at any depth, case-insensitively. + + A directory pattern ``D/`` names ``D`` itself; a pattern with ``/`` + names each leading part (``a/b/c.md``: ``a`` and ``a/b``). The reset's + ``:(glob)`` pathspecs match only the entries below such a directory, + never the entry itself, so a PR that put a symlink (or a gitlink) there + kept its own files reachable through it. + """ + parts: list[str] = [] + for pattern in patterns: + if not pattern: + continue + segments = pattern.rstrip("/").split("/") + leading = ["/".join(segments[:i]) for i in range(1, len(segments))] + if pattern.endswith("/"): + leading.append("/".join(segments)) + parts.extend(part for part in leading if part and part not in parts) + return [f":(glob,icase)**/{part}" for part in parts] + + +def _entries(listing: bytes) -> list[tuple[str, str]]: + """(mode, path) of each 'ls-files -s -z' record.""" + entries = [] + for record in listing.split(b"\0"): + if record: + meta, _, path = record.partition(b"\t") + entries.append((meta.split(b" ", 1)[0].decode("ascii", errors="replace"), os.fsdecode(path))) + return entries + + +def _reset_entries( + git: Git, specs: Sequence[str], containers: Sequence[str], env: Mapping[str, str] | None = None +) -> list[tuple[str, str]]: + """The entries to reset: those the patterns match, and symlinks and gitlinks where a directory of one is.""" + entries = _entries(git.output("ls-files", "-s", "-z", "--", *specs, env=env)) + if containers: + links = _entries(git.output("ls-files", "-s", "-z", "--", *containers, env=env)) + entries += [entry for entry in links if entry[0] in LINK_MODES and entry not in entries] + return entries + + +def reset_instruction_files( + git: Git, ws: str, *, head_sha: str, base_sha: str, patterns: Sequence[str], context_dir: str +) -> None: + """Resets every file matching a pattern to its base version; keeps the PR's changed versions as data. + + Also resets each symlink or gitlink where a pattern expects a directory + (``container_specs``): it becomes the base entry, or is removed if the + base has none; the files below are then those of the base, never the + PR's. Runs after the checkout of the head, so the index holds the head + tree (without the context directory); the base tree goes into a scratch + index. ``ls-files``, not ``ls-tree``, which rejects the ``:(glob)`` + magic. + """ + specs = pathspecs(patterns) + if not specs: + raise Fatal("No reset patterns.") + containers = container_specs(patterns) + pr_entries = _reset_entries(git, specs, containers) + base_index = os.path.join(ws, "base.index") + index = {"GIT_INDEX_FILE": base_index} + try: + git.run("read-tree", base_sha, env=index) + base_paths = [path for _, path in _reset_entries(git, specs, containers, env=index)] + finally: + if os.path.lexists(base_index): + os.unlink(base_index) + + pr_paths = [path for _, path in pr_entries] + for mode, path in pr_entries: + # Git refuses such paths in trees, but they become filesystem paths here. + if not is_tree_path(path): + raise Fatal(f"Unexpected path in PR tree: '{path}'.") + # Only what the PR adds or changes is kept, so the review can comment + # on it; a gitlink has no content here (submodules are not fetched). + head_id = git.line("rev-parse", f"{head_sha}:{path}") + if head_id is None: + raise Fatal(f"Cannot resolve '{path}' in the head commit.") + base_id = git.line("rev-parse", "-q", "--verify", f"{base_sha}:{path}") or "" + if head_id == base_id or mode == "160000": + continue + dest = os.path.join(context_dir, "pr-instruction-files", f"{path}.txt") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _write_from_git(git, dest, "cat-file", "-p", f"{head_sha}:{path}") + if pr_paths: + # Git removes paths without following symlinks in leading components. + git.run("--literal-pathspecs", "rm", "-r", "-q", "-f", "--ignore-unmatch", "--", *pr_paths) + if base_paths: + git.run("--literal-pathspecs", "checkout", "-q", base_sha, "--", *base_paths) + + +def _linked_paths(git: Git, repo_dir: str) -> list[str]: + """Every symlink in the checkout (found with lstat, never followed) and every gitlink in the index.""" + + def fail(error: OSError) -> None: + raise Fatal(f"Cannot list the checkout: {error}") + + found = [] + for directory, dirs, names in os.walk(repo_dir, onerror=fail, followlinks=False): + if directory == repo_dir and ".git" in dirs: + dirs.remove(".git") + for name in (*dirs, *names): + path = os.path.join(directory, name) + if os.path.islink(path): + found.append(os.path.relpath(path, repo_dir)) + gitlinks = [path for mode, path in _entries(git.output("ls-files", "-s", "-z")) if mode == "160000"] + return sorted(set(found) | set(gitlinks)) + + +MAX_LINK_HOPS = 8 + + +class _LinkRefused(Exception): + """A symlink fails the base-link exception; the message says why.""" + + +def _base_link_hop(git: Git, repo_dir: str, base_sha: str, path: str) -> list[str]: + """The components of the path the base symlink ``path`` points at, lexically; raises _LinkRefused. + + Safe: a symlink in the checkout with exactly its base target (so the + PR did not make or change it), relative, climbing only through leading + ``..``, and staying inside the repository. ``.`` parts and one trailing + ``/`` are dropped ('./CLAUDE.md', '../.agents/skills/'); an empty part + elsewhere ('a//b') is refused. The caller passes a ``path`` whose + leading directories are real ones, so the climb is exact. + """ + full = os.path.join(repo_dir, path) + entry = _parse_ls_tree(git.output("ls-tree", "-z", "--full-tree", base_sha, "--", path)) + if entry is None or entry[:2] != ("120000", "blob") or entry[3] != path: + raise _LinkRefused("it is not a symlink of the base commit") + target = os.readlink(os.fsencode(full)) + if target != git.output("cat-file", "blob", entry[2]): + raise _LinkRefused("its target is not the base commit's") + if target.startswith(b"/"): + raise _LinkRefused("its target is absolute") + parts = os.fsdecode(target).split("/") + if len(parts) > 1 and parts[-1] == "": + parts.pop() # one trailing '/' + parts = [part for part in parts if part != "."] + if any(part == "" for part in parts): + raise _LinkRefused("its target has an empty part ('//')") + climb = 0 + while climb < len(parts) and parts[climb] == "..": + climb += 1 + rest = parts[climb:] + parent = path.split("/")[:-1] + if ".." in rest: + raise _LinkRefused("its target has '..' after the start") + if climb > len(parent): + raise _LinkRefused("its target leads outside the repository") + if not rest: + raise _LinkRefused("its target is one of its own parent directories") + return [*parent[: len(parent) - climb], *rest] + + +def _is_base_gitlink(git: Git, repo_dir: str, base_sha: str, path: str) -> bool: + """Whether the gitlink ``path`` is the base commit's own, with nothing checked out there. + + Such a submodule is harmless: submodules are never fetched + (``submodule.recurse=false``), so its directory is empty. A PR's added + or changed gitlink is replaced by the reset itself; if the reset left + one, its commit would differ from the base's, and this check fails. + """ + base = _parse_ls_tree(git.output("ls-tree", "-z", "--full-tree", base_sha, "--", path)) + if base is None or base[:2] != ("160000", "commit") or base[3] != path: + return False + records = [r for r in git.output("ls-files", "-s", "-z", "--", f":(literal){path}").split(b"\0") if r] + if len(records) != 1: + return False + meta, _, name = records[0].partition(b"\t") + fields = meta.decode("ascii", errors="replace").split(" ") + if os.fsdecode(name) != path or len(fields) != 3 or fields[0] != "160000" or fields[1] != base[2]: + return False + full = os.path.join(repo_dir, path) + try: + return stat.S_ISDIR(os.lstat(full).st_mode) and not os.listdir(full) + except OSError: + return False + + +def _resolve_base_link(git: Git, repo_dir: str, base_sha: str, path: str, seen: list[str]) -> str: + """The real repository path the base symlink ``path`` leads to; raises _LinkRefused. + + Every symlink on the way (the target, or a directory leading to it) must + pass ``_base_link_hop`` too; at most MAX_LINK_HOPS symlinks, and a cycle + fails. A refusal on the way names that symlink. + """ + if path in seen: + raise _LinkRefused(f"its target leads through a cycle of symlinks ('{path}' again)") + if len(seen) >= MAX_LINK_HOPS: + raise _LinkRefused(f"its target leads through more than {MAX_LINK_HOPS} symlinks") + seen.append(path) + components = _base_link_hop(git, repo_dir, base_sha, path) + current: list[str] = [] + for component in components: + candidate = "/".join([*current, component]) + if os.path.islink(os.path.join(repo_dir, candidate)): + try: + resolved = _resolve_base_link(git, repo_dir, base_sha, candidate, seen) + except _LinkRefused as e: + if str(e).startswith("its target leads through"): + raise + raise _LinkRefused(f"the symlink '{candidate}' on the way: {e}") from e + current = resolved.split("/") + else: + current.append(component) + return "/".join(current) + + +def directory_target_specs(patterns: Iterable[str]) -> list[str]: + """Pathspecs of the directories whose whole content the reset covers: each directory pattern ``D/``. + + ``D`` itself and everything below it. Never the leading directories of + a file pattern (``container_specs``): only the file is reset there, not + the rest of the directory. + """ + dirs = [p for p in patterns if p.endswith("/")] + return [*pathspecs(dirs), *(f":(glob,icase)**/{d.rstrip('/')}" for d in dirs)] + + +def _is_directory(repo_dir: str, path: str) -> bool: + try: + return stat.S_ISDIR(os.lstat(os.path.join(repo_dir, path)).st_mode) + except (FileNotFoundError, NotADirectoryError): # a missing path, or one through a file + return False + + +def _has_nothing_below(repo_dir: str, path: str) -> bool: + """True if ``path`` is a regular file or does not exist (nor its parent). + + ``path`` is a resolved link target, so no component of it is a symlink. + """ + try: + return stat.S_ISREG(os.lstat(os.path.join(repo_dir, path)).st_mode) + except (FileNotFoundError, NotADirectoryError): + return True + + +def verify_no_linked_directories( + git: Git, + repo_dir: str, + *, + base_sha: str, + patterns: Sequence[str], + scratch_parent: str, + env: Mapping[str, str], +) -> None: + """Fails closed on a symlink or a gitlink that could expose files the reset does not cover. + + The post-condition of the reset for links, checked on its result, and + the full statement of the rule (docs/agent-review.md, invariant 6, + points here). Matching is git's (scratch indexes), at any depth and + case-insensitively. + + No gitlink and no symlink may stand at a path a reset pattern matches + (an instruction file, a rule file, or anything below a directory + pattern), at a directory pattern's directory, or at a directory a + pattern goes through. Otherwise the agent could read, through the + link, files the reset never touched. Exceptions: + + - A gitlink that is the base commit's own (same path, same commit) + with an empty directory (``_is_base_gitlink``): submodules are never + fetched, so nothing is below it. + - A symlink of the base that links one instruction file or directory to + another ('.claude/skills -> ../.agents/skills', 'AGENTS.md -> + CLAUDE.md'), if: + + 1. it is the base's own, with the same target as in the base commit + (a PR's symlink never qualifies: the reset replaces it); + 2. its target is relative, climbs only through leading '..' and + stays inside the repository; + 3. every symlink on the way to the target meets 1 and 2 as well, at + most MAX_LINK_HOPS of them and without a cycle; + 4. the reset covers the real path it leads to: a file must match a + reset pattern itself; a directory must be a directory pattern's + directory or lie below one, never merely a directory a file + pattern goes through, whose other files are not reset. + + - A base symlink that stands only where a pattern expects a directory + on the way (``container_specs``; not matched by a pattern itself) and + leads to a regular file or to nothing (the pull request deleted the + target, or the base never had it): no instruction file can lie below + it, and wildcard patterns ('docs/*/RULES.md') would otherwise refuse + every such link ('docs/logo.png -> ../assets/logo.png'). It must + still meet 1 to 3. + + Any other base symlink would let the agent read files the PR changes. + The error names the first refused link, with its target or the reason it + was refused, and how many were refused. + """ + linked = _linked_paths(git, repo_dir) + if not linked: + return + link_specs = [*pathspecs(patterns), *container_specs(patterns)] + file_specs = pathspecs(patterns) + dir_specs = directory_target_specs(patterns) + # (link, target the reset does not cover, or None; reason when there is no target) + refused: list[tuple[str, str | None, str]] = [] + with Coverage(scratch_parent, env, ()) as coverage: + try: + matched_itself = set(coverage.matching(linked, file_specs)) + for path in coverage.matching(linked, link_specs): + if not os.path.islink(os.path.join(repo_dir, path)): # a gitlink + if not _is_base_gitlink(git, repo_dir, base_sha, path): + reason = "it is a gitlink that is not the base commit's own with an empty directory" + refused.append((path, None, reason)) + continue + try: + target = _resolve_base_link(git, repo_dir, base_sha, path, []) + except _LinkRefused as e: + refused.append((path, None, str(e))) + continue + if path not in matched_itself and _has_nothing_below(repo_dir, target): + continue # a directory on the way to a pattern, but a file or nothing: nothing is below it + specs = dir_specs if _is_directory(repo_dir, target) else file_specs + if not coverage.matching([target], specs): + refused.append((path, target, "")) + except runner.CommandError as e: + raise Fatal(f"Could not check the symlinks and gitlinks of the checkout: {e}.") from e + if not refused: + return + first, uncovered, reason = refused[0] + count = f"({len(refused)} such path(s))" + if uncovered is None: + raise Fatal( + f"'{first}' is a symlink or a gitlink where the reset expects an instruction file or directory," + f" or a directory leading to an instruction file, and {reason} {count}." + ) + wanted = f"{uncovered}/" if _is_directory(repo_dir, uncovered) else uncovered + raise Fatal( + f"'{first}' is a symlink in the base commit to '{uncovered}', which the reset does not cover, so the agent" + f" would read the pull request's version {count}; add '{wanted}' to instruction_files to review it." + ) + + +def _parse_ls_tree(listing: bytes) -> tuple[str, str, str, str] | None: + """(mode, type, id, path) of the first 'ls-tree -z' record, or None if there is none.""" + record = listing.split(b"\0", 1)[0] + if not record: + return None + meta, _, name = record.partition(b"\t") + fields = meta.decode("ascii", errors="replace").split(" ") + if len(fields) != 3: + return ("", "", "", os.fsdecode(record)) + return (fields[0], fields[1], fields[2], os.fsdecode(name)) + + +def verify_followed_files( + git: Git, repo_dir: str, base_sha: str, rule_files: Sequence[str], named: Sequence[str] +) -> str: + """Checks the post-condition of the reset; returns the summary line, or raises Fatal. + + Checked on the result rather than on the patterns, so a pattern that + does not match what it seems to cannot let the PR's version through. + No leading directory may be a symlink, so the path in the checkout is + the path git wrote. + """ + missed = "is not its base version in the checkout: the reset missed it." + for path in (*rule_files, *named): + if not path: + continue + if not is_plain_path(path): + raise Fatal(f"Invalid followed file '{path}': not a plain path.") + parent = path + while "/" in parent: + parent = parent.rsplit("/", 1)[0] + if os.path.islink(os.path.join(repo_dir, parent)): + raise Fatal(f"Followed file '{path}': '{parent}' is a symlink in the checkout.") + checkout_path = os.path.join(repo_dir, path) + # '-z': the path comes back unquoted, so it compares with ``path`` as is. + entry = _parse_ls_tree(git.output("ls-tree", "-z", "--full-tree", base_sha, "--", path)) + if entry is None: + if os.path.lexists(checkout_path): + raise Fatal( + f"Followed file '{path}' is not in the base commit but is in the checkout: the reset missed it." + ) + continue + mode, kind, object_id, name = entry + if name != path: + raise Fatal(f"Followed file '{path}': unexpected base entry '{mode} {kind} {object_id}\t{name}'.") + if (mode, kind) in (("100644", "blob"), ("100755", "blob")): + same = ( + os.path.isfile(checkout_path) + and not os.path.islink(checkout_path) + and git.line("hash-object", "--no-filters", "--", path) == object_id + ) + if not same: + raise Fatal(f"Followed file '{path}' {missed}") + elif (mode, kind) == ("120000", "blob"): + same = os.path.islink(checkout_path) and os.fsencode(os.readlink(checkout_path)) == git.output( + "cat-file", "blob", object_id + ) + if not same: + raise Fatal(f"Followed file '{path}' {missed}") + else: + raise Fatal(f"Followed file '{path}' is not a file in the base commit (mode {mode}).") + return ( + f"run-review: {len(rule_files)} rule file(s) and {len(named)} file(s) named by the addendum" + " are their base versions." + ) diff --git a/agent-review/lib/agent_review/review_errors.py b/agent-review/lib/agent_review/review_errors.py new file mode 100644 index 0000000..37ab511 --- /dev/null +++ b/agent-review/lib/agent_review/review_errors.py @@ -0,0 +1,5 @@ +"""The error that stops ``run-review``.""" + + +class Fatal(Exception): + """Stops run-review with exit code 1; the message is printed as 'run-review: '.""" diff --git a/agent-review/lib/agent_review/run_review.py b/agent-review/lib/agent_review/run_review.py new file mode 100644 index 0000000..2b5466a --- /dev/null +++ b/agent-review/lib/agent_review/run_review.py @@ -0,0 +1,514 @@ +"""In-sandbox driver of the agent review: ``run-review``; harness-agnostic. + +Usage: ``run-review [--phase fetch|review|all] `` + +Runs INSIDE the AWF sandbox (see docs/agent-review.md), in two sandbox +runs, so that the agent never has network access: + +``fetch`` + fetches the PR from github.com (the only allowed domain), with every + object it needs, prepares the checkout and renders the prompt; no + inference key, no harness; +``review`` + runs the harness with no allowed domain (only the inference listener) + and collects its review. + +``all`` (the default) does both in one run, for local tests. Everything +fetched from the pull request is untrusted: git runs with hooks, +global/system config, submodules and LFS disabled (``sandbox_git``), and +nothing from the checkout is executed here. The harness adapter is the only +component that acts on the content, and it holds no secret. + +Inputs, written by the trusted host before the sandbox starts: +``/in/params.json`` (validated parameters: repo, pr, shas, +harness, ...) and ``/in/pr.json`` (the raw GitHub API response +for the PR, untrusted). Outputs: ``/out/review.md`` (the review, +at most REVIEW_MAX_BYTES) and ``/out/meta.json`` (the status of +the run). + +Exit codes: 0 review written (or, for ``fetch``, the checkout prepared), 2 +the harness ran but produced no review, 1 anything else. + +The harness contract (harnesses/README.md): ``bash /run.sh`` under +``timeout``, in the checkout, with ``PROMPT_FILE``, ``REPO_DIR``, +``OUT_DIR``, ``CONTEXT_DIR``, ``MODEL``, ``HARNESS_PREFIX``, ``PR_NUMBER`` +and ``STUB_PADDING_KIB`` set, and the run's ``HOME``, ``TMPDIR`` and forced +``GIT_*`` variables on top of the inherited environment; exit 0 means a +review, 2 none. +""" + +import contextlib +import json +import os +import secrets +import shutil +import stat +import sys +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +import agent_review +from agent_review import files, prompt, reset, runner, validate +from agent_review.review_errors import Fatal +from agent_review.sandbox_git import GIT_ENV, Git + +USAGE = "Usage: run-review [--phase fetch|review|all] " +PHASES = ("fetch", "review", "all") +# Leaves room for the comment header under GitHub's 65536-character limit +# and under the 64 KiB 'collect-result' cap on the host. +REVIEW_MAX_BYTES = 60000 +TRUNCATION_NOTE = b"\n\n_[Review truncated: it exceeded %d bytes.]_\n" % REVIEW_MAX_BYTES +PARAMS_MAX_BYTES = 1 << 20 +EXIT_NO_REVIEW = 2 +# A three-dot diff needs the merge base, which a shallow fetch may lack. +FETCH_DEPTH = 50 +DEEPEN_STEPS = (200, 1000, 5000) +HEADING = b"### " +_SCAN_CHUNK = 1 << 20 + +TIMEOUT_MINUTES = validate.pattern(r"[1-9][0-9]{0,2}") +STUB_PADDING_KIB = validate.pattern(r"[0-9]{1,5}") + + +def one_line(text: str) -> str: + """``text`` with CR and LF escaped: values in messages (a parameter, a path + from the PR tree) cannot add lines to the log.""" + return text.replace("\r", "\\r").replace("\n", "\\n") + + +def _write(stream: Any, text: str) -> None: + """One line; non-UTF-8 bytes of a path are written back as they were.""" + stream.buffer.write((one_line(text) + "\n").encode("utf-8", errors="surrogateescape")) + stream.flush() + + +def say(text: str) -> None: + """A progress line on stdout.""" + _write(sys.stdout, text) + + +def trusted_root() -> str: + """The directory holding bin/, lib/ and the trusted files (/opt/agent-review in the sandbox).""" + lib = os.path.dirname(os.path.dirname(os.path.realpath(agent_review.__file__))) + return os.path.dirname(lib) + + +@dataclass(frozen=True) +class Params: + repo: str + pr_number: str + head_sha: str + base_sha: str + harness: str + model: str + timeout_minutes: str + stub_padding_kib: str + project: str + + +def _tostring(value: Any) -> str: + """A JSON value as text: a string as it is, anything else as compact JSON.""" + if isinstance(value, str): + return value + return json.dumps(value, ensure_ascii=False, separators=(",", ":")) + + +def load_params(path: str) -> Params: + """The validated parameters (validated in 'authorize' already; checked again + because they become paths, URLs and command arguments).""" + try: + data = json.loads(files.read_text(path, PARAMS_MAX_BYTES)) + except (OSError, ValueError, RecursionError) as e: + raise Fatal(f"Cannot read the parameters from '{path}': {e}") from e + if not isinstance(data, dict): + raise Fatal(f"'{path}' does not hold a JSON object.") + + def param(key: str, default: str | None = None) -> str: + value = data.get(key) + if default is not None and (value is None or value is False): + return default + return _tostring(value) + + repo = param("repo") + project = param("project", "") or repo.split("/", 1)[-1] + params = Params( + repo=repo, + pr_number=param("pr"), + head_sha=param("head_sha"), + base_sha=param("base_sha"), + harness=param("harness"), + model=param("model"), + timeout_minutes=param("harness_timeout_minutes"), + stub_padding_kib=param("stub_padding_kib", "0"), + project=project, + ) + for value, pattern, what in ( + (params.repo, validate.REPO, "repo"), + (params.pr_number, validate.POSITIVE_INT, "PR number"), + (params.head_sha, validate.SHA, "head sha"), + (params.base_sha, validate.SHA, "base sha"), + (params.harness, validate.HARNESS, "harness"), + (params.model, validate.MODEL, "model"), + (params.timeout_minutes, TIMEOUT_MINUTES, "timeout"), + (params.stub_padding_kib, STUB_PADDING_KIB, "stub padding"), + (params.project, validate.PROJECT, "project"), + ): + if not validate.matches(pattern, value): + raise Fatal(f"Invalid {what} '{value}'.") + return params + + +def remove(path: str) -> None: + """``rm -rf``: a symlink is removed, never followed.""" + if os.path.isdir(path) and not os.path.islink(path): + shutil.rmtree(path) + elif os.path.lexists(path): + os.unlink(path) + + +class Run: + """One run of run-review on a workspace.""" + + def __init__(self, ws: str, root: str, params: Params, config: reset.Config) -> None: + self.ws = ws + self.root = root + self.params = params + self.config = config + self.in_dir = os.path.join(ws, "in") + self.repo_dir = os.path.join(ws, "repo") + self.context_dir = os.path.join(self.repo_dir, reset.CONTEXT_NAME) + self.harness_out = os.path.join(ws, "harness-out") + self.result_dir = os.path.join(ws, "out") + self.scratch_home = os.path.join(ws, "scratch-home") + self.scratch_tmp = os.path.join(ws, "scratch-tmp") + self.prompt_file = os.path.join(ws, "prompt.md") + self.adapter_dir = os.path.join(root, "harnesses", params.harness) + self.harness_prefix = os.path.join(root, "harness", params.harness) + # The environment overrides of every command (git and the harness): + # the forced GIT_* settings. + self.env: dict[str, str] = dict(GIT_ENV) + + def _scratch(self, *dirs: str) -> None: + """Fresh directories, and HOME and TMPDIR in the workspace, the only + directory the sandbox may write to ('filesystem.allowWrite').""" + for directory in (*dirs, self.scratch_home, self.scratch_tmp): + remove(directory) + for directory in (*dirs, self.scratch_home, self.scratch_tmp): + os.makedirs(directory, exist_ok=True) + self.env.update(HOME=self.scratch_home, TMPDIR=self.scratch_tmp) + + # --- Fetch ---------------------------------------------------------------- + + def fetch(self) -> None: + p = self.params + for path in (self.prompt_file, self.harness_out, self.result_dir): + remove(path) + self._scratch(self.repo_dir) + git = Git(self.repo_dir, self.env) + git.run("init", "-q") + git.run("remote", "add", "origin", f"https://github.com/{p.repo}.git") + + # Fetch by sha so the reviewed commit is exactly the one authorized; + # never fall back to the moving 'refs/pull/N/head'. Full objects, no + # partial clone: the review phase has no network, so nothing can be + # fetched lazily there. + git.run("fetch", "-q", "--no-tags", f"--depth={FETCH_DEPTH}", "origin", p.head_sha, p.base_sha) + if git.line("rev-parse", "--verify", f"{p.head_sha}^{{commit}}") != p.head_sha: + raise Fatal(f"Fetched head does not match {p.head_sha}.") + if git.line("rev-parse", "--verify", f"{p.base_sha}^{{commit}}") != p.base_sha: + raise Fatal(f"Fetched base does not match {p.base_sha}.") + merge_base = self._merge_base(git) + + git.run("checkout", "-q", "--detach", p.head_sha) + + # --- Context files --- + # The PR may itself contain '.agent-review-context'; git removes it + # safely (it does not follow symlinks), then the directory is created fresh. + git.run("rm", "-r", "-q", "-f", "--ignore-unmatch", "--", reset.CONTEXT_NAME) + remove(self.context_dir) + os.makedirs(os.path.join(self.context_dir, "pr-instruction-files")) + info = os.path.join(self.repo_dir, ".git", "info") + os.makedirs(info, exist_ok=True) + files.append_bytes(os.path.join(info, "exclude"), f"/{reset.CONTEXT_NAME}/\n".encode()) + self._git_to_file(git, "diff.patch", "diff", "--no-ext-diff", "--no-textconv", merge_base, p.head_sha) + self._git_to_file(git, "changed-files.txt", "diff", "--no-ext-diff", "--name-status", merge_base, p.head_sha) + + # --- Reset agent instruction files to the base version --- + reset.reset_instruction_files( + git, + self.ws, + head_sha=p.head_sha, + base_sha=p.base_sha, + patterns=self.config.reset_patterns, + context_dir=self.context_dir, + ) + followed = reset.verify_followed_files( + git, self.repo_dir, p.base_sha, self.config.rule_files, self.config.addendum_named + ) + reset.verify_no_linked_directories( + git, + self.repo_dir, + base_sha=p.base_sha, + patterns=self.config.reset_patterns, + scratch_parent=self.ws, + env=self.env, + ) + # Only once both post-conditions hold: a followed file that is a + # base symlink to a file the reset does not cover is its base + # version, but not its base content. + say(followed) + + # --- Render the prompt --- + title, body = prompt.read_pr(os.path.join(self.in_dir, "pr.json")) + values = prompt.PromptValues( + project=p.project, + repo=p.repo, + pr_number=p.pr_number, + head_sha=p.head_sha, + base_sha=p.base_sha, + merge_base=merge_base, + rules=prompt.rules_bytes(self.config.rule_files), + addendum=prompt.addendum_bytes(self.config.addendum), + title=title, + body=body, + ) + files.write_new(self.prompt_file, prompt.render(self.config.template, values, prompt.new_nonce())) + say(f"run-review: fetched {p.repo}#{p.pr_number} at {p.head_sha} (merge base {merge_base}).") + + def _merge_base(self, git: Git) -> str: + """Deepens the shallow fetch until base and head have a merge base.""" + p = self.params + for deepen in DEEPEN_STEPS: + found = git.line("merge-base", p.base_sha, p.head_sha, quiet=True) + if found is not None: + return found + git.run("fetch", "-q", "--no-tags", f"--deepen={deepen}", "origin", p.head_sha, p.base_sha) + # After the last deepening, unshallow without another merge-base attempt. + git.run("fetch", "-q", "--no-tags", "--unshallow", "origin", p.head_sha, p.base_sha) + found = git.line("merge-base", p.base_sha, p.head_sha) + if found is None: + raise Fatal("No merge base between base and head.") + return found + + def _git_to_file(self, git: Git, name: str, *args: str) -> None: + path = os.path.join(self.context_dir, name) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o644) + try: + git.run(*args, stdout_fd=fd) + finally: + os.close(fd) + + # --- Review ----------------------------------------------------------------- + + def review(self) -> int: + p = self.params + # The checkout and prompt come from the fetch phase, which ran no agent. + if not (os.path.isfile(self.prompt_file) and os.path.isdir(os.path.join(self.repo_dir, ".git"))): + raise Fatal(f"No prepared checkout in '{self.ws}'; run the fetch phase first.") + self._scratch(self.harness_out, self.result_dir) + + say(f"run-review: running harness '{p.harness}' on {p.repo}#{p.pr_number} at {p.head_sha}.") + harness_exit = self._run_harness() + self._fresh_result_dir() + status = {0: "ok", 2: "no-review", 124: "timeout", 137: "timeout"}.get(harness_exit, "failed") + + # The harness output is agent-controlled: accept only a regular file. + # The host re-checks this ('collect-result'); this check keeps the + # failure readable. + collected = read_review(os.path.join(self.harness_out, "review.md")) if status == "ok" else None + if collected is None: + if status == "ok": + status = "no-review" + self._write_meta(status, harness_exit, truncated=False, review_bytes=0) + _write(sys.stderr, f"run-review: no review produced (status '{status}', harness exit {harness_exit}).") + return EXIT_NO_REVIEW if status == "no-review" else 1 + + review, truncated = collected + files.write_new(os.path.join(self.result_dir, "review.md"), review) + self._write_meta("ok", harness_exit, truncated=truncated, review_bytes=len(review)) + say(f"run-review: review written ({len(review)} bytes, truncated={'true' if truncated else 'false'}).") + return 0 + + def _fresh_result_dir(self) -> None: + """Replaces out/ by an empty directory after the harness ran. + + The harness can write anywhere in the workspace, out/ included, and + could make it impossible to empty (a read-only subdirectory), so the + old out/ is renamed aside, under a name it cannot guess, and removed + as far as possible. Only what this script writes into the new out/ is + the result. A harness process left running could still write there + until the sandbox is torn down: the workflow collects nothing while + any sandbox container survives, and collect-result accepts only a + regular review.md and meta.json, re-checked on the host. + """ + if os.path.lexists(self.result_dir): + aside = f"{self.result_dir}.harness-{secrets.token_hex(8)}" + os.rename(self.result_dir, aside) + with contextlib.suppress(OSError): # else left in the workspace, outside out/ + remove(aside) + os.mkdir(self.result_dir) + + def _run_harness(self) -> int: + """The adapter's exit code, as a shell reports it: 128 + n for signal n, 127 if it cannot start.""" + p = self.params + env = { + **self.env, + "PROMPT_FILE": self.prompt_file, + "REPO_DIR": self.repo_dir, + "MODEL": p.model, + "HARNESS_PREFIX": self.harness_prefix, + "PR_NUMBER": p.pr_number, + "CONTEXT_DIR": self.context_dir, + "STUB_PADDING_KIB": p.stub_padding_kib, + # The harness writes to its own directory; only this script writes the result. + "OUT_DIR": self.harness_out, + } + argv = [ + "timeout", + "--kill-after=30s", + f"{p.timeout_minutes}m", + "bash", + os.path.join(self.adapter_dir, "run.sh"), + ] + try: + # stdout and stderr pass through to the sandbox's output. + result = runner.run( + runner.Zone.SANDBOX, + argv, + env=env, + cwd=self.repo_dir, + stdout_fd=1, + capture_stderr=False, + check=False, + ) + except runner.CommandError as e: + _write(sys.stderr, f"run-review: {e}") + return 127 + return result.returncode if result.returncode >= 0 else 128 - result.returncode + + def _write_meta(self, status: str, harness_exit: int, *, truncated: bool, review_bytes: int) -> None: + meta = { + "harness": self.params.harness, + "model": self.params.model, + "status": status, + "harness_exit": harness_exit, + "truncated": truncated, + "review_bytes": review_bytes, + } + os.makedirs(self.result_dir, exist_ok=True) + # A stable layout: two-space indent, non-ASCII as is, a final newline. + text = json.dumps(meta, indent=2, ensure_ascii=False) + "\n" + files.write_new(os.path.join(self.result_dir, "meta.json"), text.encode("utf-8")) + + +def _heading_offset(fd: int) -> int | None: + """The offset of the first line that starts with '### ', or None.""" + if os.pread(fd, len(HEADING), 0) == HEADING: + return 0 + needle = b"\n" + HEADING + pos, tail = 0, b"" + while chunk := os.pread(fd, _SCAN_CHUNK, pos): + window = tail + chunk + found = window.find(needle) + if found >= 0: + return pos - len(tail) + found + 1 + tail = window[-(len(needle) - 1) :] + pos += len(chunk) + return None + + +def read_review(path: str) -> tuple[bytes, bool] | None: + """The review to publish and whether it was truncated; None unless ``path`` is a non-empty regular file. + + Models often open their answer with a note ("Writing the final review + now.") although the prompt asks them to start with '### Summary': the + review is kept from its first '### ' heading, if any, and then ends + with a newline (counted in the size); a review without such a heading + is kept as it is. Over REVIEW_MAX_BYTES, it is cut and a note appended; + that is decided from the bytes read, never from the file's size, which + the agent can change meanwhile. Invalid or cut UTF-8 sequences are + dropped. The file is scanned in chunks, never held in memory whole: the + agent controls its size (without a heading, the scan for one still reads + to the end of the file). + """ + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_NOCTTY | os.O_CLOEXEC) + except OSError: + return None + try: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_size == 0: + return None + start = _heading_offset(fd) + # At most one byte more than the limit, so that 'too long' is known. + wanted = REVIEW_MAX_BYTES + 1 + chunks, pos, got, at_end = [], start or 0, 0, False + while got < wanted: + chunk = os.pread(fd, wanted - got, pos) + if not chunk: + at_end = True + break + chunks.append(chunk) + pos += len(chunk) + got += len(chunk) + finally: + os.close(fd) + body = b"".join(chunks) + if start is not None and at_end and body and not body.endswith(b"\n"): + body += b"\n" + if len(body) > REVIEW_MAX_BYTES: + return prompt.clip(body, REVIEW_MAX_BYTES - 100) + TRUNCATION_NOTE, True + return prompt.clip(body, len(body)), False + + +def parse_args(args: Sequence[str]) -> tuple[str, str]: + """(phase, workspace); the messages are part of the CLI contract the test suites pin.""" + phase = "all" + rest = list(args) + if rest and rest[0] == "--phase": + if len(rest) < 2: + raise Fatal(USAGE) + phase, rest = rest[1], rest[2:] + if phase not in PHASES: + raise Fatal(f"Invalid phase '{phase}'.") + if len(rest) != 1: + raise Fatal(USAGE) + ws = rest[0] + if not ws.startswith("/"): + raise Fatal(f"The workspace must be an absolute path, got '{ws}'.") + return phase, ws + + +def run(args: Sequence[str], root: str) -> int: + phase, ws = parse_args(args) + params = load_params(os.path.join(ws, "in", "params.json")) + # Caller configuration (trusted: the caller's validated inputs and its + # addendum file at the caller's workflow commit), next to this script's + # own files. A missing caller file means "not configured"; a missing + # central list or template is fatal. + config = reset.load_config(root) + reset.check_coverage(config, ws, GIT_ENV) + current = Run(ws, root, params, config) + if not os.path.isfile(os.path.join(current.adapter_dir, "run.sh")): + raise Fatal(f"No adapter for harness '{params.harness}'.") + if not os.path.isdir(current.harness_prefix): + raise Fatal(f"Harness '{params.harness}' is not installed at '{current.harness_prefix}'.") + if phase in ("fetch", "all"): + current.fetch() + if phase in ("review", "all"): + return current.review() + return 0 + + +def main(argv: Sequence[str] | None = None) -> int: + try: + return run(sys.argv[1:] if argv is None else argv, trusted_root()) + except Fatal as e: + message = str(e) + except runner.CommandError as e: + message = str(e) + except OSError as e: + message = f"{e.filename or ''}: {e.strerror or e}".lstrip(": ") + _write(sys.stderr, f"run-review: {message}") + return 1 diff --git a/agent-review/lib/agent_review/runner.py b/agent-review/lib/agent_review/runner.py new file mode 100644 index 0000000..c51a332 --- /dev/null +++ b/agent-review/lib/agent_review/runner.py @@ -0,0 +1,237 @@ +"""The only place that starts processes. + +Commands are argument lists, never shell strings. How the program is found +and which environment it gets depend on the trust zone the caller runs in +(docs/adr/0004-python-runtime.md): + +``TRUSTED_HOST`` + ``authorize`` and ``publish-comment post``: they run before any untrusted + code, or on a fresh VM. A bare program name is looked up on ``PATH`` + and the environment is inherited: the workflow fixes ``PATH`` on those + steps, and the test suites put a fake ``gh`` first on ``PATH``. +``SANDBOX`` + ``run-review``, inside AWF: ``PATH`` lookup and the inherited + environment, plus the caller's overrides (the forced ``GIT_*`` + settings). An inherited ``GIT_ALLOW_PROTOCOL`` reaches git. +``TAINTED_HOST`` + The host after the sandbox has run. No process starts there today + (``collect-result`` runs there and starts none); the zone exists so + that any future one gets an absolute program under ``/usr/bin`` or + ``/bin`` and a fixed environment (``FIXED_ENV`` plus overrides, never + ``PATH``): the runner's ``PATH`` searches ``~/.local/bin`` and the like + first, and AWF mounts them read-only, but after the sandbox has run + nothing on the host is trusted (invariant 3). + +The lookup never uses a relative ``PATH`` entry (an empty entry means the +working directory), and the program is resolved to an absolute path before +it runs. +""" + +import enum +import os +import selectors +import subprocess +import sys +import time +from collections.abc import Mapping, Sequence +from dataclasses import dataclass + + +class Zone(enum.Enum): + TRUSTED_HOST = "trusted-host" + SANDBOX = "sandbox" + TAINTED_HOST = "tainted-host" + + +# The whole environment of a command on the tainted host. +FIXED_ENV: Mapping[str, str] = {"PATH": "/usr/bin:/bin", "LC_ALL": "C.UTF-8"} +TAINTED_TOOL_DIRS = ("/usr/bin", "/bin") +# Bytes of stderr kept (the last ones) in a Result or CommandError. +STDERR_EXCERPT_BYTES = 4096 +# Default cap on a command's stdout; more kills the command. +MAX_STDOUT_BYTES = 16 * 1024 * 1024 +_CHUNK = 1 << 16 + + +class CommandError(Exception): + """A command could not be started, timed out or exited non-zero.""" + + def __init__(self, program: str, message: str, returncode: int | None = None, stderr: bytes = b"") -> None: + super().__init__(f"{program}: {message}") + self.program = program + self.returncode = returncode + self.stderr = stderr[-STDERR_EXCERPT_BYTES:] + + +@dataclass(frozen=True) +class Result: + returncode: int + stdout: bytes + stderr: bytes + + +def _check_argv(argv: Sequence[str]) -> list[str]: + if isinstance(argv, str | bytes) or not argv: + raise ValueError("argv must be a non-empty list of strings") + args = list(argv) + for arg in args: + if not isinstance(arg, str): + raise TypeError(f"argument {arg!r} is not a string") + if "\0" in arg: + raise ValueError("an argument contains a NUL character") + return args + + +def find_program(name: str, path: str) -> str: + """Resolves a bare program name on ``path``, skipping relative entries.""" + if not name or "/" in name or name in (".", ".."): + raise ValueError(f"not a bare program name: {name!r}") + for directory in path.split(os.pathsep): + if not directory.startswith("/"): + continue + candidate = os.path.join(directory, name) + if os.path.isfile(candidate) and os.access(candidate, os.X_OK): + return candidate + raise CommandError(name, "not found on PATH") + + +def resolve(zone: Zone, program: str, env: Mapping[str, str]) -> str: + """The absolute path of ``program`` as ``zone`` allows it.""" + if zone is Zone.TAINTED_HOST: + directory, name = os.path.split(program) + if directory not in TAINTED_TOOL_DIRS or name in ("", ".", ".."): + raise ValueError( + f"on the tainted host, programs must be absolute paths under /usr/bin or /bin: {program!r}" + ) + return program + if program.startswith("/"): + return program + return find_program(program, env.get("PATH", "")) + + +def environment(zone: Zone, overrides: Mapping[str, str] | None = None) -> dict[str, str]: + """The environment a command gets in ``zone``.""" + overrides = dict(overrides or {}) + for key, value in overrides.items(): + if not key or "=" in key or "\0" in key or "\0" in value: + raise ValueError(f"invalid environment override {key!r}") + if zone is Zone.TAINTED_HOST: + if "PATH" in overrides: + raise ValueError("PATH is fixed on the tainted host") + return {**FIXED_ENV, **overrides} + return {**os.environ, **overrides} + + +def _remaining(deadline: float | None) -> float | None: + return None if deadline is None else max(0.0, deadline - time.monotonic()) + + +def _communicate( + proc: "subprocess.Popen[bytes]", stdin: bytes | None, max_stdout: int, deadline: float | None +) -> tuple[bytes, bytes, str | None]: + """Feeds stdin and reads stdout and stderr until EOF; returns (stdout, stderr tail, abort reason).""" + out = bytearray() + err = bytearray() + pending = memoryview(stdin or b"") + stdin_fd = proc.stdin.fileno() if proc.stdin is not None else -1 + stdout_fd = proc.stdout.fileno() if proc.stdout is not None else -1 + with selectors.DefaultSelector() as selector: + if proc.stdin is not None: + os.set_blocking(stdin_fd, False) + selector.register(stdin_fd, selectors.EVENT_WRITE) + if proc.stdout is not None: + selector.register(stdout_fd, selectors.EVENT_READ) + if proc.stderr is not None: + selector.register(proc.stderr.fileno(), selectors.EVENT_READ) + while selector.get_map(): + remaining = _remaining(deadline) + if remaining == 0.0: + return bytes(out), bytes(err), "timeout" + for key, _ in selector.select(remaining): + fd = key.fd + if fd == stdin_fd: + try: + pending = pending[os.write(fd, pending[:_CHUNK]) :] + except BrokenPipeError: + pending = pending[len(pending) :] + if not pending and proc.stdin is not None: + selector.unregister(fd) + proc.stdin.close() + continue + chunk = os.read(fd, _CHUNK) + if not chunk: + selector.unregister(fd) + elif fd == stdout_fd: + out += chunk + if len(out) > max_stdout: + return bytes(out), bytes(err), "output" + else: + err += chunk + del err[:-STDERR_EXCERPT_BYTES] + return bytes(out), bytes(err), None + + +def run( + zone: Zone, + argv: Sequence[str], + *, + stdin: bytes | None = None, + env: Mapping[str, str] | None = None, + cwd: str | None = None, + timeout: float | None = None, + check: bool = True, + capture_stderr: bool = True, + max_stdout: int = MAX_STDOUT_BYTES, + stdout_fd: int | None = None, +) -> Result: + """Runs ``argv`` (never through a shell) and returns its output as bytes. + + ``env`` holds overrides on top of the zone's environment. Without + ``stdin`` the command reads from /dev/null. With ``capture_stderr`` + false, stderr goes to this process's stderr; otherwise its last + STDERR_EXCERPT_BYTES are kept. More than ``max_stdout`` bytes of stdout, + or the ``timeout``, kills the command and raises CommandError. With + ``stdout_fd``, stdout goes to that open descriptor instead (a file the + caller created, or 1 to pass it through), uncapped, and + ``Result.stdout`` is empty. With ``check``, a non-zero exit raises + CommandError. This process's own buffered output is flushed first, so + that it stays in order with what the command writes to an inherited + stdout or stderr. + """ + args = _check_argv(argv) + full_env = environment(zone, env) + program = args[0] + args[0] = resolve(zone, program, full_env) + deadline = None if timeout is None else time.monotonic() + timeout + if stdout_fd is not None and stdout_fd < 0: + raise ValueError("stdout_fd must be an open descriptor") + sys.stdout.flush() + sys.stderr.flush() + try: + proc = subprocess.Popen( # noqa: S603 (argument list, resolved program) + args, + stdin=subprocess.DEVNULL if stdin is None else subprocess.PIPE, + stdout=subprocess.PIPE if stdout_fd is None else stdout_fd, + stderr=subprocess.PIPE if capture_stderr else None, + env=full_env, + cwd=cwd, + close_fds=True, + ) + except OSError as e: + raise CommandError(program, f"could not run: {e.strerror}") from e + with proc: + stdout, stderr, abort = _communicate(proc, stdin, max_stdout, deadline) + if abort is None: + try: + returncode = proc.wait(timeout=_remaining(deadline)) + except subprocess.TimeoutExpired: + abort = "timeout" + if abort is not None: + proc.kill() + proc.wait() + if abort == "timeout": + raise CommandError(program, f"timed out after {timeout} s", stderr=stderr) + raise CommandError(program, f"more than {max_stdout} bytes of output", stderr=stderr) + if check and returncode != 0: + raise CommandError(program, f"exit code {returncode}", returncode, stderr) + return Result(returncode, stdout, stderr) diff --git a/agent-review/lib/agent_review/sandbox_git.py b/agent-review/lib/agent_review/sandbox_git.py new file mode 100644 index 0000000..f194c9d --- /dev/null +++ b/agent-review/lib/agent_review/sandbox_git.py @@ -0,0 +1,85 @@ +"""git on pull request content, inside the sandbox (``run-review``). + +Everything fetched from the pull request is untrusted, so git runs with +no system or global configuration (the host's may enable LFS filters or +other helpers), no terminal prompt, no LFS smudging and no replace objects +(``GIT_ENV``), and on every call with hooks and fsmonitor disabled, +symlinks checked out as symlinks, the ``file`` and ``ext`` transports +refused, no submodule recursion and no external diff (``SAFE_CONFIG``): +``.git`` could otherwise be influenced by repository content. + +``GIT_ENV`` is part of the run's environment, which the harness inherits +too, so the harness's own git calls get the same settings. Commands run in +the sandbox zone: git is found on ``PATH`` and the environment is +inherited, so an inherited ``GIT_ALLOW_PROTOCOL`` reaches git (the offline +test of the review phase relies on it). +""" + +from collections.abc import Mapping, Sequence + +from agent_review import runner + +GIT_ENV: Mapping[str, str] = { + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_TERMINAL_PROMPT": "0", + "GIT_LFS_SKIP_SMUDGE": "1", + "GIT_NO_REPLACE_OBJECTS": "1", +} +SAFE_CONFIG = ( + "core.hooksPath=/dev/null", + "core.fsmonitor=false", + "core.symlinks=true", + "protocol.file.allow=never", + "protocol.ext.allow=never", + "submodule.recurse=false", + "diff.external=", + "advice.detachedHead=false", +) + + +class Git: + """git with the safe settings, on the repository at ``repo_dir``. + + ``env`` holds the run's environment overrides (``GIT_ENV`` and the + scratch ``HOME`` and ``TMPDIR``), on top of the inherited environment. + """ + + def __init__(self, repo_dir: str, env: Mapping[str, str]) -> None: + self.repo_dir = repo_dir + self.env = {**env, **GIT_ENV} + + def argv(self, args: Sequence[str]) -> list[str]: + config = [item for setting in SAFE_CONFIG for item in ("-c", setting)] + return ["git", *config, "-C", self.repo_dir, *args] + + def run( + self, + *args: str, + env: Mapping[str, str] | None = None, + stdin: bytes | None = None, + stdout_fd: int | None = None, + quiet: bool = False, + check: bool = True, + ) -> runner.Result: + """Runs git; its stderr goes to ours unless ``quiet`` (then it is dropped).""" + return runner.run( + runner.Zone.SANDBOX, + self.argv(args), + env={**self.env, **(env or {})}, + stdin=stdin, + stdout_fd=stdout_fd, + capture_stderr=quiet, + check=check, + ) + + def output(self, *args: str, env: Mapping[str, str] | None = None, stdin: bytes | None = None) -> bytes: + """The stdout of a git command that must succeed.""" + return self.run(*args, env=env, stdin=stdin).stdout + + def line(self, *args: str, quiet: bool = False) -> str | None: + """The output without its trailing newlines; None if git fails.""" + result = self.run(*args, quiet=quiet, check=False) + if result.returncode != 0: + return None + return result.stdout.rstrip(b"\n").decode("utf-8", errors="strict") diff --git a/agent-review/lib/agent_review/sanitize.py b/agent-review/lib/agent_review/sanitize.py new file mode 100644 index 0000000..bf5b7e5 --- /dev/null +++ b/agent-review/lib/agent_review/sanitize.py @@ -0,0 +1,167 @@ +"""The review sanitiser of ``publish-comment`` (invariant 5 in docs/agent-review.md). + +The review is model output that the pull request can steer, so it is +treated as hostile text that GitHub will render as Markdown in a comment +posted with a write token: + +- it must be valid UTF-8 (strict: no surrogates, nothing above U+10FFFF); +- C0 control characters except tab and newline, and DEL, are dropped; +- invisible characters are dropped: the explicit ranges of ``INVISIBLE`` + (zero-width, bidirectional controls, variation selectors, tag + characters, ...) and every character of Unicode category ``Cf``. The + ranges are kept although most of them are ``Cf``: variation selectors are + ``Mn``, U+2065 is unassigned (``Cn``) in Python's Unicode 15.0, and the + category of a character GitHub knows but Python does not is ``Cn``; +- no raw HTML can form: a zero-width space (ZWSP) follows every ``<`` + that is followed by an ASCII letter, ``/``, ``!`` or ``?``, so there is + no tag, end tag, HTML block, comment (the review cannot imitate the + marker of this workflow's comment), processing instruction, declaration + or CDATA section. GitHub strips attributes and hides the contents of + some HTML; outside HTML, a named reference needs its ``;``. A ZWSP rather + than ``<``: ``std::vector`` in a code span stays readable; +- comment ends (``-->``) and link reference definitions (``[label]: url``) + are broken up with a ZWSP too; +- character references are escaped so they render literally: named ones + (``@``, ``‍``, ``‏``), which GitHub decodes into mentions or + invisible characters, and numeric ones (``@``), with a ZWSP after the + ``#`` so that the escaped form is no issue reference like ``#64``; +- ``@mentions`` get a zero-width joiner (ZWJ) after the ``@``; +- the result is cut to ``REVIEW_MAX_BYTES``, never inside a character or + a neutralisation (``@`` and its ZWJ, ``&``, ...). + +The invisible characters go first, so removing them cannot join a delimiter +that a later replacement would miss (``<`` U+200B ``!--``). The later +replacements cannot create new matches: none inserts ``<``, ``>``, ``&``, +``]`` or ``@``, and the named-reference rule runs before the numeric one. + +Pure functions on bytes and text: this module runs no program and has no +token (its import closure excludes ``agent_review.gh``). +""" + +import re +import unicodedata + +REVIEW_MAX_BYTES = 60000 +ZWSP = "\u200b" # zero-width space +ZWJ = "\u200d" # zero-width joiner + +# Inclusive code point ranges. U+E0100-U+E01FF is the whole block, not only +# the selectors up to U+E01EF, so its unassigned code points go too. +INVISIBLE: tuple[tuple[int, int], ...] = ( + (0x00AD, 0x00AD), # soft hyphen + (0x061C, 0x061C), # Arabic letter mark + (0x180E, 0x180E), # Mongolian vowel separator + (0x200B, 0x200F), # zero-width space, (non-)joiner, LRM, RLM + (0x202A, 0x202E), # bidirectional embeddings and overrides + (0x2060, 0x206F), # word joiner, invisible operators, isolates, ... + (0xFE00, 0xFE0F), # variation selectors + (0xFEFF, 0xFEFF), # byte order mark + (0xE0000, 0xE007F), # tag characters + (0xE0100, 0xE01FF), # variation selectors supplement +) +# Kept: tab and newline. Dropped: the rest of C0, and DEL. +CONTROLS: tuple[tuple[int, int], ...] = ((0x00, 0x08), (0x0B, 0x1F), (0x7F, 0x7F)) + +_DROPPED_BY_RANGE = re.compile( + "[" + "".join(f"\\U{lo:08x}-\\U{hi:08x}" for lo, hi in (*CONTROLS, *INVISIBLE)) + "]", re.ASCII +) + +# The replacements, applied in the order the module docstring gives. +# The start of every raw HTML construct in GitHub's Markdown. +_HTML_START = re.compile(r"<([A-Za-z/!?])", re.ASCII) +_MENTION = re.compile(r"@([A-Za-z0-9])", re.ASCII) +_NAMED_REFERENCE = re.compile(r"&([A-Za-z][A-Za-z0-9]*;)", re.ASCII) + + +class InvalidReviewError(ValueError): + """The review is not valid UTF-8.""" + + +def is_dropped(char: str) -> bool: + """True for a character that ``clean`` removes.""" + return _DROPPED_BY_RANGE.fullmatch(char) is not None or unicodedata.category(char) == "Cf" + + +def drop_invisible(text: str) -> str: + """``text`` without control characters (but tab and newline) and invisible ones.""" + text = _DROPPED_BY_RANGE.sub("", text) + # Cf outside the ranges; only non-ASCII characters can be Cf. + if not text.isascii(): + text = "".join(c for c in text if c < "\x80" or unicodedata.category(c) != "Cf") + return text + + +def neutralise(text: str) -> str: + """Breaks up hidden markup, escapes character references, neutralises mentions.""" + text = _HTML_START.sub(f"<{ZWSP}\\1", text) + text = text.replace("-->", f"--{ZWSP}>") + text = text.replace("]:", f"]{ZWSP}:") + text = _MENTION.sub(f"@{ZWJ}\\1", text) + text = _NAMED_REFERENCE.sub("&\\1", text) + return text.replace("&#", f"&#{ZWSP}") + + +def clean(text: str) -> str: + """The sanitised ``text``, before the size cap.""" + return neutralise(drop_invisible(text)) + + +# What a neutralisation inserts, with the character(s) it protects: a cut +# never falls inside one, so the cut text never ends with a bare '@', '<', +# ']' or '--', or with part of '&'. Every ZWSP and ZWJ in the cleaned +# text was inserted (the input's are dropped), and so was every '&' +# (an '&' in the input becomes '&amp;'). +# Longest first: '&#' ZWSP before '&'. +_UNITS = re.compile( + "|".join(re.escape(u) for u in (f"&#{ZWSP}", "&", f"<{ZWSP}", f"--{ZWSP}", f"]{ZWSP}", f"@{ZWJ}")).encode() +) +_UNIT_MAX_BYTES = len(f"&#{ZWSP}".encode()) + + +def cut(data: bytes, max_bytes: int) -> bytes: + """``data`` (cleaned, valid UTF-8) cut to at most ``max_bytes``. + + Never inside a character, and never inside a neutralisation (``_UNITS``): + the cut backs off to the start of either. + """ + if len(data) <= max_bytes: + return data + end = max_bytes + # Back off over continuation bytes to the start of the cut character. + while end > 0 and data[end] & 0xC0 == 0x80: + end -= 1 + # A unit that contains the cut starts at most _UNIT_MAX_BYTES - 1 before it. + base = max(0, end - _UNIT_MAX_BYTES) + for m in _UNITS.finditer(data, base, end + _UNIT_MAX_BYTES): + if m.start() < end < m.end(): + end = m.start() + break + return data[:end] + + +def decode(data: bytes) -> str: + """``data`` as strict UTF-8, or InvalidReviewError.""" + try: + return data.decode("utf-8", errors="strict") + except UnicodeDecodeError as e: + raise InvalidReviewError("the review is not valid UTF-8.") from e + + +def sanitize_and_report(data: bytes, max_bytes: int = REVIEW_MAX_BYTES) -> tuple[bytes, bool]: + """(the sanitised review as UTF-8 bytes of at most ``max_bytes``, whether the cap cut content). + + The flag is false when the cap removed only trailing newlines, which + ``render`` drops anyway. Raises InvalidReviewError if ``data`` is not + valid UTF-8. + """ + cleaned = clean(decode(data)).encode("utf-8", errors="strict") + out = cut(cleaned, max_bytes) + return out, cleaned[len(out) :].rstrip(b"\n") != b"" + + +def sanitize(data: bytes, max_bytes: int = REVIEW_MAX_BYTES) -> bytes: + """The sanitised review, as UTF-8 bytes of at most ``max_bytes``. + + Raises InvalidReviewError if ``data`` is not valid UTF-8. + """ + return sanitize_and_report(data, max_bytes)[0] diff --git a/agent-review/lib/agent_review/validate.py b/agent-review/lib/agent_review/validate.py new file mode 100644 index 0000000..e6be87e --- /dev/null +++ b/agent-review/lib/agent_review/validate.py @@ -0,0 +1,64 @@ +"""Validation helpers: a value matches its pattern as a whole, in ASCII only. + +Python's defaults accept more than these checks mean to: + +- ``re.match(r'^[0-9a-f]{4}$', 'abcd\\n')`` matches (``$`` before a final + newline), so patterns are only ever applied with ``re.fullmatch``; +- ``\\d``, ``\\w`` and ``\\s`` match non-ASCII characters unless the pattern + is compiled with ``re.ASCII``, which ``pattern()`` always does; +- ``int()`` accepts full-width digits, underscores and surrounding + whitespace (``int(' 1_0\\n')`` is 10), so numbers are matched against a + pattern first (``parse_int``). + +Patterns shared by several entry points are defined here. +""" + +import re + + +class ValidationError(ValueError): + """A value does not match its pattern.""" + + +def pattern(regex: str) -> re.Pattern[str]: + """Compiles a pattern for ``fullmatch`` with ASCII-only classes.""" + if regex.startswith("^") or regex.endswith("$"): + raise ValueError("patterns are applied with fullmatch; drop the anchors") + return re.compile(regex, re.ASCII) + + +def matches(compiled: re.Pattern[str], value: str) -> bool: + """True if all of ``value`` matches ``compiled``.""" + if not compiled.flags & re.ASCII: + raise ValueError("compile patterns with validate.pattern()") + return isinstance(value, str) and compiled.fullmatch(value) is not None + + +def require(compiled: re.Pattern[str], value: str, what: str) -> str: + """Returns ``value`` if it matches, else raises ValidationError.""" + if not matches(compiled, value): + raise ValidationError(f"Invalid {what} {value!r}.") + return value + + +def parse_int(value: str, what: str, *, digits: re.Pattern[str] | None = None, maximum: int | None = None) -> int: + """Parses a decimal integer, validated by ``digits`` before ``int()``. + + The default pattern is ``[0-9]{1,10}``; pass a stricter one to reject a + leading zero, as ``POSITIVE_INT`` does. + """ + require(digits or DIGITS, value, what) + number = int(value, 10) + if maximum is not None and number > maximum: + raise ValidationError(f"Invalid {what} {value!r}: more than {maximum}.") + return number + + +DIGITS = pattern(r"[0-9]{1,10}") +# Pull request numbers: no leading zero. +POSITIVE_INT = pattern(r"[1-9][0-9]{0,9}") +SHA = pattern(r"[0-9a-f]{40}") +REPO = pattern(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") +HARNESS = pattern(r"[a-z][a-z0-9-]{0,31}") +MODEL = pattern(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}") +PROJECT = pattern(r"[A-Za-z0-9][A-Za-z0-9._ -]{0,63}") diff --git a/agent-review/lib/agent_review/workflow.py b/agent-review/lib/agent_review/workflow.py new file mode 100644 index 0000000..997f854 --- /dev/null +++ b/agent-review/lib/agent_review/workflow.py @@ -0,0 +1,115 @@ +"""Workflow commands, step outputs and log lines. + +- Workflow commands (``::notice::`` and the like) escape ``%``, CR and LF in + their data, so a value cannot end the command and start another one. +- ``set_output`` writes ``name=value`` lines to ``$GITHUB_OUTPUT`` and + rejects CR and LF in values: a newline would let a value set other + outputs. The multi-line (heredoc) form is not offered. +- ``log_lines`` writes text that may be untrusted: every line gets a prefix + that starts with neither whitespace nor ``:`` (the runner trims leading + whitespace, including non-breaking spaces, before matching ``::``), NUL + characters are dropped, and every ``##[`` is then broken up with a + zero-width space, because the runner's legacy parser finds + ``##[command]`` anywhere in a line. It never uses ``::stop-commands::``, + whose token would be printed to the live log first. + +Everything is written as strict UTF-8 bytes, never in the locale's +encoding. +""" + +import os +import sys +from typing import BinaryIO + +from agent_review import files, validate + +COMMANDS = ("notice", "warning", "error") +OUTPUT_NAME = validate.pattern(r"[A-Za-z_][A-Za-z0-9_-]{0,63}") +PROPERTY_NAME = validate.pattern(r"[a-zA-Z]{1,16}") + + +def escape_data(text: str) -> str: + return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + + +def escape_property(text: str) -> str: + return escape_data(text).replace(":", "%3A").replace(",", "%2C") + + +def _stdout() -> BinaryIO: + return sys.stdout.buffer + + +def _write(stream: BinaryIO, line: str) -> None: + stream.write(line.encode("utf-8", errors="strict")) + stream.flush() + + +def command(name: str, message: str, properties: dict[str, str] | None = None) -> str: + """One workflow command line, with a trailing newline.""" + if name not in COMMANDS: + raise ValueError(f"unsupported workflow command {name!r}") + props = "" + if properties: + for key in properties: + validate.require(PROPERTY_NAME, key, "command property") + props = " " + ",".join(f"{k}={escape_property(v)}" for k, v in properties.items()) + return f"::{name}{props}::{escape_data(message)}\n" + + +def notice(message: str, *, title: str | None = None, stream: BinaryIO | None = None) -> None: + _write(stream or _stdout(), command("notice", message, {"title": title} if title else None)) + + +def warning(message: str, *, title: str | None = None, stream: BinaryIO | None = None) -> None: + _write(stream or _stdout(), command("warning", message, {"title": title} if title else None)) + + +def error(message: str, *, title: str | None = None, stream: BinaryIO | None = None) -> None: + _write(stream or _stdout(), command("error", message, {"title": title} if title else None)) + + +# The legacy command marker, and what it becomes in log text. +LEGACY_MARKER = "##[" +LEGACY_BROKEN = "#\u200b#[" + + +def neutralise(text: str) -> str: + """Drops NUL and breaks up every legacy command marker (``##[``) in ``text``. + + NUL first, so that '#\\0#[' cannot become a marker afterwards. + """ + return text.replace("\0", "").replace(LEGACY_MARKER, LEGACY_BROKEN) + + +def log_lines(text: str, prefix: str, *, stream: BinaryIO | None = None) -> None: + """Writes ``text`` with ``prefix`` before every line; CRs are dropped.""" + if ( + not prefix + or prefix[0].isspace() + or prefix[0] == ":" + or not prefix.isprintable() + or LEGACY_MARKER in prefix + or "::" in prefix + ): + raise ValueError(f"invalid log prefix {prefix!r}") + lines = neutralise(text.replace("\r", "")).split("\n") + if lines and lines[-1] == "": + lines.pop() + _write(stream or _stdout(), "".join(f"{prefix}{line}\n" for line in lines)) + + +def output_line(name: str, value: str) -> str: + """The ``name=value`` line for ``$GITHUB_OUTPUT``.""" + validate.require(OUTPUT_NAME, name, "output name") + if "\n" in value or "\r" in value: + raise ValueError(f"the value of output {name!r} contains a line break") + return f"{name}={value}\n" + + +def set_output(name: str, value: str, *, path: str | None = None) -> None: + """Appends ``name=value`` to ``$GITHUB_OUTPUT`` (or ``path``).""" + target = path if path is not None else os.environ.get("GITHUB_OUTPUT", "") + if not target.startswith("/"): + raise ValueError("GITHUB_OUTPUT is not an absolute path") + files.append_bytes(target, output_line(name, value).encode("utf-8", errors="strict")) diff --git a/agent-review/tests/lib.sh b/agent-review/tests/lib.sh index f66b335..205ffab 100755 --- a/agent-review/tests/lib.sh +++ b/agent-review/tests/lib.sh @@ -6,6 +6,39 @@ TESTS_FAILED=0 # shellcheck disable=SC2034 # used by the test scripts BIN_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../bin" && pwd) +# The first line of every Python entry point (ENTRY_TEMPLATE in +# workflow_structure.py, which also checks the rest of the file). +PYTHON_ENTRY_MARKER="# agent-review Python entry point: run only as '/usr/bin/python3 -I -S -B /bin/'." + +# Sets ENTRY_CMD to the production command line of a bin/ entry point, +# '/usr/bin/python3 -I -S -B '; a file without the marker above is an +# error. Builtins and absolute paths only: some tests put fake tools first +# on PATH. +entry_command() { # file + local first="" + IFS= read -r first <"$1" || [ -n "${first}" ] || { + echo "entry_command: cannot read '$1'" >&2 + return 1 + } + case "${first}" in + "${PYTHON_ENTRY_MARKER}") ENTRY_CMD=(/usr/bin/python3 -I -S -B "$1") ;; + *) + echo "entry_command: '$1' is not a Python entry point" >&2 + return 1 + ;; + esac +} + +# Runs a bin/ entry point with its production command line (entry_command). +# For a wrapper such as 'timeout', which cannot run a function, call +# entry_command and run "${ENTRY_CMD[@]}" instead. +run_entry() { # file args... + local -a ENTRY_CMD=() + entry_command "$1" || return 1 + shift + "${ENTRY_CMD[@]}" "$@" +} + fail() { echo " FAIL: $*" TESTS_FAILED=$((TESTS_FAILED + 1)) diff --git a/agent-review/tests/python/test_authorize.py b/agent-review/tests/python/test_authorize.py new file mode 100644 index 0000000..9f9e086 --- /dev/null +++ b/agent-review/tests/python/test_authorize.py @@ -0,0 +1,612 @@ +"""agent_review.authorize: the validators, splitting inputs and command output, and the decision. + +The black-box cases are in tests/test-authorize.sh, the specification of +the entry point; these test each piece, with the traps of Python's looser +defaults (docs/adr/0004-python-runtime.md, Context), and the entry point +in a hostile environment. +""" + +import os +import pathlib +import re +import subprocess + +import pytest + +from agent_review import authorize, validate +from agent_review.authorize import Fail, Skip + +AR_DIR = pathlib.Path(__file__).resolve().parents[2] +CSCS = "https://api.inference.cscs.ch/v1" +HEAD, BASE = "a" * 40, "b" * 40 + + +# --- Reading the environment --------------------------------------------------- + + +def test_unset_is_empty_and_values_are_kept_as_they_are() -> None: + env = authorize.read_environment({b"REPO": b" a/b\n", b"OTHER": b"x"}) + assert env["REPO"] == " a/b\n" + assert env["IN_PR"] == "" + assert set(env) == set(authorize.VARIABLES) + + +def test_values_that_are_not_utf8_fail() -> None: + with pytest.raises(Fail, match="IN_MODEL is not valid UTF-8"): + authorize.read_environment({b"IN_MODEL": b"x\xff"}) + with pytest.raises(Fail, match="REPO"): + authorize.read_environment({b"REPO": b"\xed\xa0\x80"}) # an encoded surrogate + + +# --- Shell semantics ------------------------------------------------------------------ + + +@pytest.mark.parametrize( + ("text", "want"), + [ + (" a ", "a"), + ("\t\r\n\v\fa\f\v\n\r\t", "a"), + (" ", ""), + ("a b", "a b"), + # Not [:space:] in the C locale: kept, so the entry is invalid. + ("\u3000a", "\u3000a"), + ("a\u00a0", "a\u00a0"), + ("\x1ca\x1f", "\x1ca\x1f"), + ("\u2028a\x85", "\u2028a\x85"), + ], +) +def test_trim_is_ascii_only(text: str, want: str) -> None: + assert authorize.trim(text) == want + # str.strip() would remove the non-ASCII ones. + if want != text.strip(): + assert text.strip() != authorize.trim(text) + + +@pytest.mark.parametrize( + ("text", "lines"), + [ + ("", [""]), + ("a", ["a"]), + ("a\n", ["a", ""]), + ("a\r\nb", ["a\r", "b"]), + ("a\x0bb\x0cc\x1cd\x85e\u2028f", ["a\x0bb\x0cc\x1cd\x85e\u2028f"]), + ], +) +def test_heredoc_lines_split_on_lf_only(text: str, lines: list[str]) -> None: + assert authorize.heredoc_lines(text) == lines + + +@pytest.mark.parametrize( + ("text", "count"), [("", 0), ("\n", 0), ("a", 1), ("a\n", 1), ("a\n ", 2), ("\r", 1), ("a\n\nb", 2)] +) +def test_count_nonempty_lines_is_grep_c_dot(text: str, count: int) -> None: + assert authorize.count_nonempty_lines(text) == count + + +@pytest.mark.parametrize( + ("stdout", "want"), + [ + (b"write\n", "write"), + (b"write\n\n\n", "write"), + (b"write\r\n", "write\r"), + (b" write \n", " write "), + (b"\nwrite", "\nwrite"), + (b"wr\0ite\n", "wr\0ite"), # the NUL is kept, so it never matches "write" + (b"write\xff", "write\ufffd"), + ], +) +def test_command_output_strips_trailing_newlines_only(stdout: bytes, want: str) -> None: + assert authorize.command_output(stdout) == want + + +@pytest.mark.parametrize( + ("text", "fields"), + [ + (f"{HEAD}\t{BASE}", (HEAD, BASE)), + (f" {HEAD} \t {BASE} ", (HEAD, BASE)), + (f"{HEAD}\t{BASE}\tx", (HEAD, f"{BASE}\tx")), + (f"{HEAD}\t{BASE}\nx\ty", (HEAD, BASE)), + (f"{HEAD}\r\t{BASE}", (f"{HEAD}\r", BASE)), + (f"{HEAD}\t{BASE}\r", (HEAD, f"{BASE}\r")), + (f"{HEAD}\x0b{BASE}", (f"{HEAD}\x0b{BASE}", "")), + (f"{HEAD}", (HEAD, "")), + (f"\n{HEAD}\t{BASE}", ("", "")), + ("", ("", "")), + ], +) +def test_read_two_fields(text: str, fields: tuple[str, str]) -> None: + assert authorize.read_two_fields(text) == fields + + +# --- Validators ------------------------------------------------------------------------- + +GOOD_PATHS = ["AGENTS.md", "src/pkg/AGENTS.md", "_x", ".github/x.md", "x" * 200, "a.b..md"[:3]] +BAD_PATHS = [ + "", + "/etc/passwd", + "../x", + "a..b", + "docs/../x", + "a//b", + "./a", + "a/./b", + "a/.", + ".", + "..", + "a/", + "-rf", + "a b", + "*.md", + ":(glob)x", + "x" * 201, + "a\nb", + "a\r", + "\u00e9", + "\uff41", + "a?ref=main", + "x%2f.md", +] + + +@pytest.mark.parametrize("entry", GOOD_PATHS) +def test_check_path_accepts(entry: str) -> None: + authorize.check_path("rule_files", entry, False) + + +@pytest.mark.parametrize("entry", BAD_PATHS) +def test_check_path_rejects(entry: str) -> None: + with pytest.raises(Fail, match=re.escape(f"Invalid entry in rule_files: '{entry}'.")): + authorize.check_path("rule_files", entry, False) + + +@pytest.mark.parametrize("entry", ["*.md", "docs/", "docs/**/*.mdc", "**/AGENTS.md", "*"]) +def test_check_path_glob_accepts(entry: str) -> None: + authorize.check_path("instruction_files", entry, True) + + +@pytest.mark.parametrize("entry", ["docs//", "/docs/", "a/./b/", "../x/", "docs/**/../x", "/", "a?", "[a]"]) +def test_check_path_glob_rejects(entry: str) -> None: + with pytest.raises(Fail, match="Invalid entry in instruction_files"): + authorize.check_path("instruction_files", entry, True) + + +def test_check_list_skips_blanks_and_comments_and_trims() -> None: + authorize.check_list("rule_files", "# a comment\n\n AGENTS.md \r\nsrc/AGENTS.md\n \t\n # x/../y", False) + with pytest.raises(Fail, match=re.escape("'../y'")): + authorize.check_list("rule_files", "AGENTS.md\n../y", False) + with pytest.raises(Fail, match=re.escape("'\u3000AGENTS.md'")): + authorize.check_list("rule_files", "\u3000AGENTS.md", False) + + +@pytest.mark.parametrize("text", ["", "a.md", " a.md\n", "\n\na.md\r\n", "\n\ta.md \n"]) +def test_check_addendum_accepts(text: str) -> None: + authorize.check_addendum(text) + + +@pytest.mark.parametrize( + ("text", "message"), + [ + ("a.md\nb.md", "takes one path"), + ("a.md\n ", "takes one path"), + ("a.md\n\r", "takes one path"), + ("\r\na.md", "takes one path"), # the CR is a character on its own line + (" ", "Invalid entry in prompt_addendum: ''"), + ("\n", "Invalid entry in prompt_addendum: ''"), + ("# comment", "Invalid entry in prompt_addendum"), + ("#../../user", "Invalid entry in prompt_addendum"), + ], +) +def test_check_addendum_rejects(text: str, message: str) -> None: + with pytest.raises(Fail, match=re.escape(message)): + authorize.check_addendum(text) + + +@pytest.mark.parametrize(("value", "maximum"), [("1", 30), ("30", 30), ("9", 100), ("100", 100)]) +def test_check_cap_accepts(value: str, maximum: int) -> None: + authorize.check_cap("requests_per_minute", value, maximum) + + +@pytest.mark.parametrize( + "value", + [ + *["0", "31", "01", "00", "-1", "+1", "1.0", "1e1", "1_0", "0x1", " 5", "5 ", "5\n", "", "10000", "99999"], + *["\uff11", "\u0661", "1\uff11", "\u00b2", "\U0001d7cf"], + ], +) +def test_check_cap_rejects_what_int_accepts(value: str) -> None: + with pytest.raises(Fail, match=re.escape(f"Input requests_per_minute must be an integer in 1..30, got '{value}'.")): + authorize.check_cap("requests_per_minute", value, 30) + + +def test_key_mode() -> None: + assert authorize.key_mode("stub") is False + assert authorize.key_mode("opencode") is True + assert authorize.key_mode("pi") is True + with pytest.raises(Fail, match="No harness given"): + authorize.key_mode("") + for harness in ("Stub", "stub ", "pi\n", "memdoor"): + with pytest.raises(Fail, match="Unknown harness"): + authorize.key_mode(harness) + + +def test_check_shared_key() -> None: + authorize.check_shared_key("false") + with pytest.raises(Fail, match="readable in a job without an environment"): + authorize.check_shared_key("true") + for flag in ("", "True", "false ", "0"): + with pytest.raises(Fail, match="Invalid HAS_SHARED_KEY"): + authorize.check_shared_key(flag) + + +def test_choose_model() -> None: + assert authorize.choose_model(False, "anything at all", "stub") == "none" + assert authorize.choose_model(True, "zai-org/GLM-5.3-Flash", "pi") == "zai-org/GLM-5.3-Flash" + assert authorize.choose_model(True, "a" * 128, "pi") == "a" * 128 + with pytest.raises(Fail, match="No model given for harness 'pi'"): + authorize.choose_model(True, "", "pi") + for model in ("a" * 129, "-m", "/m", "a b", "m\n", "\u00e9"): + with pytest.raises(Fail, match="Invalid model id"): + authorize.choose_model(True, model, "pi") + + +def test_parse_api_bases_is_grep_v() -> None: + text = f"# comment\n\n{CSCS}\n #not a comment\nhttps://b/v1\r\nlast" + assert authorize.parse_api_bases(text) == [CSCS, " #not a comment", "https://b/v1\r", "last"] + assert authorize.parse_api_bases("") == [] + assert authorize.parse_api_bases("\n# x\n") == [] + + +def test_choose_api_base_is_an_exact_entry() -> None: + allowed = [CSCS, "https://b/v1"] + assert authorize.choose_api_base("", allowed) == CSCS + assert authorize.choose_api_base("https://b/v1", allowed) == "https://b/v1" + for value in (f"{CSCS}/", f" {CSCS}", CSCS.upper(), f"{CSCS}\n", "#" + CSCS): + with pytest.raises(Fail, match="is not an allowed inference endpoint"): + authorize.choose_api_base(value, allowed) + with pytest.raises(Fail, match="No allowed inference endpoint"): + authorize.choose_api_base(CSCS, []) + + +def test_the_real_api_bases_file() -> None: + assert authorize.load_api_bases(str(AR_DIR)) == [CSCS] + assert authorize.load_api_bases("/nonexistent") == [] + + +@pytest.mark.parametrize( + ("pattern", "good", "bad"), + [ + (authorize.LABEL, ["agent-review", "needs review: agent", "a" * 50], [" a", "a" * 51, "a\\b", "a\tb", ""]), + (authorize.ENVIRONMENT, ["agent-review", "a" * 64], ["-x", "a b", "a" * 65, "a/b"]), + ( + authorize.ACTOR, + ["actor", "dependabot[bot]", "a" * 39, "a" * 39 + "[bot]"], + ["a" * 40, "-x", "a_b", "[bot]", "a[bot]x", "a[bot][bot]", "a/b", "\u00e9"], + ), + ], +) +def test_patterns(pattern: re.Pattern[str], good: list[str], bad: list[str]) -> None: + assert all(validate.matches(pattern, v) for v in good) + assert not any(validate.matches(pattern, v) for v in bad) + assert not any(validate.matches(pattern, v + "\n") for v in good) + + +# --- The decision, with fake lookups ------------------------------------------------------ + + +def dispatch_env(**overrides: str) -> dict[str, str]: + env = dict.fromkeys(authorize.VARIABLES, "") + env.update( + REPO="example-org/example", + EVENT="workflow_dispatch", + ACTOR="actor", + IN_PR="7", + IN_HARNESS="opencode", + IN_MODEL="m", + IN_DRY_RUN="false", + IN_LABEL="agent-review", + IN_RULES="AGENTS.md", + IN_API_BASE=CSCS, + IN_RPH="100", + IN_RPM="30", + IN_TURNS="80", + IN_TIMEOUT="20", + IN_ENVIRONMENT="agent-review", + TRUSTED_REPO="GridTools/ci-workflows", + TRUSTED_SHA="c" * 40, + HAS_SHARED_KEY="false", + ) + env.update(overrides) + return env + + +class Lookups: + def __init__(self, shas: tuple[str, str] = (HEAD, BASE), level: str = "write") -> None: + self.shas, self.level = shas, level + self.calls: list[tuple[str, str, str]] = [] + self.notices: list[str] = [] + + def pr_shas(self, repo: str, number: str) -> tuple[str, str]: + self.calls.append(("pr", repo, number)) + return self.shas + + def permission(self, repo: str, actor: str) -> str: + self.calls.append(("permission", repo, actor)) + return self.level + + def decide(self, env: dict[str, str]) -> dict[str, str]: + return dict(authorize.decide(env, lambda: [CSCS], self.notices.append, self.pr_shas, self.permission)) + + +def test_decide_dispatch() -> None: + lookups = Lookups() + out = lookups.decide(dispatch_env()) + assert re.fullmatch(r"[0-9a-f]{16}", out.pop("call_id")) + assert out == { + "allowed": "true", + "keyed": "true", + "pr": "7", + "head_sha": HEAD, + "base_sha": BASE, + "harness": "opencode", + "model": "m", + "dry_run": "false", + "project": "example", + "api_base": CSCS, + "source_repo": "example-org/example", + "trusted_repo": "GridTools/ci-workflows", + "trusted_sha": "c" * 40, + } + assert lookups.calls == [("pr", "example-org/example", "7"), ("permission", "example-org/example", "actor")] + + +def test_static_inputs_fail_before_any_lookup() -> None: + lookups = Lookups() + with pytest.raises(Fail, match="Invalid environment"): + lookups.decide(dispatch_env(IN_ENVIRONMENT="-x")) + assert lookups.calls == [] + + +def test_a_denied_writer_skips_before_the_shas_are_checked() -> None: + # The writer is checked before the pinned shas (an order test-authorize.sh + # pins): a bad sha from a denied actor is a skip, not an error. + lookups = Lookups(shas=("main", ""), level="read") + with pytest.raises(Skip, match="actor has 'read' permission; skipping"): + lookups.decide(dispatch_env()) + lookups = Lookups(shas=("main", "")) + with pytest.raises(Fail, match="Invalid head sha 'main'"): + lookups.decide(dispatch_env()) + + +@pytest.mark.parametrize("level", ["read", "triage", "maintain", "none", "", " write", "write\r", "Write", "wr\0ite"]) +def test_only_admin_and_write_pass(level: str) -> None: + with pytest.raises(Skip, match="permission; skipping"): + Lookups(level=level).decide(dispatch_env()) + + +def test_pull_request_target_actions() -> None: + base = dispatch_env( + EVENT="pull_request_target", + EVENT_PR="12", + EVENT_HEAD_SHA=HEAD, + EVENT_BASE_SHA=BASE, + EVENT_DRAFT="false", + AUTHOR="author", + SENDER="sender", + IN_PR="", + ) + lookups = Lookups() + assert lookups.decide({**base, "ACTION": "labeled", "EVENT_LABEL": "agent-review"})["pr"] == "12" + assert lookups.calls == [("permission", "example-org/example", "sender")] + for action in authorize.PR_ACTIONS_BY_AUTHOR: + lookups = Lookups() + lookups.decide({**base, "ACTION": action}) + assert lookups.calls == [("permission", "example-org/example", "author")] + with pytest.raises(Skip, match="Label 'agent-review ' does not request a review"): + Lookups().decide({**base, "ACTION": "labeled", "EVENT_LABEL": "agent-review "}) + with pytest.raises(Skip, match="Draft pull request"): + Lookups().decide({**base, "ACTION": "opened", "EVENT_DRAFT": "true"}) + for action in ("synchronize", "", "labeled ", "Opened"): + with pytest.raises(Skip, match="does not start a review"): + Lookups().decide({**base, "ACTION": action}) + + +@pytest.mark.parametrize("actor", ["a/b", "-x", "x[bot]x", "a" * 40, "a" * 40 + "[bot]"]) +def test_an_invalid_actor_fails_before_the_permission_lookup(actor: str) -> None: + lookups = Lookups() + with pytest.raises(Fail, match=re.escape(f"Invalid actor '{actor}'.")): + lookups.decide(dispatch_env(ACTOR=actor)) + assert [c[0] for c in lookups.calls] == ["pr"] + lookups = Lookups() + prt = dispatch_env( + EVENT="pull_request_target", + ACTION="labeled", + EVENT_LABEL="agent-review", + SENDER=actor, + EVENT_PR="12", + EVENT_HEAD_SHA=HEAD, + EVENT_BASE_SHA=BASE, + IN_PR="", + ) + with pytest.raises(Fail, match="Invalid actor"): + lookups.decide(prt) + assert lookups.calls == [] + + +def test_entry_point_invalid_actor_makes_no_permission_call(tmp_path: pathlib.Path) -> None: + result = run_entry(tmp_path, {"ACTOR": "a/b"}, tmp_path) + assert result.returncode == 1 + assert b"::error::Invalid actor 'a/b'." in result.stdout + assert "collaborators" not in (tmp_path / "gh.log").read_text() + + +def test_stub_events() -> None: + env = dispatch_env(EVENT="pull_request", IN_HARNESS="stub", IN_MODEL="", IN_PR="", EVENT_PR="12") + lookups = Lookups() + out = lookups.decide(env) + assert (out["dry_run"], out["keyed"], out["model"], out["pr"]) == ("true", "false", "none", "12") + assert [c[0] for c in lookups.calls] == ["pr"] + assert any("Caller test mode" in n for n in lookups.notices) + with pytest.raises(Fail, match="runs the 'stub' harness only, not 'pi'"): + Lookups().decide({**env, "IN_HARNESS": "pi", "IN_MODEL": "m"}) + for event in ("push", "schedule"): + with pytest.raises(Fail, match=f"Event '{event}' is for the self-test of GridTools/ci-workflows only"): + Lookups().decide({**env, "EVENT": event}) + out = Lookups().decide( + {**env, "EVENT": event, "REPO": "GridTools/ci-workflows", "IN_TEST_REPO": "other-org/other"} + ) + assert (out["source_repo"], out["dry_run"]) == ("other-org/other", "true") + for event in ("", "issue_comment", "PUSH"): + with pytest.raises(Fail, match="Unexpected event"): + Lookups().decide({**env, "EVENT": event}) + + +def test_test_repository_rule() -> None: + central = {"REPO": "GridTools/ci-workflows", "IN_TEST_REPO": "other-org/other"} + with pytest.raises(Fail, match="is for the self-test"): + Lookups().decide(dispatch_env(IN_TEST_REPO="other-org/other")) + with pytest.raises(Fail, match="is for the self-test"): + Lookups().decide(dispatch_env(**central)) # keyed + out = Lookups().decide(dispatch_env(IN_HARNESS="stub", **central)) + assert (out["source_repo"], out["dry_run"]) == ("other-org/other", "true") + for action in ("labeled", "opened"): + lookups = Lookups() + with pytest.raises(Fail, match="not supported under 'pull_request_target'"): + lookups.decide( + dispatch_env( + IN_HARNESS="stub", + EVENT="pull_request_target", + ACTION=action, + EVENT_LABEL="agent-review", + EVENT_PR="12", + EVENT_HEAD_SHA=HEAD, + EVENT_BASE_SHA=BASE, + IN_PR="", + **central, + ) + ) + assert lookups.calls == [] + with pytest.raises(Fail, match="Invalid test_repository"): + Lookups().decide(dispatch_env(IN_HARNESS="stub", REPO="GridTools/ci-workflows", IN_TEST_REPO="a/b/c")) + + +# --- Output and log helpers ----------------------------------------------------------------- + + +def test_shown_breaks_up_legacy_commands_and_shows_nul() -> None: + assert authorize.shown("Invalid label '##[error]x'") == "Invalid label '#\u200b#[error]x'" + assert authorize.shown("'wr\0ite'") == "'wr\\x00ite'" + + +def test_write_outputs(tmp_path: pathlib.Path) -> None: + out = tmp_path / "out" + authorize.write_outputs(str(out), [("allowed", "true"), ("pr", "7")]) + assert out.read_bytes() == b"allowed=true\npr=7\n" + for bad in ("a\nb", "a\rb"): + with pytest.raises(ValueError, match="line break"): + authorize.write_outputs(str(out), [("allowed", "true"), ("x", bad)]) + assert out.read_bytes() == b"allowed=true\npr=7\n" # nothing half-written + with pytest.raises(ValueError, match="absolute"): + authorize.write_outputs("out", [("allowed", "false")]) + + +# --- The entry point --------------------------------------------------------------------------- + +FAKE_GH = """#!/usr/bin/bash +echo "gh $*" >>"${FAKE_DIR}/gh.log" +case "$2" in + */pulls/*) printf '%s\\t%s\\n' "${FAKE_HEAD}" "${FAKE_BASE}" ;; + */collaborators/*/permission) printf -- "${FAKE_PERM}\\n" ;; + *) exit 1 ;; +esac +""" +PLANTED = ["json.py", "os.py", "re.py", "secrets.py", "sitecustomize.py", "agent_review/__init__.py"] + + +def run_entry(tmp_path: pathlib.Path, env: dict[str, str], cwd: pathlib.Path) -> subprocess.CompletedProcess[bytes]: + fakebin = tmp_path / "fakebin" + fakebin.mkdir(exist_ok=True) + (fakebin / "gh").write_text(FAKE_GH) + (fakebin / "gh").chmod(0o755) + full = { + **dispatch_env(), + "PATH": f"{fakebin}:/usr/bin:/bin", + "GITHUB_OUTPUT": str(tmp_path / "out"), + "FAKE_DIR": str(tmp_path), + "FAKE_HEAD": HEAD, + "FAKE_BASE": BASE, + "FAKE_PERM": "write", + **env, + } + return subprocess.run( + ["/usr/bin/python3", "-I", "-S", "-B", str(AR_DIR / "bin" / "authorize")], + env=full, + cwd=cwd, + capture_output=True, + timeout=60, + check=False, + ) + + +def test_entry_point_allows_in_a_hostile_environment(tmp_path: pathlib.Path) -> None: + markers = tmp_path / "markers" + markers.mkdir() + cwd = tmp_path / "cwd" + for rel in PLANTED: + path = cwd / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"open({str(markers / rel.replace('/', '-'))!r}, 'w').close()\n") + hostile = { + "PYTHONPATH": str(cwd), + "PYTHONSTARTUP": str(cwd / "json.py"), + "PYTHONHOME": str(cwd), + "PYTHONINSPECT": "1", + } + result = run_entry(tmp_path, hostile, cwd) + assert result.returncode == 0, result.stdout + result.stderr + assert result.stderr == b"" + assert not list(markers.iterdir()) + out = (tmp_path / "out").read_text() + assert out.startswith("allowed=true\nkeyed=true\npr=7\n") + assert (tmp_path / "gh.log").read_text().splitlines() == [ + "gh api repos/example-org/example/pulls/7 --jq [.head.sha, .base.sha] | @tsv", + "gh api repos/example-org/example/collaborators/actor/permission --jq .permission", + ] + + +@pytest.mark.parametrize( + ("env", "rc", "log"), + [ + # Values reach the log escaped: they cannot end the command. + ({"IN_MODEL": "m\n::warning::x%0A"}, 1, b"::error::Invalid model id 'm%0A::warning::x%250A'."), + ({"IN_LABEL": "x\r::error::y"}, 1, b"::error::Invalid label 'x%0D::error::y'."), + ({"IN_LABEL": "##[warning]x"}, 1, "::error::Invalid label '#\u200b#[warning]x'.".encode()), + ({"FAKE_PERM": "wr\\0ite", "FAKE_HEAD": HEAD}, 0, b"::notice::actor has 'wr\\x00ite' permission; skipping"), + ({"IN_MODEL": "\udcff"}, 1, b"::error::Variable IN_MODEL is not valid UTF-8."), + # 'read' skips the leading tab: the base sha becomes the head. + ({"FAKE_HEAD": ""}, 1, b"::error::Invalid base sha ''."), + ({"FAKE_HEAD": "main"}, 1, b"::error::Invalid head sha 'main'."), + ({"PATH": "/nonexistent"}, 1, b"::error::Could not resolve pull request example-org/example#7: 'gh: not found"), + ], +) +def test_entry_point_log_and_exit_codes(tmp_path: pathlib.Path, env: dict[str, str], rc: int, log: bytes) -> None: + result = run_entry(tmp_path, env, tmp_path) + assert result.returncode == rc, result.stdout + assert result.stderr == b"" + assert log in result.stdout + assert (tmp_path / "out").read_text() == "allowed=false\n" + + +def test_entry_point_without_github_output(tmp_path: pathlib.Path) -> None: + result = run_entry(tmp_path, {"GITHUB_OUTPUT": ""}, tmp_path) + assert result.returncode == 1 + assert b"::error::GITHUB_OUTPUT is not set." in result.stdout + assert not (tmp_path / "out").exists() + + +def test_entry_point_with_an_unwritable_output_fails(tmp_path: pathlib.Path) -> None: + (tmp_path / "target").write_text("") + os.symlink(tmp_path / "target", tmp_path / "out") + result = run_entry(tmp_path, {}, tmp_path) + assert result.returncode == 1 + assert b"::error::" in result.stdout + assert (tmp_path / "target").read_text() == "" # the symlink is not followed diff --git a/agent-review/tests/python/test_collect_result.py b/agent-review/tests/python/test_collect_result.py new file mode 100644 index 0000000..440eba3 --- /dev/null +++ b/agent-review/tests/python/test_collect_result.py @@ -0,0 +1,447 @@ +"""agent_review.collect_result: what may leave the sandbox workspace. + +The black-box cases are in tests/test-collect-result.sh; these add the +races and the cases it does not cover, and run the entry point in a +hostile environment with real inputs. +""" + +import os +import pathlib +import socket +import subprocess +from typing import Any + +import pytest + +from agent_review import collect_result + +AR_DIR = pathlib.Path(__file__).resolve().parents[2] +ENTRY = AR_DIR / "bin" / "collect-result" +REVIEW = b"a review\n" +META = b'{"status": "ok"}\n' + + +@pytest.fixture +def ws(tmp_path: pathlib.Path) -> pathlib.Path: + """A workspace with ws/out/{review.md,meta.json} and a planted payload.""" + out = tmp_path / "ws" / "out" + out.mkdir(parents=True) + (out / "review.md").write_bytes(REVIEW) + (out / "meta.json").write_bytes(META) + (out / "payload.sh").write_bytes(b"evil\n") + return tmp_path + + +def run(capsys: pytest.CaptureFixture[str], *args: str) -> tuple[int, str, str]: + rc = collect_result.main(list(args)) + captured = capsys.readouterr() + return rc, captured.out, captured.err + + +def collect(capsys: pytest.CaptureFixture[str], root: pathlib.Path, src: str | None = None) -> tuple[int, str]: + rc, out, err = run(capsys, src or str(root / "ws" / "out"), str(root / "dest")) + assert err == "" + return rc, out + + +def dest_files(root: pathlib.Path) -> dict[str, bytes]: + return {p.name: p.read_bytes() for p in (root / "dest").iterdir()} + + +def warning(message: str) -> str: + return f"::warning title=Agent review result::{message}\n" + + +def test_copies_only_the_expected_files(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + rc, out = collect(capsys, ws) + assert rc == 0 + assert out == f"Collected 'review.md' ({len(REVIEW)} bytes).\nCollected 'meta.json' ({len(META)} bytes).\n" + assert dest_files(ws) == {"review.md": REVIEW, "meta.json": META} + + +@pytest.mark.parametrize("args", [[], ["a"], ["a", "b", "c"]]) +def test_usage(args: list[str], capsys: pytest.CaptureFixture[str]) -> None: + assert run(capsys, *args) == (1, "", "Usage: collect-result \n") + + +def test_dest_is_created_even_without_a_source(tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + rc, out = collect(capsys, tmp_path) + assert rc == 0 + src = tmp_path / "ws" / "out" + assert out == warning(f"'{src}' is missing, not a directory, or reached through a symlink; nothing collected.") + assert dest_files(tmp_path) == {} + + +def test_symlinked_out_dir(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "ws" / "out").rename(ws / "elsewhere") + (ws / "ws" / "out").symlink_to(ws / "elsewhere") + rc, out = collect(capsys, ws) + assert rc == 0 + assert "reached through a symlink; nothing collected." in out + assert dest_files(ws) == {} + + +def test_symlinked_parent(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "ws").rename(ws / "real") + (ws / "ws").symlink_to(ws / "real") + rc, out = collect(capsys, ws) + assert rc == 0 + assert "reached through a symlink; nothing collected." in out + assert dest_files(ws) == {} + + +def test_out_dir_that_is_a_file(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + rc, out = collect(capsys, ws, str(ws / "ws" / "out" / "review.md")) + assert rc == 0 + assert "nothing collected." in out + assert dest_files(ws) == {} + + +@pytest.mark.parametrize("suffix", ["/", "/.", "/../out", "//", ""]) +def test_source_must_be_canonical( + suffix: str, ws: pathlib.Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + src = str(ws / "ws" / "out") + suffix if suffix else "ws/out" + monkeypatch.chdir(ws) + rc, out = collect(capsys, ws, src) + assert rc == 0 + assert "nothing collected." in out + assert dest_files(ws) == {} + + +def test_out_dir_swapped_for_a_symlink_after_it_was_opened( + ws: pathlib.Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + """The directory is used through its descriptor, never by path again.""" + (ws / "elsewhere").mkdir() + (ws / "elsewhere" / "review.md").write_bytes(b"secret\n") + real_open_source = collect_result.open_source + + def open_then_swap(src: str) -> int | None: + fd = real_open_source(src) + (ws / "ws" / "out").rename(ws / "ws" / "old") + (ws / "ws" / "out").symlink_to(ws / "elsewhere") + return fd + + monkeypatch.setattr(collect_result, "open_source", open_then_swap) + rc, _ = collect(capsys, ws) + assert rc == 0 + assert dest_files(ws) == {"review.md": REVIEW, "meta.json": META} + + +def test_parent_swapped_for_a_symlink_during_the_walk( + ws: pathlib.Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + """Swapping a parent after it was opened changes nothing either.""" + (ws / "elsewhere" / "out").mkdir(parents=True) + (ws / "elsewhere" / "out" / "review.md").write_bytes(b"secret\n") + real_open_directory = collect_result.open_path_directory + + def open_then_swap(path: str, *, dir_fd: int | None = None) -> int: + fd = real_open_directory(path, dir_fd=dir_fd) + if path == "ws": + (ws / "ws").rename(ws / "old") + (ws / "ws").symlink_to(ws / "elsewhere") + return fd + + monkeypatch.setattr(collect_result, "open_path_directory", open_then_swap) + rc, _ = collect(capsys, ws) + assert rc == 0 + assert dest_files(ws) == {"review.md": REVIEW, "meta.json": META} + + +def test_file_swapped_for_a_symlink_between_check_and_open( + ws: pathlib.Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + """The lstat check passes, then review.md becomes a symlink: the open refuses it.""" + (ws / "secret").write_bytes(b"secret\n") + real_stat = os.stat + + def stat_then_swap(path: Any, *args: Any, **kwargs: Any) -> os.stat_result: + result = real_stat(path, *args, **kwargs) + if path == "review.md": + (ws / "ws" / "out" / "review.md").unlink() + (ws / "ws" / "out" / "review.md").symlink_to(ws / "secret") + return result + + monkeypatch.setattr(os, "stat", stat_then_swap) + rc, out = collect(capsys, ws) + assert rc == 0 + assert warning("'review.md' is missing or not a regular file; skipped.") in out + assert dest_files(ws) == {"meta.json": META} + + +def test_file_swapped_for_a_fifo_between_check_and_open( + ws: pathlib.Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + """fstat on the open descriptor catches what the lstat check missed, without blocking.""" + real_stat = os.stat + + def stat_then_swap(path: Any, *args: Any, **kwargs: Any) -> os.stat_result: + result = real_stat(path, *args, **kwargs) + if path == "review.md": + (ws / "ws" / "out" / "review.md").unlink() + os.mkfifo(ws / "ws" / "out" / "review.md") + return result + + monkeypatch.setattr(os, "stat", stat_then_swap) + rc, out = collect(capsys, ws) + assert rc == 0 + assert warning("'review.md' is missing or not a regular file; skipped.") in out + assert dest_files(ws) == {"meta.json": META} + + +def test_file_growing_past_the_cap_while_read( + ws: pathlib.Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + review = ws / "ws" / "out" / "review.md" + review.write_bytes(b"x" * collect_result.MAX_BYTES) + real_read = os.read + + def growing_read(fd: int, n: int) -> bytes: + with open(review, "ab") as f: + f.write(b"y") + return real_read(fd, n) + + monkeypatch.setattr(os, "read", growing_read) + rc, out = collect(capsys, ws) + assert rc == 0 + assert warning("'review.md' grew over the 65536-byte limit while reading; skipped.") in out + assert dest_files(ws) == {"meta.json": META} + + +@pytest.mark.skipif(os.geteuid() == 0, reason="root ignores permissions") +@pytest.mark.parametrize("directory", ["ws", "ws/out"]) +def test_search_only_directories(directory: str, ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + """Mode 0311 (search, no read): enough to reach the files, so they are collected.""" + (ws / directory).chmod(0o311) + try: + rc, out = collect(capsys, ws) + finally: + (ws / directory).chmod(0o755) + assert rc == 0 + assert out == f"Collected 'review.md' ({len(REVIEW)} bytes).\nCollected 'meta.json' ({len(META)} bytes).\n" + assert dest_files(ws) == {"review.md": REVIEW, "meta.json": META} + + +@pytest.mark.skipif(os.geteuid() == 0, reason="root ignores permissions") +@pytest.mark.parametrize("mode", [0o444, 0o000]) +def test_out_dir_without_search_permission(mode: int, ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + """Without search permission each file is refused on its own, with its own warning.""" + (ws / "ws" / "out").chmod(mode) + try: + rc, out = collect(capsys, ws) + finally: + (ws / "ws" / "out").chmod(0o755) + assert rc == 0 + assert out == ( + warning("'review.md' could not be read (Permission denied); skipped.") + + warning("'meta.json' could not be read (Permission denied); skipped.") + ) + assert dest_files(ws) == {} + + +def test_lstat_check_keeps_a_fifo_from_being_opened( + ws: pathlib.Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + (ws / "ws" / "out" / "review.md").unlink() + os.mkfifo(ws / "ws" / "out" / "review.md") + opened: list[object] = [] + real_open = os.open + + def recording_open(path: Any, *args: Any, **kwargs: Any) -> int: + opened.append(path) + return real_open(path, *args, **kwargs) + + monkeypatch.setattr(os, "open", recording_open) + rc, out = collect(capsys, ws) + assert rc == 0 + assert out.startswith(warning("'review.md' is missing or not a regular file; skipped.")) + assert "review.md" not in opened + assert "meta.json" in opened # the recording works + + +def test_size_limit(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "ws" / "out" / "review.md").write_bytes(b"x" * collect_result.MAX_BYTES) + (ws / "ws" / "out" / "meta.json").write_bytes(b"x" * (collect_result.MAX_BYTES + 1)) + rc, out = collect(capsys, ws) + assert rc == 0 + assert out == ( + "Collected 'review.md' (65536 bytes).\n" + + warning("'meta.json' is 65537 bytes, over the 65536-byte limit; skipped.") + ) + assert dest_files(ws) == {"review.md": b"x" * collect_result.MAX_BYTES} + + +def test_directory_named_review_md(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "ws" / "out" / "review.md").unlink() + (ws / "ws" / "out" / "review.md").mkdir() + (ws / "ws" / "out" / "review.md" / "x").write_bytes(b"x") + rc, out = collect(capsys, ws) + assert rc == 0 + assert out.startswith(warning("'review.md' is missing or not a regular file; skipped.")) + assert dest_files(ws) == {"meta.json": META} + + +def test_socket(ws: pathlib.Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch) -> None: + (ws / "ws" / "out" / "review.md").unlink() + monkeypatch.chdir(ws / "ws" / "out") # AF_UNIX paths are short + with socket.socket(socket.AF_UNIX) as s: + s.bind("review.md") + rc, out = collect(capsys, ws) + assert rc == 0 + assert out.startswith(warning("'review.md' is missing or not a regular file; skipped.")) + assert dest_files(ws) == {"meta.json": META} + + +def test_hard_link(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "hostfile").write_bytes(b"host file\n") + (ws / "ws" / "out" / "review.md").unlink() + os.link(ws / "hostfile", ws / "ws" / "out" / "review.md") + rc, out = collect(capsys, ws) + assert rc == 0 + assert out.startswith(warning("'review.md' has 2 hard links; skipped.")) + assert dest_files(ws) == {"meta.json": META} + + +@pytest.mark.skipif(os.geteuid() == 0, reason="root reads mode-000 files") +def test_unreadable_file_is_skipped(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "ws" / "out" / "review.md").chmod(0) + rc, out = collect(capsys, ws) + assert rc == 0 + assert out.startswith(warning("'review.md' could not be read (Permission denied); skipped.")) + assert dest_files(ws) == {"meta.json": META} + + +def test_non_utf8_content_is_copied_as_bytes(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + data = b"\xff\xfe\x00 not UTF-8 \xc3\x28\r\n::error::x\n" + (ws / "ws" / "out" / "review.md").write_bytes(data) + rc, _ = collect(capsys, ws) + assert rc == 0 + assert dest_files(ws)["review.md"] == data + + +def test_empty_file(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "ws" / "out" / "review.md").write_bytes(b"") + rc, out = collect(capsys, ws) + assert rc == 0 + assert out.startswith("Collected 'review.md' (0 bytes).\n") + assert dest_files(ws)["review.md"] == b"" + + +def test_existing_dest_files_are_replaced(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "dest").mkdir() + (ws / "dest" / "review.md").write_bytes(b"old") + collect(capsys, ws) + assert dest_files(ws)["review.md"] == REVIEW + + +def test_planted_tmp_symlink_in_dest_is_not_followed(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "target").write_bytes(b"untouched") + (ws / "dest").mkdir() + (ws / "dest" / "review.md.tmp").symlink_to(ws / "target") + (ws / "dest" / "meta.json").symlink_to(ws / "target") + rc, _ = collect(capsys, ws) + assert rc == 0 + assert (ws / "target").read_bytes() == b"untouched" + assert dest_files(ws) == {"review.md": REVIEW, "meta.json": META} + assert not (ws / "dest" / "meta.json").is_symlink() + + +def test_dest_that_is_a_symlink_fails(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "elsewhere").mkdir() + (ws / "dest").symlink_to(ws / "elsewhere") + rc, out, err = run(capsys, str(ws / "ws" / "out"), str(ws / "dest")) + assert rc == 1 + assert out == "" + assert err.startswith(f"collect-result: cannot use '{ws / 'dest'}' as the destination: ") + assert list((ws / "elsewhere").iterdir()) == [] + + +def test_dest_write_error_fails(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "dest" / "review.md.tmp").mkdir(parents=True) + rc, out, err = run(capsys, str(ws / "ws" / "out"), str(ws / "dest")) + assert rc == 1 + assert out == "" + assert err.startswith(f"collect-result: cannot write 'review.md' to '{ws / 'dest'}': ") + + +def test_failed_rename_leaves_no_tmp(ws: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + (ws / "dest" / "review.md").mkdir(parents=True) + rc, _, err = run(capsys, str(ws / "ws" / "out"), str(ws / "dest")) + assert rc == 1 + assert err.startswith("collect-result: cannot write 'review.md'") + assert sorted(p.name for p in (ws / "dest").iterdir()) == ["review.md"] + assert (ws / "dest" / "review.md").is_dir() + + +def test_warning_data_is_escaped(tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + src = str(tmp_path / "a%0A::error::b\nc") + rc, out, _ = run(capsys, src, str(tmp_path / "dest")) + assert rc == 0 + assert out.count("\n") == 1 + assert "a%250A::error::b%0Ac" in out + + +def test_undecodable_argument(tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: + src = os.fsdecode(bytes(tmp_path) + b"/\xff") + rc, out, _ = run(capsys, src, str(tmp_path / "dest")) + assert rc == 0 + assert "\\xff' is missing" in out + + +# --- The entry point, as the workflow runs it, in a hostile environment ------ + + +def plant(directory: pathlib.Path, markers: pathlib.Path, names: list[str]) -> None: + for name in names: + path = directory / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"open({str(markers / (directory.name + '-' + name.replace('/', '-')))!r}, 'w').close()\n") + + +def test_entry_point_in_a_hostile_environment(ws: pathlib.Path) -> None: + markers = ws / "markers" + markers.mkdir() + cwd = ws / "ws" / "out" # the sandbox could write here + modules = ["json.py", "os.py", "stat.py", "errno.py", "sitecustomize.py", "agent_review/__init__.py"] + plant(cwd, markers, modules) + plant(ws / "pythonpath", markers, [*modules, "startup.py"]) + tools = ws / "bin" + tools.mkdir() + for tool in ("python3", "head", "stat", "mv", "mkdir", "realpath"): + (tools / tool).write_text(f"#!/bin/sh\ntouch {markers / ('tool-' + tool)}\n") + (tools / tool).chmod(0o755) + env = { + **os.environ, + "PATH": f"{tools}:{os.environ.get('PATH', '/usr/bin:/bin')}", + "PYTHONPATH": str(ws / "pythonpath"), + "PYTHONSTARTUP": str(ws / "pythonpath" / "startup.py"), + "PYTHONINSPECT": "1", + } + result = subprocess.run( + ["/usr/bin/python3", "-I", "-S", "-B", str(ENTRY), str(ws / "ws" / "out"), str(ws / "dest")], + cwd=cwd, + env=env, + capture_output=True, + timeout=60, + check=False, + ) + assert result.returncode == 0, result.stderr + assert result.stderr == b"" + assert sorted(p.name for p in markers.iterdir()) == [] + assert dest_files(ws) == {"review.md": REVIEW, "meta.json": META} + + +def test_entry_point_does_not_block_on_a_fifo(ws: pathlib.Path) -> None: + (ws / "ws" / "out" / "review.md").unlink() + os.mkfifo(ws / "ws" / "out" / "review.md") + result = subprocess.run( + ["/usr/bin/python3", "-I", "-S", "-B", str(ENTRY), str(ws / "ws" / "out"), str(ws / "dest")], + capture_output=True, + timeout=20, + check=False, + ) + assert result.returncode == 0 + assert b"'review.md' is missing or not a regular file; skipped." in result.stdout + assert dest_files(ws) == {"meta.json": META} diff --git a/agent-review/tests/python/test_entry_points.py b/agent-review/tests/python/test_entry_points.py new file mode 100644 index 0000000..e3cb193 --- /dev/null +++ b/agent-review/tests/python/test_entry_points.py @@ -0,0 +1,197 @@ +"""The Python entry points under the production command line, in a hostile environment. + +pytest imports agent_review without '-I -S', so these tests run each entry +point as a subprocess, exactly as the workflow does +('/usr/bin/python3 -I -S -B /bin/'), with PYTHONPATH, +PYTHONSTARTUP, PYTHONHOME and PYTHONUSERBASE pointing at planted code and +from a working directory holding 'json.py', 'agent_review/' and +'sitecustomize.py'. Every planted module leaves a marker file if imported. +The entry points are found from the files (workflow_structure.entry_kind), +not from a list. +""" + +import os +import pathlib +import re +import shutil +import subprocess + +import pytest + +from workflow_structure import entry_kind + +AR_DIR = pathlib.Path(__file__).resolve().parents[2] +BIN_DIR = AR_DIR / "bin" +PYTHON_CALL = ["/usr/bin/python3", "-I", "-S", "-B"] +PYTHON_ENTRIES = sorted( + p.name for p in BIN_DIR.iterdir() if entry_kind(p.name, p.read_text(encoding="utf-8")) == "python" +) +PLANTED = [ + "json.py", + "os.py", + "re.py", + "sitecustomize.py", + "usercustomize.py", + "agent_review/__init__.py", + "agent_review/probe.py", + "encodings/__init__.py", +] +PROBE_LINE = re.compile( + r"agent-review-probe python=3\.[0-9]+\.[0-9]+ executable=/usr/bin/python3 isolated=1 ignore_environment=1" + r" no_user_site=1 no_site=1 dont_write_bytecode=1 safe_path=1 site=0 stdlib_only=1 lib=(?P/\S+)\n", + re.ASCII, +) + + +def plant(directory: pathlib.Path, markers: pathlib.Path) -> None: + """Modules that write a marker named after themselves when imported.""" + for rel in PLANTED: + path = directory / rel + path.parent.mkdir(parents=True, exist_ok=True) + tag = f"{directory.name}-{rel.replace('/', '-')}" + path.write_text(f"open({str(markers / tag)!r}, 'w').close()\nmain = lambda: 0\n") + + +@pytest.fixture +def hostile(tmp_path: pathlib.Path) -> tuple[pathlib.Path, dict[str, str], pathlib.Path]: + """(working directory, environment, marker directory).""" + markers = tmp_path / "markers" + markers.mkdir() + cwd, pythonpath, home, userbase = (tmp_path / n for n in ("cwd", "pythonpath", "home", "userbase")) + for directory in (cwd, pythonpath): + plant(directory, markers) + plant(home / "lib" / "python3.12", markers) + plant(userbase / "lib" / "python3.12" / "site-packages", markers) + (pythonpath / "startup.py").write_text(f"open({str(markers / 'startup')!r}, 'w').close()\n") + env = { + **os.environ, + "PYTHONPATH": f"{pythonpath}:{cwd}", + "PYTHONSTARTUP": str(pythonpath / "startup.py"), + "PYTHONHOME": str(home), + "PYTHONUSERBASE": str(userbase), + "PYTHONINSPECT": "1", + "PYTHONSAFEPATH": "", + } + return cwd, env, markers + + +def test_there_is_a_python_entry_point() -> None: + assert "probe" in PYTHON_ENTRIES + + +@pytest.mark.parametrize("name", PYTHON_ENTRIES) +def test_hostile_environment_loads_nothing( + name: str, hostile: tuple[pathlib.Path, dict[str, str], pathlib.Path] +) -> None: + cwd, env, markers = hostile + result = subprocess.run( + [*PYTHON_CALL, str(BIN_DIR / name)], cwd=cwd, env=env, capture_output=True, timeout=60, check=False + ) + # The entry point got past its flag guard, so the test is not vacuous. + assert b"run only as" not in result.stderr + assert sorted(p.name for p in markers.iterdir()) == [] + + +def test_probe_in_a_hostile_environment(hostile: tuple[pathlib.Path, dict[str, str], pathlib.Path]) -> None: + cwd, env, markers = hostile + result = subprocess.run( + [*PYTHON_CALL, str(BIN_DIR / "probe")], cwd=cwd, env=env, capture_output=True, timeout=60, check=False + ) + assert result.returncode == 0, result.stderr + assert result.stderr == b"" + m = PROBE_LINE.fullmatch(result.stdout.decode()) + assert m, result.stdout + assert m.group("lib") == str((AR_DIR / "lib").resolve()) + assert not list(markers.iterdir()) + + +def test_negative_control_the_plants_work(hostile: tuple[pathlib.Path, dict[str, str], pathlib.Path]) -> None: + """Without '-I -S' the same plants are imported: the test above can fail.""" + cwd, env, markers = hostile + # Each of these would stop the interpreter from starting at all. + del env["PYTHONHOME"] + del env["PYTHONINSPECT"] + for directory in env["PYTHONPATH"].split(":"): + shutil.rmtree(pathlib.Path(directory) / "encodings") + result = subprocess.run( + ["/usr/bin/python3", "-B", str(BIN_DIR / "probe")], + cwd=cwd, + env=env, + capture_output=True, + timeout=60, + check=False, + ) + fired = {p.name for p in markers.iterdir()} + assert "pythonpath-sitecustomize.py" in fired + assert "pythonpath-json.py" not in fired # the guard stopped it first + assert result.returncode == 2 + assert b"run only as '/usr/bin/python3 -I -S -B /bin/'" in result.stderr + + +@pytest.mark.parametrize("name", PYTHON_ENTRIES) +@pytest.mark.parametrize( + "flags", + [ + [], # nothing + ["-S", "-B"], # not isolated + ["-I", "-B"], # site imported + ["-I", "-S"], # bytecode written + ["-E", "-s", "-S", "-B"], # not isolated, no safe path + ["-E", "-s", "-P", "-S", "-B"], # all but '-I' itself + ], +) +def test_flag_guard(name: str, flags: list[str], tmp_path: pathlib.Path) -> None: + result = subprocess.run( + ["/usr/bin/python3", *flags, str(BIN_DIR / name)], cwd=tmp_path, capture_output=True, timeout=60, check=False + ) + assert result.returncode == 2 + assert result.stdout == b"" + assert b"run only as" in result.stderr + assert not list(tmp_path.iterdir()) + + +def test_symlinked_entry_point_finds_its_real_lib(tmp_path: pathlib.Path) -> None: + (tmp_path / "bin").mkdir() + (tmp_path / "bin" / "probe").symlink_to(BIN_DIR / "probe") + result = subprocess.run( + [*PYTHON_CALL, str(tmp_path / "bin" / "probe")], capture_output=True, timeout=60, check=False + ) + m = PROBE_LINE.fullmatch(result.stdout.decode()) + assert m and m.group("lib") == str((AR_DIR / "lib").resolve()) + + +def launcher(script: str, *args: str) -> subprocess.CompletedProcess[bytes]: + """Runs ``script`` in bash with tests/lib.sh sourced.""" + return subprocess.run( + ["/usr/bin/bash", "-c", f'. "$1"; shift; {script}', "bash", str(AR_DIR / "tests" / "lib.sh"), *args], + capture_output=True, + timeout=60, + check=False, + ) + + +def test_launcher_runs_python_entry_points_with_the_production_command_line(tmp_path: pathlib.Path) -> None: + result = launcher('run_entry "$1"', str(BIN_DIR / "probe")) + assert result.returncode == 0, result.stderr + assert PROBE_LINE.fullmatch(result.stdout.decode()) + result = launcher('entry_command "$1" && printf "%s\\n" "${ENTRY_CMD[@]}"', str(BIN_DIR / "probe")) + assert result.stdout.decode().splitlines() == [*PYTHON_CALL, str(BIN_DIR / "probe")] + + +@pytest.mark.parametrize("shebang", ["#!/usr/bin/env bash", "#!/usr/bin/bash"]) +def test_launcher_refuses_bash_scripts(shebang: str, tmp_path: pathlib.Path) -> None: + # bin/ holds only Python entry points: a bash script is not run at all. + script = tmp_path / "script" + script.write_text(f"{shebang}\necho ran\n") + result = launcher('run_entry "$1"', str(script)) + assert result.returncode == 1 + assert result.stdout == b"" + assert b"not a Python entry point" in result.stderr + + +def test_launcher_refuses_other_files(tmp_path: pathlib.Path) -> None: + for text in ["#!/usr/bin/python3\nprint(1)\n", "", "import sys\n"]: + (tmp_path / "x").write_text(text) + result = launcher('run_entry "$1"', str(tmp_path / "x")) + assert result.returncode == 1 + assert result.stdout == b"" diff --git a/agent-review/tests/python/test_files.py b/agent-review/tests/python/test_files.py new file mode 100644 index 0000000..696d6d2 --- /dev/null +++ b/agent-review/tests/python/test_files.py @@ -0,0 +1,138 @@ +"""agent_review.files: no symlinks followed, no blocking, bounded reads.""" + +import errno +import os +import pathlib + +import pytest + +from agent_review import files + + +def test_reads_a_regular_file(tmp_path: pathlib.Path) -> None: + (tmp_path / "f").write_bytes(b"data") + assert files.read_bytes(str(tmp_path / "f"), 4) == b"data" + + +def test_refuses_a_symlink(tmp_path: pathlib.Path) -> None: + (tmp_path / "real").write_bytes(b"secret") + (tmp_path / "link").symlink_to(tmp_path / "real") + with pytest.raises(OSError) as e: + files.read_bytes(str(tmp_path / "link"), 100) + assert e.value.errno == errno.ELOOP + + +def test_refuses_a_fifo_without_blocking(tmp_path: pathlib.Path) -> None: + os.mkfifo(tmp_path / "fifo") + with pytest.raises(files.UnsafeFileError, match="not a regular file"): + files.read_bytes(str(tmp_path / "fifo"), 100) + + +def test_refuses_a_directory(tmp_path: pathlib.Path) -> None: + with pytest.raises(files.UnsafeFileError, match="not a regular file"): + files.read_bytes(str(tmp_path), 100) + + +def test_refuses_a_device() -> None: + with pytest.raises(files.UnsafeFileError, match="not a regular file"): + files.read_bytes("/dev/zero", 100) + + +def test_size_cap(tmp_path: pathlib.Path) -> None: + (tmp_path / "f").write_bytes(b"x" * 11) + assert files.read_bytes(str(tmp_path / "f"), 11) == b"x" * 11 + with pytest.raises(files.UnsafeFileError, match="11 bytes, more than 10"): + files.read_bytes(str(tmp_path / "f"), 10) + + +def test_hard_links(tmp_path: pathlib.Path) -> None: + (tmp_path / "f").write_bytes(b"x") + os.link(tmp_path / "f", tmp_path / "g") + assert files.read_bytes(str(tmp_path / "f"), 1) == b"x" + with pytest.raises(files.UnsafeFileError, match="2 hard links"): + files.read_bytes(str(tmp_path / "f"), 1, single_link=True) + + +def test_dir_fd(tmp_path: pathlib.Path) -> None: + (tmp_path / "d").mkdir() + (tmp_path / "d" / "f").write_bytes(b"in d") + (tmp_path / "link").symlink_to(tmp_path / "d") + with pytest.raises(OSError): + files.open_directory(str(tmp_path / "link")) + fd = files.open_directory(str(tmp_path / "d")) + try: + assert files.read_bytes("f", 10, dir_fd=fd) == b"in d" + finally: + os.close(fd) + + +def test_read_text_is_strict_utf8(tmp_path: pathlib.Path) -> None: + (tmp_path / "ok").write_bytes("é\n".encode()) + assert files.read_text(str(tmp_path / "ok"), 10) == "é\n" + (tmp_path / "bad").write_bytes(b"\xff") + with pytest.raises(UnicodeDecodeError): + files.read_text(str(tmp_path / "bad"), 10) + + +def test_write_new(tmp_path: pathlib.Path) -> None: + files.write_new(str(tmp_path / "new"), b"x", mode=0o600) + assert (tmp_path / "new").read_bytes() == b"x" + assert (tmp_path / "new").stat().st_mode & 0o777 == 0o600 + with pytest.raises(FileExistsError): + files.write_new(str(tmp_path / "new"), b"y") + (tmp_path / "dangling").symlink_to(tmp_path / "target") + with pytest.raises(FileExistsError): + files.write_new(str(tmp_path / "dangling"), b"y") + assert not (tmp_path / "target").exists() + + +def test_append_refuses_a_symlink(tmp_path: pathlib.Path) -> None: + (tmp_path / "real").write_bytes(b"") + (tmp_path / "link").symlink_to(tmp_path / "real") + with pytest.raises(OSError): + files.append_bytes(str(tmp_path / "link"), b"x") + files.append_bytes(str(tmp_path / "real"), b"x") + files.append_bytes(str(tmp_path / "real"), b"y") + assert (tmp_path / "real").read_bytes() == b"xy" + + +def _reason(path: str, max_bytes: int, **kwargs: bool) -> str: + with pytest.raises(files.UnsafeFileError) as e: + files.read_bytes(path, max_bytes, **kwargs) + assert isinstance(e.value.st, os.stat_result) + return e.value.reason + + +def test_reasons(tmp_path: pathlib.Path) -> None: + os.mkfifo(tmp_path / "fifo") + (tmp_path / "f").write_bytes(b"x" * 11) + os.link(tmp_path / "f", tmp_path / "g") + assert _reason(str(tmp_path / "fifo"), 100) == "type" + assert _reason(str(tmp_path), 100) == "type" + assert _reason(str(tmp_path / "f"), 100, single_link=True) == "links" + assert _reason(str(tmp_path / "f"), 10) == "size" + + +def test_reason_grew(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A file that grows past the cap after the fstat check is refused.""" + (tmp_path / "f").write_bytes(b"x" * 10) + real_read = os.read + + def growing_read(fd: int, n: int) -> bytes: + with open(tmp_path / "f", "ab") as f: + f.write(b"y" * 10) + return real_read(fd, n) + + monkeypatch.setattr(os, "read", growing_read) + with pytest.raises(files.UnsafeFileError, match="more than 10 bytes") as e: + files.read_bytes(str(tmp_path / "f"), 10) + assert e.value.reason == "grew" + assert e.value.st is not None + assert e.value.st.st_size == 10 + + +def test_unsafe_file_error_old_form() -> None: + """Raising it with a message only still works; 'reason' is then 'other'.""" + e = files.UnsafeFileError("x: refused") + assert (str(e), e.reason, e.st) == ("x: refused", "other", None) + assert isinstance(e, OSError) diff --git a/agent-review/tests/python/test_gh.py b/agent-review/tests/python/test_gh.py new file mode 100644 index 0000000..162d62f --- /dev/null +++ b/agent-review/tests/python/test_gh.py @@ -0,0 +1,104 @@ +"""agent_review.gh: the 'gh api' argument order the suites' fakes rely on.""" + +import os +import pathlib + +import pytest + +from agent_review import gh, runner + + +@pytest.fixture +def fake_gh(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> pathlib.Path: + """A fake 'gh' first on PATH that logs its arguments (one per line) and stdin.""" + bindir = tmp_path / "fakebin" + bindir.mkdir() + script = bindir / "gh" + script.write_text( + "#!/bin/sh\n" + 'printf "%s\\n" "$@" >"${FAKE_DIR}/args"\n' + 'cat >"${FAKE_DIR}/stdin"\n' + '[ -z "${FAKE_FAIL:-}" ] || { echo "HTTP 502" >&2; exit 1; }\n' + '[ -z "${FAKE_WARN:-}" ] || echo "warning" >&2\n' + "echo answer\n" + ) + script.chmod(0o755) + monkeypatch.setenv("PATH", f"{bindir}:{os.environ['PATH']}") + monkeypatch.setenv("FAKE_DIR", str(tmp_path)) + return tmp_path + + +def args(directory: pathlib.Path) -> list[str]: + return (directory / "args").read_text().splitlines() + + +def test_get_with_jq(fake_gh: pathlib.Path) -> None: + out = gh.api("repos/o/r/pulls/7", jq="[.head.sha, .base.sha] | @tsv") + assert out == b"answer\n" + # test-authorize.sh's fake matches the endpoint as "$2". + assert args(fake_gh) == ["api", "repos/o/r/pulls/7", "--jq", "[.head.sha, .base.sha] | @tsv"] + assert (fake_gh / "stdin").read_bytes() == b"" + + +def test_paginate(fake_gh: pathlib.Path) -> None: + gh.api("repos/o/r/issues/9/comments?per_page=100", jq=".[]", paginate=True) + assert args(fake_gh) == ["api", "--paginate", "repos/o/r/issues/9/comments?per_page=100", "--jq", ".[]"] + + +def test_write_with_body(fake_gh: pathlib.Path) -> None: + gh.api("repos/o/r/issues/comments/11", method="PATCH", body=b'{"body": "x"}', jq=".html_url") + # test-publish-comment.sh's fake matches "api -X " and logs "$3 $4". + assert args(fake_gh) == ["api", "-X", "PATCH", "repos/o/r/issues/comments/11", "--input", "-", "--jq", ".html_url"] + assert (fake_gh / "stdin").read_bytes() == b'{"body": "x"}' + + +def test_failure(fake_gh: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("FAKE_FAIL", "1") + with pytest.raises(runner.CommandError) as e: + gh.api("repos/o/r/pulls/7") + assert e.value.stderr == b"HTTP 502\n" + + +def test_stderr_on_success(fake_gh: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("FAKE_WARN", "1") + assert gh.api("repos/o/r/pulls/7") == b"answer\n" + with pytest.raises(runner.CommandError, match="output on stderr") as e: + gh.api("repos/o/r/pulls/7", stderr_is_error=True) + assert e.value.returncode == 0 + assert e.value.stderr == b"warning\n" + monkeypatch.delenv("FAKE_WARN") + assert gh.api("repos/o/r/pulls/7", stderr_is_error=True) == b"answer\n" + + +@pytest.mark.parametrize( + "endpoint", + [ + "-X", + "--hostname=evil", + "https://evil.example/x", + "/repos/o/r", + "repos/o/r/../../user", + "repos//o", + "repos/o/r pulls", + "repos/o/r\n", + "repos/é", + "[::1]/repos", + "repos/o/r?q=[x]", + "", + ], +) +def test_endpoint_validation(fake_gh: pathlib.Path, endpoint: str) -> None: + with pytest.raises(ValueError, match="API endpoint"): + gh.api(endpoint) + assert not (fake_gh / "args").exists() + + +def test_bot_login_in_the_path(fake_gh: pathlib.Path) -> None: + # authorize checks the permission of a bot actor such as 'dependabot[bot]'. + gh.api("repos/o/r/collaborators/dependabot[bot]/permission", jq=".permission") + assert args(fake_gh) == ["api", "repos/o/r/collaborators/dependabot[bot]/permission", "--jq", ".permission"] + + +def test_method_validation(fake_gh: pathlib.Path) -> None: + with pytest.raises(ValueError, match="unsupported method"): + gh.api("repos/o/r", method="get") diff --git a/agent-review/tests/python/test_prompt.py b/agent-review/tests/python/test_prompt.py new file mode 100644 index 0000000..29f64f1 --- /dev/null +++ b/agent-review/tests/python/test_prompt.py @@ -0,0 +1,202 @@ +"""agent_review.prompt: the PR title and body as data, caps, nonce delimiters, bash-identical rendering.""" + +import json +import pathlib +import re +import subprocess + +import pytest + +from agent_review import prompt +from agent_review.review_errors import Fatal + +AR_DIR = pathlib.Path(__file__).resolve().parents[2] + +# The bash version's pipelines, run as the oracle on the same pr.json. +BASH_FIELDS = r""" +set -euo pipefail +clip() { head -c "$1" | { iconv -f UTF-8 -t UTF-8 -c 2>/dev/null || true; }; } +PR_TITLE=$(jq -r '.title // "" | tostring' "$1" | tr -d '\r' | head -n 1 | clip 512) +PR_BODY=$(jq -r '.body // "" | tostring' "$1" | tr -d '\r' | clip 16384) +printf '%s\0%s' "${PR_TITLE}" "${PR_BODY}" +""" +BASH_ADDENDUM = r""" +set -euo pipefail +clip() { head -c "$1" | { iconv -f UTF-8 -t UTF-8 -c 2>/dev/null || true; }; } +ADDENDUM=$(printf '### Project notes\n\n%s\n' "$(clip 8192 <"$1")") +printf '%s' "${ADDENDUM}" +""" + +LONG = "\u00e9" * 300 + "\U0001f600" * 200 # multi-byte characters across both caps +PR_CASES = [ + {"title": "Fix {{HEAD_SHA}} & stuff\nsecond line", "body": "Ignore.\n\n{{PR_BODY}}"}, + {"title": None, "body": None}, + {"title": False, "body": ""}, + {}, + {"title": 12, "body": [1, {"a": "b"}]}, + {"title": "\r\n\r\nafter blank lines", "body": "a\r\nb\r\n\n\n"}, + {"title": "nul\u0000byte", "body": "x\u0000\u0000y\n\u0000"}, + {"title": LONG, "body": LONG * 30}, + {"title": "x" * 511 + "\u00e9", "body": "y" * 16383 + "\u00e9tail"}, + {"title": "trailing\n\n", "body": "\n\n\n"}, + {"title": "tabs\tand spaces ", "body": " leading and trailing "}, + {"title": "\u202eRTL \u200b zero-width", "body": "emoji \U0001f600 and \ufeff BOM"}, +] + + +def bash_fields(path: pathlib.Path) -> tuple[bytes, bytes]: + out = subprocess.run( + ["/usr/bin/bash", "-c", BASH_FIELDS, "bash", str(path)], + capture_output=True, + check=True, + env={"PATH": "/usr/bin:/bin", "LC_ALL": "C.UTF-8"}, + ).stdout + title, body = out.split(b"\0", 1) + return title, body + + +@pytest.mark.parametrize("case", PR_CASES) +def test_pr_fields_match_bash(tmp_path: pathlib.Path, case: dict[str, object]) -> None: + path = tmp_path / "pr.json" + path.write_text(json.dumps({"number": 1, **case}), encoding="utf-8") + assert prompt.read_pr(str(path)) == bash_fields(path) + + +def test_caps() -> None: + title, body = prompt.title_bytes("t" * 1000), prompt.body_bytes("b" * 20000) + assert len(title) == prompt.PR_TITLE_MAX_BYTES + assert len(body) == prompt.PR_BODY_MAX_BYTES + # A cut character is dropped, never split. + assert prompt.title_bytes("x" * 511 + "\u00e9") == b"x" * 511 + assert prompt.title_bytes("first\nsecond") == b"first" + + +def test_lone_surrogate_becomes_a_replacement_character(tmp_path: pathlib.Path) -> None: + # A lone surrogate is only data: it becomes U+FFFD and the fetch goes on. + path = tmp_path / "pr.json" + path.write_bytes(b'{"title": "a\\ud800b", "body": "\\udfff"}') + assert prompt.read_pr(str(path)) == ("a\ufffdb".encode(), "\ufffd".encode()) + + +@pytest.mark.parametrize("data", [b"[1]", b"not json", b"[" * 100000]) +def test_bad_pr_json_fails(tmp_path: pathlib.Path, data: bytes) -> None: + path = tmp_path / "pr.json" + path.write_bytes(data) + with pytest.raises(Fatal): + prompt.read_pr(str(path)) + + +def test_pr_json_must_be_a_regular_file(tmp_path: pathlib.Path) -> None: + (tmp_path / "real.json").write_text('{"title": "x"}') + (tmp_path / "pr.json").symlink_to(tmp_path / "real.json") + with pytest.raises(Fatal, match="Cannot read the pull request"): + prompt.read_pr(str(tmp_path / "pr.json")) + + +@pytest.mark.parametrize( + "addendum", + [ + b"Test addendum: also follow `CODING_GUIDELINES.md`.\n", + b"no newline", + b"\n\n\n", + b"trailing\n\n\n", + b"a\0b\n", + b"\xc3\xa9" * 5000, # cut at 8192 bytes, in the middle of nothing + b"x" + b"\xc3\xa9" * 5000, # cut inside a character + b"bad \xff byte\n", + ], +) +def test_addendum_matches_bash(tmp_path: pathlib.Path, addendum: bytes) -> None: + path = tmp_path / "addendum.md" + path.write_bytes(addendum) + expected = subprocess.run( + ["/usr/bin/bash", "-c", BASH_ADDENDUM, "bash", str(path)], + capture_output=True, + check=True, + env={"PATH": "/usr/bin:/bin", "LC_ALL": "C.UTF-8"}, + ).stdout + assert prompt.addendum_bytes(addendum) == expected + + +def test_no_addendum() -> None: + assert prompt.addendum_bytes(b"") == b"" + + +def test_rules() -> None: + assert prompt.rules_bytes([]) == b"No project rule files are configured." + assert prompt.rules_bytes(["AGENTS.md", "CODING_GUIDELINES.md"]) == ( + b"1. `AGENTS.md`, if it exists.\n2. `CODING_GUIDELINES.md`, if it exists." + ) + + +def values(**changes: object) -> prompt.PromptValues: + base: dict[str, object] = { + "project": "Example", + "repo": "example-org/example", + "pr_number": "2983", + "head_sha": "a" * 40, + "base_sha": "b" * 40, + "merge_base": "c" * 40, + "rules": b"1. `AGENTS.md`, if it exists.", + "addendum": b"### Project notes\n\nnotes", + "title": b"Fix {{HEAD_SHA}}", + "body": b"{{PR_BODY}} {{NONCE}}", + } + base.update(changes) + return prompt.PromptValues(**base) # type: ignore[arg-type] + + +def test_render_real_template() -> None: + template = (AR_DIR / "prompt.md.tmpl").read_bytes() + nonce = prompt.new_nonce() + assert re.fullmatch("[0-9a-f]{24}", nonce) + out = prompt.render(template, values(), nonce).decode() + assert out.endswith("\n") and not out.endswith("\n\n") + assert "pull request to Example." in out + assert f"\nTitle: Fix {{{{HEAD_SHA}}}}\n\n{{{{PR_BODY}}}} {{{{NONCE}}}}\n" in out + assert out.count("{{") == 3 # only in the PR text + assert "1. `AGENTS.md`, if it exists." in out + assert "### Project notes\n\nnotes" in out + assert "`.agent-review-context/diff.patch`" in out + + +def test_render_strips_the_nonce_from_the_pr_text() -> None: + nonce = "0123456789abcdef01234567" + out = prompt.render( + b"<{{NONCE}}>{{PR_TITLE}}|{{PR_BODY}}", + values(title=nonce.encode(), body=b"x" + nonce.encode() + b"y"), + nonce, + ) + assert out == f"<{nonce}>|xy\n".encode() + + +def test_render_is_one_pass() -> None: + # Placeholders inside values stay as they are, wherever they come from. + out = prompt.render(b"{{PR_TITLE}}\n{{PR_BODY}}", values(title=b"T {{PR_BODY}}", body=b"B {{PR_TITLE}}"), "n" * 24) + assert out == b"T {{PR_BODY}}\nB {{PR_TITLE}}\n" + assert prompt.render(b"{{RULES}}", values(rules=b"{{REPO}}"), "n" * 24) == b"{{REPO}}\n" + # Unknown placeholders in the template stay too. + assert prompt.render(b"{{UNKNOWN}} {{REPO}}", values(), "n" * 24) == b"{{UNKNOWN}} example-org/example\n" + + +def test_title_cannot_multiply_the_body() -> None: + """With sequential substitution, each '{{PR_BODY}}' in the title expanded the body: + 46 of them in a 512-byte title gave a prompt of about 774 KB.""" + template = (AR_DIR / "prompt.md.tmpl").read_bytes() + title = prompt.title_bytes("{{PR_BODY}}" * 46) + body = prompt.body_bytes("b" * 20000) + out = prompt.render(template, values(title=title, body=body), prompt.new_nonce()) + assert out.count(b"{{PR_BODY}}") == 46 + assert len(out) < len(template) + 2 * prompt.PR_TITLE_MAX_BYTES + prompt.PR_BODY_MAX_BYTES + 4096 + + +def test_render_template_newlines_and_nul() -> None: + assert prompt.render(b"a\0b\n\n\n", values(), "n" * 24) == b"ab\n" + + +@pytest.mark.parametrize("raw", [b"a\xffb", b"a\xc3\x28b", b"a\xe2\x82b", b"a\xc0\x80b", b"tail\xe2\x82"]) +def test_invalid_utf8_in_pr_json_matches_jq(tmp_path: pathlib.Path, raw: bytes) -> None: + """jq replaces invalid bytes with U+FFFD and goes on; so does read_pr.""" + path = tmp_path / "pr.json" + path.write_bytes(b'{"title": "' + raw + b'", "body": "' + raw + b'"}') + assert prompt.read_pr(str(path)) == bash_fields(path) diff --git a/agent-review/tests/python/test_publish_comment.py b/agent-review/tests/python/test_publish_comment.py new file mode 100644 index 0000000..82055e4 --- /dev/null +++ b/agent-review/tests/python/test_publish_comment.py @@ -0,0 +1,454 @@ +"""agent_review.publish_comment: render and post (tests/test-publish-comment.sh is the black-box spec). + +Unit tests of the parts the .sh suite does not reach, and the entry point +under the production command line in a hostile environment, with a fake +'gh' first on PATH. +""" + +import json +import os +import pathlib +import subprocess + +import pytest + +from agent_review import publish_comment as pc +from agent_review import runner, sanitize + +AR_DIR = pathlib.Path(__file__).resolve().parents[2] +ENTRY = [*("/usr/bin/python3", "-I", "-S", "-B"), str(AR_DIR / "bin" / "publish-comment")] +SHA = "0123456789abcdef0123456789abcdef01234567" +RUN_URL = "https://github.com/example-org/example/actions/runs/1" +MARKER = "" + + +def render(review: bytes, **overrides: str) -> bytes: + args = {"harness": "stub", "version": "stub-1", "model": "none", "head_sha": SHA, "run_url": RUN_URL} + return pc.render(**{**args, **overrides}, review=review) + + +# --- render ------------------------------------------------------------------------ + + +def test_render_layout() -> None: + body = render(b"### Summary\nok\n\n\n").decode() + assert body == ( + f"{MARKER}\n> [!NOTE]\n> Advisory review by **stub** stub-1 (`none`) of commit {SHA}, produced in a sandbox. " + "Later pushes are not reviewed. Not a required check: it may be wrong, and the content of the pull request " + f"can steer it. [Workflow run]({RUN_URL}).\n\n### Summary\nok\n" + ) + + +@pytest.mark.parametrize("review", [b"", b"\n\n", b" \t\n", b"\x0b\x0c\r\n", "\u200b\u2066\n".encode()]) +def test_render_empty(review: bytes) -> None: + with pytest.raises(pc.Failure) as e: + render(review) + assert e.value.code == pc.EXIT_INVALID + + +def test_render_non_ascii_whitespace_is_not_empty() -> None: + # Only ASCII whitespace makes a review empty; U+00A0 is content. + assert render("\u00a0\n".encode()).endswith("\n\n\u00a0\n".encode()) + + +def test_render_invalid_utf8() -> None: + with pytest.raises(pc.Failure) as e: + render(b"\xff") + assert e.value.code == pc.EXIT_INVALID + + +@pytest.mark.parametrize( + ("review", "noted"), + [ + (b"x" * 59999, False), + # Exactly the cap and not cut: no note. + (b"x" * 60000, False), + (b"x" * 60000 + b"\n", False), + (b"x" * 60001, True), + # Grows past the cap through escaping, cut: noted. + (b"xx" + b"@a" * 12000, True), + # Larger than the cap only because of dropped characters: not cut. + (b"ok\n" + "\u200b".encode() * 30000, False), + ], + ids=["below", "at-cap", "at-cap-newline", "above", "grows-past-cap", "dropped-only"], +) +def test_render_truncation_note(review: bytes, noted: bool) -> None: + """The note appears if and only if the sanitised review was cut.""" + body = render(review) + assert (b"_[Truncated to 60000 bytes.]_" in body) is noted + assert len(body) <= pc.BODY_MAX_BYTES + assert sanitize.sanitize_and_report(review)[1] is noted + + +def test_render_cut_keeps_every_mention_neutralised() -> None: + body = render(b"xx" + b"@a" * 12000).decode() + text = body.split("\n\n", 1)[1].split("\n\n_[Truncated")[0] + # Cut after a whole '@' ZWJ unit at most: never a bare '@'. + assert text.endswith(("a", "@\u200d")) + assert text.count("@") == text.count("@\u200d") + + +def test_render_body_fits_github_for_any_review() -> None: + body = render("\U0001f600@a", f"<{ZWSP}!-- x --{ZWSP}>"), + ("", f"<{ZWSP}?php ?>"), + ("", f"<{ZWSP}![CDATA[x]]>"), + ('v', f'<{ZWSP}b foo="TEXT">v<{ZWSP}/b>'), + ("std::vector a < b <3 <-x <_", f"std::vector<{ZWSP}int> a < b <3 <-x <_"), + ("--->", f"---{ZWSP}>"), + ("[x]: https://e.org", f"[x]{ZWSP}: https://e.org"), + ("@user @@a a@b.org @-x @ x", f"@{ZWJ}user @@{ZWJ}a a@{ZWJ}b.org @-x @ x"), + ("@x &ok ‍", "&commat;x &amp;ok &zwj;"), + ("@ @ @", f"&#{ZWSP}64; &#{ZWSP}x40; &#{ZWSP}X40;"), + ("& a&b &; &1x; &\u00e9;", "& a&b &; &1x; &\u00e9;"), + (f"<{ZWSP}!-- @{ZWSP}x &\u200f#64; [x]{ZWSP}:", f"<{ZWSP}!-- @{ZWJ}x &#{ZWSP}64; [x]{ZWSP}:"), + ], +) +def test_clean(text: str, want: str) -> None: + assert sanitize.clean(text) == want + + +@pytest.mark.parametrize( + "text", + [ + # Each rendered as nothing (or as an invisible soft hyphen) on GitHub + # before every '<' + letter, '/', '!' or '?' was broken up (checked + # with 'gh api markdown', render only). + 'v\n', + "\n\n", + "
\nA B\n
\n", + "
\nx­TEXT\n
\n", + "
sTEXT
\n", + "\n\n
x
\n\n", + "\n\n\n\n", + "v TEXT TEXT\n", + ], +) +def test_no_raw_html_can_form(text: str) -> None: + out = sanitize.clean(text) + assert re.search(r"<[A-Za-z/!?]", out, re.ASCII) is None + # Visible text stays, with a ZWSP after each '<'. '­' without its ';' + # is not a reference outside HTML: GitHub shows it literally. + assert out.replace(ZWSP, "") == text + + +def test_unicode_digits_and_letters_are_not_login_characters() -> None: + # A login is ASCII letters and digits only: '@' before other letters is no mention. + assert sanitize.clean("@\u0661 @\u00e9") == "@\u0661 @\u00e9" + + +# --- Encoding and the size cap ------------------------------------------------------ + + +@pytest.mark.parametrize( + "data", + [ + b"\xff", + b"\xc0\x80", # overlong + b"\xed\xa0\x80", # surrogate + b"\xf4\x90\x80\x80", # above U+10FFFF (glibc iconv accepted it) + b"\xf8\x88\x80\x80\x80", # 5-byte form (glibc iconv accepted it) + b"a\xe2\x80", # truncated + ], +) +def test_invalid_utf8(data: bytes) -> None: + with pytest.raises(sanitize.InvalidReviewError): + sanitize.sanitize(data) + + +@pytest.mark.parametrize("char", ["a", "\u00e9", "\u20ac", "\U0001f600"]) +@pytest.mark.parametrize("cap", [0, 1, 2, 3, 4, 5, 10, 11]) +def test_cut_on_character_boundary(char: str, cap: int) -> None: + data = (char * 10).encode() + out = sanitize.cut(data, cap) + assert len(out) <= cap + assert data.startswith(out) + assert out.decode() == char * (len(out) // len(char.encode())) + # Nothing more could have fitted. + assert len(out) + len(char.encode()) > cap or out == data + + +def test_sanitize_caps_after_escaping() -> None: + out, cut = sanitize.sanitize_and_report(b"@a" * 40000) + assert cut + assert len(out) <= sanitize.REVIEW_MAX_BYTES + out.decode("utf-8") + + +@pytest.mark.parametrize( + ("text", "units"), + [ + ("x@a", ["@\u200d"]), + ("x", ["--\u200b"]), + ("x--->", ["--\u200b"]), + ("x]:", ["]\u200b"]), + ("x", ["&#\u200b"]), + ("x<", ["&"]), + ], +) +def test_cut_never_splits_a_neutralisation(text: str, units: list[str]) -> None: + """Every cap: the cut keeps a neutralisation whole or drops all of it.""" + full = sanitize.clean(text) + data = full.encode() + for cap in range(len(data) + 1): + out = sanitize.cut(data, cap).decode() + assert full.startswith(out) + for unit in units: + start = full.index(unit) + assert len(out) <= start or len(out) >= start + len(unit), (cap, out) + + +def test_reported_cut_is_exact() -> None: + assert sanitize.sanitize_and_report(b"x" * 10, 10) == (b"x" * 10, False) + assert sanitize.sanitize_and_report(b"x" * 11, 10) == (b"x" * 10, True) + assert sanitize.sanitize_and_report(b"@a", 3) == (b"", True) + assert sanitize.sanitize_and_report(b"@a", 4) == ("@\u200d".encode(), True) + # Only trailing newlines lost: no content was cut. + assert sanitize.sanitize_and_report(b"xx\n\n", 2) == (b"xx", False) + assert sanitize.sanitize_and_report(b"xx\n\ny", 2) == (b"xx", True) + assert sanitize.sanitize_and_report("\u200b".encode() * 10 + b"x", 2) == (b"x", False) + + +# --- Property tests ------------------------------------------------------------------ + +NAMED_REF = re.compile(r"&[A-Za-z][A-Za-z0-9]*;", re.ASCII) +# Characters that build the constructs, and hiding tricks around them. +ADVERSARIAL = [ + *"]:[@&#;aZ09 \t\n", + "", + "\n", + "­", + MARKER, + "agent-review:stub -->", + "@", + "@", + "@", + "&", + "]:", + "@user", + "\r", + "\x00", + "\x1b", + "\x7f", + "\u0085", +] +INVISIBLE_SAMPLES = [c for c in map(chr, range(0x110000)) if not 0xD800 <= ord(c) <= 0xDFFF and oracle_dropped(c)] + + +def random_text(rng: random.Random) -> str: + parts = [] + for _ in range(rng.randrange(1, 60)): + roll = rng.random() + if roll < 0.45: + parts.append(rng.choice(ADVERSARIAL)) + elif roll < 0.75: + parts.append(rng.choice(INVISIBLE_SAMPLES)) + else: + cp = rng.randrange(0x110000) + if not 0xD800 <= cp <= 0xDFFF: + parts.append(chr(cp)) + return "".join(parts) + + +def inserted_at(out: str, i: int) -> bool: + """True if ``out[i]`` is a character the sanitiser inserts, in its place.""" + c = out[i] + before, after = out[:i], out[i + 1 : i + 2] + if c == ZWJ: + return before.endswith("@") and (LOGIN_CHAR.fullmatch(after) is not None or after == "") + if c == ZWSP: + return ( + (before.endswith("<") and (re.fullmatch(r"[A-Za-z/!?]", after, re.ASCII) is not None or after == "")) + or (before.endswith("--") and after in (">", "")) + or (before.endswith("]") and after in (":", "")) + or before.endswith("&#") + ) + return False + + +def check_output(out: str, *, at_end_only_if_cut: bool) -> None: + assert MARKER not in out + assert "" not in out + assert re.search(r"<[A-Za-z/!?]", out, re.ASCII) is None + assert "]:" not in out + assert re.search(r"@[A-Za-z0-9]", out, re.ASCII) is None + assert "&#" not in out + assert all(m.group(0) == "&" for m in NAMED_REF.finditer(out)) + for i, c in enumerate(out): + if oracle_dropped(c): + assert inserted_at(out, i), (f"U+{ord(c):04X}", i, out[max(0, i - 8) : i + 8]) + # An inserted character with nothing after it only where the cap + # cut, or after '&#' (the review may end with '&#'). + if not at_end_only_if_cut and not out[:i].endswith("&#"): + assert i + 1 < len(out) + + +@pytest.mark.parametrize("seed", range(20)) +def test_property_random_adversarial(seed: int) -> None: + rng = random.Random(seed) # noqa: S311 (reproducible test inputs) + for _ in range(300): + text = random_text(rng) + check_output(sanitize.clean(text), at_end_only_if_cut=False) + + +# Independent of the module: what each neutralisation inserts, with the +# character(s) it protects. +UNIT = re.compile("&#\u200b|&|<\u200b|--\u200b|\\]\u200b|@\u200d") + + +def legal_cuts(full: str) -> list[int]: + """Byte offsets where ``full`` may be cut: character boundaries outside every unit.""" + inside = {i for m in UNIT.finditer(full) for i in range(m.start() + 1, m.end())} + offsets, pos = [], 0 + for i, c in enumerate(full): + if i not in inside: + offsets.append(pos) + pos += len(c.encode()) + offsets.append(pos) + return offsets + + +@pytest.mark.parametrize("seed", range(5)) +def test_property_with_the_cap(seed: int) -> None: + """At every cap: the longest legal prefix, reported as cut exactly when it is.""" + rng = random.Random(1000 + seed) # noqa: S311 (reproducible test inputs) + for _ in range(40): + text = random_text(rng) + full = sanitize.clean(text) + data = full.encode() + legal = legal_cuts(full) + for cap in range(len(data) + 1): + out = sanitize.cut(data, cap) + assert len(out) == max(o for o in legal if o <= cap) + check_output(out.decode("utf-8"), at_end_only_if_cut=True) + for cap in (0, len(data) // 2, len(data) - 1, len(data)): + if cap >= 0: + out, cut = sanitize.sanitize_and_report(text.encode(), cap) + assert cut is (len(data.rstrip(b"\n")) > len(out)) + + +@pytest.mark.parametrize("seed", range(5)) +def test_property_dropping_never_joins(seed: int) -> None: + """Invisible characters inside every delimiter, mention and reference.""" + rng = random.Random(2000 + seed) # noqa: S311 (reproducible test inputs) + words = ["", " None: + with pytest.raises(AssertionError): + check_output("a\u200bb", at_end_only_if_cut=False) + with pytest.raises(AssertionError): + check_output("@\u200d-", at_end_only_if_cut=False) + with pytest.raises(AssertionError): + check_output("x \u2066y", at_end_only_if_cut=False) + + +# --- Token reach ------------------------------------------------------------------- + + +def test_sanitizer_cannot_reach_gh() -> None: + import pathlib + + lib = pathlib.Path(sanitize.__file__).resolve().parent + modules = { + f"agent_review.{p.stem}": p.read_text(encoding="utf-8") for p in lib.glob("*.py") if p.stem != "__init__" + } + modules["agent_review"] = (lib / "__init__.py").read_text(encoding="utf-8") + closure = import_closure((lib / "sanitize.py").read_text(encoding="utf-8"), modules) + assert "agent_review.gh" not in closure + assert "agent_review.runner" not in closure diff --git a/agent-review/tests/python/test_validate.py b/agent-review/tests/python/test_validate.py new file mode 100644 index 0000000..8f096fb --- /dev/null +++ b/agent-review/tests/python/test_validate.py @@ -0,0 +1,74 @@ +"""agent_review.validate: whole-value ASCII matching, without Python's looser defaults.""" + +import re + +import pytest + +from agent_review import validate + + +def test_fullmatch_rejects_a_trailing_newline() -> None: + # re.match(r'^[0-9a-f]{40}$', sha + '\n') would match. + sha = "a" * 40 + assert validate.matches(validate.SHA, sha) + assert re.match(r"^[0-9a-f]{40}$", sha + "\n") + assert not validate.matches(validate.SHA, sha + "\n") + + +@pytest.mark.parametrize("value", ["\uff11\uff12", "\u0661\u0662", "1_0", " 7", "7\n", "+7", "-7", "", "0x10", "1e3"]) +def test_parse_int_rejects_what_int_accepts(value: str) -> None: + with pytest.raises(validate.ValidationError): + validate.parse_int(value, "number") + + +def test_int_traps_exist() -> None: + # The reason parse_int validates first. + assert int("\uff11\uff12") == 12 + assert int("1_0") == 10 + assert int(" 7\n") == 7 + + +def test_parse_int() -> None: + assert validate.parse_int("0042", "number") == 42 + assert validate.parse_int("7", "number", digits=validate.POSITIVE_INT) == 7 + with pytest.raises(validate.ValidationError): + validate.parse_int("07", "number", digits=validate.POSITIVE_INT) + with pytest.raises(validate.ValidationError): + validate.parse_int("101", "cap", maximum=100) + with pytest.raises(validate.ValidationError): + validate.parse_int("1" * 11, "number") + + +def test_classes_are_ascii_only() -> None: + word = validate.pattern(r"\w+") + assert validate.matches(word, "abc_1") + assert not validate.matches(word, "é") + assert not validate.matches(validate.pattern(r"\d+"), "\u0661") + + +def test_pattern_refuses_anchors_and_unicode_patterns() -> None: + with pytest.raises(ValueError, match="anchors"): + validate.pattern(r"^[a-z]+$") + with pytest.raises(ValueError, match=r"validate\.pattern"): + validate.matches(re.compile(r"[a-z]+"), "abc") + + +def test_require() -> None: + assert validate.require(validate.REPO, "example-org/example", "repository") == "example-org/example" + with pytest.raises(validate.ValidationError, match="Invalid repository"): + validate.require(validate.REPO, "example-org/example/extra", "repository") + + +@pytest.mark.parametrize( + ("compiled", "good", "bad"), + [ + (validate.POSITIVE_INT, ["1", "2983", "9999999999"], ["0", "01", "10000000000"]), + (validate.REPO, ["a/b", "Example-Org/repo.x"], ["a", "a/b/c", "a /b", "a/b\n"]), + (validate.HARNESS, ["stub", "open-code"], ["Stub", "1x", "-x", "a" * 33]), + (validate.MODEL, ["zai-org/GLM-5.3-Flash", "m:1"], ["-m", "m m", "/m"]), + (validate.PROJECT, ["ExampleProj", "proj 4x"], [" x", "x\ty", "a" * 65]), + ], +) +def test_shared_patterns(compiled: re.Pattern[str], good: list[str], bad: list[str]) -> None: + assert all(validate.matches(compiled, v) for v in good) + assert not any(validate.matches(compiled, v) for v in bad) diff --git a/agent-review/tests/python/test_workflow.py b/agent-review/tests/python/test_workflow.py new file mode 100644 index 0000000..aa969ea --- /dev/null +++ b/agent-review/tests/python/test_workflow.py @@ -0,0 +1,113 @@ +"""agent_review.workflow: workflow commands, step outputs and log lines.""" + +import io +import os +import pathlib + +import pytest + +from agent_review import workflow + + +def test_escape_data() -> None: + assert workflow.escape_data("100%\r\n::error::x") == "100%25%0D%0A::error::x" + + +def test_command_cannot_be_split() -> None: + out = io.BytesIO() + workflow.notice("a\n::error::injected", stream=out) + assert out.getvalue() == b"::notice::a%0A::error::injected\n" + assert out.getvalue().count(b"\n") == 1 + + +def test_command_properties_are_escaped() -> None: + out = io.BytesIO() + workflow.warning("msg", title="a:b,c\nd", stream=out) + assert out.getvalue() == b"::warning title=a%3Ab%2Cc%0Ad::msg\n" + + +def test_only_known_commands() -> None: + with pytest.raises(ValueError, match="unsupported"): + workflow.command("stop-commands", "token") + with pytest.raises(ValueError, match="unsupported"): + workflow.command("add-mask", "x") + + +def test_output_is_utf8_bytes() -> None: + out = io.BytesIO() + workflow.error("é", stream=out) + assert out.getvalue() == "::error::é\n".encode() + with pytest.raises(UnicodeEncodeError): + workflow.error("\udcff", stream=io.BytesIO()) + + +def test_log_lines_prefix_every_line() -> None: + out = io.BytesIO() + workflow.log_lines("one\r\n::error::two\n\nthree", "awf| ", stream=out) + assert out.getvalue() == b"awf| one\nawf| ::error::two\nawf| \nawf| three\n" + + +def test_log_lines_drop_nul_before_breaking_markers() -> None: + out = io.BytesIO() + workflow.log_lines("x #\0#[warning]a\0b", "awf| ", stream=out) + assert out.getvalue().decode() == "awf| x #\u200b#[warning]ab\n" + + +def test_log_lines_break_legacy_commands() -> None: + out = io.BytesIO() + workflow.log_lines("x ##[warning]fake\n##[add-mask]v ##[set-output name=a;]b", "awf| ", stream=out) + text = out.getvalue().decode() + assert "##[" not in text + assert text == "awf| x #\u200b#[warning]fake\nawf| #\u200b#[add-mask]v #\u200b#[set-output name=a;]b\n" + + +@pytest.mark.parametrize("prefix", ["", "::", " ::x", "a\nb", " x", "\u00a0x", "\tx", ":x", "a\x00", "##[x", "a::b"]) +def test_log_lines_rejects_unsafe_prefixes(prefix: str) -> None: + with pytest.raises(ValueError, match="prefix"): + workflow.log_lines("x", prefix, stream=io.BytesIO()) + + +@pytest.mark.parametrize("value", ["a\nb=c", "a\rb", "\n"]) +def test_output_rejects_line_breaks(value: str) -> None: + with pytest.raises(ValueError, match="line break"): + workflow.output_line("name", value) + + +@pytest.mark.parametrize("name", ["", "a=b", "a b", "-a", "a\n", "é"]) +def test_output_rejects_bad_names(name: str) -> None: + with pytest.raises(ValueError, match="Invalid output name"): + workflow.output_line(name, "v") + + +def test_set_output_appends(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: + target = tmp_path / "output" + target.write_bytes(b"first=1\n") + monkeypatch.setenv("GITHUB_OUTPUT", str(target)) + workflow.set_output("allowed", "true") + workflow.set_output("model", "zai-org/GLM-5.3-Flash") + assert target.read_bytes() == b"first=1\nallowed=true\nmodel=zai-org/GLM-5.3-Flash\n" + + +def test_set_output_refuses_a_symlink(tmp_path: pathlib.Path) -> None: + real = tmp_path / "real" + real.write_bytes(b"") + link = tmp_path / "link" + link.symlink_to(real) + with pytest.raises(OSError): + workflow.set_output("a", "b", path=str(link)) + assert real.read_bytes() == b"" + + +def test_set_output_refuses_a_fifo_without_blocking(tmp_path: pathlib.Path) -> None: + fifo = tmp_path / "fifo" + os.mkfifo(fifo) + with pytest.raises(OSError): + workflow.set_output("a", "b", path=str(fifo)) + + +def test_set_output_needs_an_absolute_path(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("GITHUB_OUTPUT", raising=False) + with pytest.raises(ValueError, match="absolute"): + workflow.set_output("a", "b") + with pytest.raises(ValueError, match="absolute"): + workflow.set_output("a", "b", path="relative/out") diff --git a/agent-review/tests/python/test_workflow_structure.py b/agent-review/tests/python/test_workflow_structure.py new file mode 100644 index 0000000..bcb16f3 --- /dev/null +++ b/agent-review/tests/python/test_workflow_structure.py @@ -0,0 +1,984 @@ +"""The structure checks of workflow_structure.py on crafted inputs. + +The call-site rules are tested on a small frozen workflow (``fixture``) with +the same jobs, roots and call lines as agent-review.yml, which every script +calls as a Python entry point; each case breaks it in one way. Only the +"real ... passes" tests read the live tree. +""" + +import copy +import pathlib +import subprocess +from typing import Any + +import pytest + +import workflow_structure as ws + +WORKFLOW: dict[str, Any] = ws.load(ws.REVIEW_WORKFLOW) +REPO = ws.repository() +KINDS: dict[str, str | None] = REPO["kinds"] + +ENTRIES = ("authorize", "collect-result", "publish-comment", "run-review") +TRUSTED = '"${RUNNER_TEMP}/trusted/bin/' +OPT = "/opt/agent-review/bin/" +PY = "/usr/bin/python3 -I -S -B " +# The call of each entry point, as the fixture and agent-review.yml write it. +CALLS = { + "authorize": f'{PY}{TRUSTED}authorize"', + "run-review": f"-- {PY}{OPT}run-review --phase fetch", + "collect-result": f"{PY}{OPT}collect-result", + "publish-comment": f'{PY}{TRUSTED}publish-comment" render', +} + + +def fixture() -> dict[str, Any]: + """agent-review.yml's call sites: every entry point called in the Python form.""" + fetch = {"name": "Fetch trusted files", "run": f'[ -f {TRUSTED}run-review" ] || exit 1\n'} + review_steps = [ + fetch, + {"name": "Fetch the caller configuration", "run": "true\n"}, + {"name": "Prepare the sandbox inputs", "run": 'sudo cp -R "${RUNNER_TEMP}/trusted/." /opt/agent-review/\n'}, + { + "name": "Fetch the pull request in the sandbox", + "run": f'sudo -E "${{AWF_BIN}}" {CALLS["run-review"]} "${{WS}}"\n', + }, + {"name": "Collect the result", "run": f'{CALLS["collect-result"]} "${{WS}}/out" r\n'}, + ] + return { + "jobs": { + "authorize": {"steps": [fetch, {"name": "Authorize", "run": CALLS["authorize"] + "\n"}]}, + "prepare": {"steps": [fetch, {"name": "Install the harness", "run": "true\n"}]}, + "review": {"steps": copy.deepcopy(review_steps)}, + "review-keyless": {"steps": copy.deepcopy(review_steps)}, + "publish": { + "steps": [ + fetch, + {"name": "Render the review", "run": f"{CALLS['publish-comment']} --review r.md\n"}, + {"name": "Publish the review", "run": f'url=$({PY}{TRUSTED}publish-comment" post --pr 9)\n'}, + ] + }, + } + } + + +def kinds() -> dict[str, str | None]: + return dict.fromkeys(ENTRIES, "python") + + +def problems(workflow: dict[str, Any], entry_kinds: dict[str, str | None]) -> list[str]: + return ws.call_site_problems(workflow, entry_kinds) + ws.python_word_problems(workflow, entry_kinds) + + +def edit_runs(workflow: dict[str, Any], old: str, new: str) -> int: + """Replaces ``old`` in every 'run:' script; returns the number of scripts changed.""" + changed = 0 + for job in workflow["jobs"].values(): + for step in job.get("steps", []): + if old in step.get("run", ""): + step["run"] = step["run"].replace(old, new) + changed += 1 + return changed + + +def test_real_workflow_passes() -> None: + assert ws.call_site_problems(WORKFLOW, KINDS) == [] + assert ws.python_word_problems(WORKFLOW, KINDS) == [] + + +@pytest.mark.parametrize("name", ENTRIES) +def test_fixture_matches_the_real_call_lines(name: str) -> None: + real = "\n".join(script for _, _, _, script in ws.run_scripts(WORKFLOW)) + assert KINDS[name] == "python" + assert CALLS[name] in real + + +def test_fixture_passes() -> None: + assert problems(fixture(), kinds()) == [] + + +@pytest.mark.parametrize( + ("old", "new"), + [ + # Calls that run an entry point with bash instead of the Python command line. + (CALLS["authorize"], f'bash {TRUSTED}authorize"'), + (CALLS["run-review"], f"-- {OPT}run-review --phase fetch"), + (CALLS["collect-result"], f"/usr/bin/bash {OPT}collect-result"), + ( + f"{CALLS['publish-comment']} --review r.md\n", + f'pc={TRUSTED}publish-comment"\n{PY}"${{pc}}" render --review r.md\n', + ), + ], +) +def test_bash_call_forms_fail(old: str, new: str) -> None: + workflow = fixture() + assert edit_runs(workflow, old, new) + found = ws.call_site_problems(workflow, kinds()) + assert found + assert all("is Python; call it exactly as" in p for p in found) + + +def test_wrong_root_fails() -> None: + workflow = fixture() + assert edit_runs(workflow, f'{TRUSTED}authorize"', f"{OPT}authorize") + assert edit_runs(workflow, f"{OPT}collect-result", f'{TRUSTED}collect-result"') + found = ws.call_site_problems(workflow, kinds()) + assert any("authorize/Authorize: '/opt/agent-review/bin/authorize'" in p for p in found) + assert any("review/Collect the result: '${RUNNER_TEMP}/trusted/bin/collect-result'" in p for p in found) + + +def test_trusted_root_in_review_jobs_only_before_the_copy() -> None: + workflow = fixture() + assert edit_runs(workflow, f"{PY}{OPT}run-review", f'{PY}{TRUSTED}run-review"') + found = ws.call_site_problems(workflow, kinds()) + assert any("Fetch the pull request in the sandbox" in p and "only '/opt/agent-review'" in p for p in found) + + +@pytest.mark.parametrize( + "call", + [ + f'python3 {TRUSTED}authorize"', + f'/usr/bin/python3 -I -B {TRUSTED}authorize"', + f'/usr/bin/python3 -I -S -B -c {TRUSTED}authorize"', + f'p={TRUSTED}authorize"; /usr/bin/python3 -I -S -B "$p"', + f'/usr/bin/python3 -ISB {TRUSTED}authorize"', + f'{TRUSTED}authorize"', + f'bash {TRUSTED}authorize"', + f'"${{HOME}}"{PY}{TRUSTED}authorize"', + f'x{PY}{TRUSTED}authorize"', + ], +) +def test_other_call_forms_fail(call: str) -> None: + workflow = fixture() + assert edit_runs(workflow, CALLS["authorize"], call) + assert problems(workflow, kinds()) + + +@pytest.mark.parametrize( + ("old", "call"), + [ + # The call must start a command ('bounded'): 'x' or a closing quote before it. + (CALLS["authorize"], f'x{PY}{TRUSTED}authorize"'), + (CALLS["authorize"], f'"${{HOME}}"{PY}{TRUSTED}authorize"'), + # Only a separator may follow the name (PYTHON_AFTER). + (CALLS["authorize"], f'{PY}{TRUSTED}authorize/../../x"'), + (CALLS["authorize"], f'{PY}{TRUSTED}authorize"x'), + (CALLS["collect-result"], f"{PY}{OPT}collect-result/x"), + (CALLS["collect-result"], f"{PY}{OPT}collect-result;x"), + # An existence test must be complete ('" ]' after the name). + (CALLS["authorize"], f'[ -f {TRUSTED}authorize"'), + (CALLS["authorize"], f'[ -f {TRUSTED}authorize"x'), + (CALLS["authorize"], f'[ -f {TRUSTED}authorize";'), + ], +) +def test_each_call_site_check_alone(old: str, call: str) -> None: + """Each case fails in call_site_problems itself, not only through the 'python' word rule.""" + workflow = fixture() + assert edit_runs(workflow, old, call) + found = ws.call_site_problems(workflow, kinds()) + assert found and all("is Python; call it exactly as" in p for p in found), found + + +@pytest.mark.parametrize( + "script", + ["python3 -c 'print(1)'", "/usr/bin/python3 -m pip install x", "pip install pytest", "pipx run x", "python -V"], +) +def test_python_and_pip_elsewhere_in_the_workflow_fail(script: str) -> None: + workflow = fixture() + workflow["jobs"]["prepare"]["steps"].append({"name": "x", "run": script}) + assert ws.python_word_problems(workflow, kinds()) + + +def test_setup_python_fails() -> None: + workflow = fixture() + workflow["jobs"]["publish"]["steps"].insert(0, {"uses": "actions/setup-python@0123456789abcdef"}) + assert ws.python_word_problems(workflow, kinds()) + + +def test_unknown_entry_point_and_job_fail() -> None: + workflow = fixture() + workflow["jobs"]["extra"] = {"steps": [{"name": "x", "run": CALLS["authorize"] + "\n"}]} + workflow["jobs"]["prepare"]["steps"].append({"name": "y", "run": f'{PY}{TRUSTED}nope"\n'}) + found = ws.call_site_problems(workflow, kinds()) + assert any("no allowed root for job 'extra'" in p for p in found) + assert any("bin/nope is not a known entry point" in p for p in found) + + +def test_a_non_template_file_is_not_an_entry_point() -> None: + found = ws.call_site_problems(fixture(), {**kinds(), "authorize": None}) + assert any("bin/authorize is not a known entry point" in p for p in found) + + +ROOT_LINE = 'ar_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)' +GOOD_CALL = '/usr/bin/python3 -I -S -B "${ar_root}/bin/probe"' + + +def shell(*lines: str) -> dict[str, str]: + return {"harnesses/x/run.sh": "#!/usr/bin/env bash\n" + "".join(f"{line}\n" for line in lines)} + + +def test_shell_files() -> None: + kinds = {"probe": "python", "run-review": "bash"} + assert ws.shell_python_problems(shell("# python in a comment", ROOT_LINE, GOOD_CALL), kinds) == [] + assert ws.shell_python_problems(shell(ROOT_LINE, f"out=$({GOOD_CALL})", f"x && {GOOD_CALL}"), kinds) == [] + assert ws.ar_root_line("bin/run-review") == 'ar_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)' + for line in [ + 'python3 "${ar_root}/bin/probe"', + '/usr/bin/python3 -I -S -B "${ar_root}/bin/run-review"', + "/usr/bin/python3 -I -S -B -c 'import os'", + '/usr/bin/python3 -I -S -B "${GITHUB_WORKSPACE}/bin/probe"', + '/usr/bin/python3 -I -S -B "${root}/bin/probe"', + '"${HOME}"/usr/bin/python3 -I -S -B "${ar_root}/bin/probe"', + "exec python3", + ]: + assert ws.shell_python_problems(shell(ROOT_LINE, line), kinds), line + + +def test_shell_root_must_be_set_from_the_files_path() -> None: + kinds = {"probe": "python"} + assert any("does not set" in p for p in ws.shell_python_problems(shell(GOOD_CALL), kinds)) + for bad in ["ar_root=/tmp/evil", "export ar_root=${HOME}", 'ar_root=$(cd "$(dirname "$0")/../.." && pwd)']: + found = ws.shell_python_problems(shell(ROOT_LINE, bad, GOOD_CALL), kinds) + assert any("set 'ar_root' only as" in p for p in found), bad + + +def test_python_shebang_in_a_shell_file_fails() -> None: + sources = {"harnesses/x/helper.sh": "#!/usr/bin/env python3\nprint(1)\n"} + assert ws.shell_python_problems(sources, {}) + + +def test_shebang_problems() -> None: + lines = { + "agent-review/harnesses/x/helper": "#!/usr/bin/env python3", + "agent-review/bin/tool": "#!/usr/bin/python3 -I", + "agent-review/harnesses/x/run.sh": "#!/usr/bin/env bash", + "agent-review/tests/tool": "#!/usr/bin/env python3", + "agent-review/lib/agent_review/x.py": "#!/usr/bin/python3", + "agent-review/prompt.md.tmpl": "# python", + } + assert ws.shebang_problems(lines) == [ + "agent-review/bin/tool: a Python shebang ('#!/usr/bin/python3 -I'); use an entry point in bin/", + "agent-review/harnesses/x/helper: a Python shebang ('#!/usr/bin/env python3'); use an entry point in bin/", + ] + + +def test_real_shebangs_pass() -> None: + assert ws.shebang_problems(REPO["first_lines"]) == [] + + +def test_real_shell_files_pass() -> None: + assert "harnesses/stub/run.sh" in REPO["shell"] + assert "harnesses/stub/install.sh" in REPO["shell"] + assert ws.shell_python_problems(REPO["shell"], KINDS) == [] + + +# --- Entry points and tree ------------------------------------------------------- + +LIB_WITH_MAIN = {"lib/agent_review/probe.py": "def main() -> int:\n return 0\n"} + + +def test_entry_template() -> None: + text = ws.render_entry("probe") + assert ws.entry_kind("probe", text) == "python" + assert ws.entry_problems({"probe": (text, "100644")}, LIB_WITH_MAIN) == [] + assert ws.render_entry("publish-comment").count("from agent_review.publish_comment import main") == 1 + + +def test_real_entry_points_pass() -> None: + assert ws.entry_problems(REPO["entries"], REPO["lib"]) == [] + assert REPO["kinds"]["probe"] == "python" + + +NOT_TEMPLATE = "not the exact Python entry-point template" + + +@pytest.mark.parametrize( + ("text", "mode", "expected"), + [ + (ws.render_entry("probe"), "100755", "mode 100644"), + (ws.render_entry("probe") + "print('extra')\n", "100644", NOT_TEMPLATE), + ( + ws.render_entry("probe").replace("sys.flags.safe_path", "True"), + "100644", + "not the exact Python entry-point template", + ), + (ws.render_entry("other"), "100644", NOT_TEMPLATE), + ("#!/usr/bin/python3 -ISB\nimport sys\n", "100755", NOT_TEMPLATE), + ("", "100644", NOT_TEMPLATE), + ("#!/usr/bin/env bash\necho hi\n", "100755", NOT_TEMPLATE), + ("#!/usr/bin/bash\necho hi\n", "100644", NOT_TEMPLATE), + ], +) +def test_entry_problems(text: str, mode: str, expected: str) -> None: + problems = ws.entry_problems({"probe": (text, mode)}, LIB_WITH_MAIN) + assert any(expected in p for p in problems), problems + + +def test_entry_needs_its_module_and_main() -> None: + entries = {"probe": (ws.render_entry("probe"), "100644")} + assert any("no lib/agent_review/probe.py" in p for p in ws.entry_problems(entries, {})) + no_main = {"lib/agent_review/probe.py": "def run() -> int:\n return 0\n"} + assert any("defines no main()" in p for p in ws.entry_problems(entries, no_main)) + + +def test_real_tree_passes() -> None: + assert ws.tree_problems(REPO["index"]) == [] + + +@pytest.mark.parametrize( + ("mode", "path"), + [ + ("120000", "agent-review/harnesses/stub/link"), + ("160000", "agent-review/vendor"), + ("100644", "agent-review/lib/agent_review/__pycache__/x.cpython-312.pyc"), + ("100644", "agent-review/bin/x.pyc"), + ("100644", "agent-review/lib/agent_review/x.pth"), + ("100644", "agent-review/tests/sitecustomize.py"), + ("100644", "agent-review/usercustomize.py"), + ("100644", "agent-review/lib/other.py"), + ("100644", "agent-review/lib/agent_review/_speedups.so"), + ("100644", "agent-review/lib/agent_review/data.json"), + ("100644", "agent-review/harnesses/x/helper.py"), + ("100644", "agent-review/bin/tool.py"), + ], +) +def test_tree_problems(mode: str, path: str) -> None: + assert ws.tree_problems([(mode, path)]) + + +# --- AST and token reach --------------------------------------------------------- + + +def test_real_python_passes() -> None: + assert ws.ast_problems(REPO["python"]) == [] + assert ws.token_reach_problems(REPO["python"]) == [] + + +@pytest.mark.parametrize( + "source", + [ + "import pickle\n", + "import importlib\n", + "from importlib import import_module\n", + "import ctypes\n", + "import marshal\n", + "import urllib.request\n", + "import fnmatch\n", + "import yaml\n", + "import subprocess\n", + "from subprocess import run\n", + "eval('1')\n", + "exec('x = 1')\n", + "compile('1', 'f', 'eval')\n", + "__import__('os')\n", + "breakpoint()\n", + "import os\nos.system('id')\n", + "import os\nos.popen('id')\n", + "import os\nos.execv('/bin/sh', [])\n", + "import os\nos.posix_spawn('/bin/sh', [], {})\n", + "import os\nos.fork()\n", + "from os import system\n", + "import os as o\no.system('id')\n", + "from os import *\n", + "from json import *\n", + "from . import runner\n", + "f(shell=True)\n", + "f(shell=False)\n", + "run(['gh', 'api'])\n", + "run(['/usr/bin/gh', 'api'])\n", + "from agent_review import runner\nrunner.run(runner.Zone.TRUSTED_HOST, ['x'])\n", + "from agent_review.runner import subprocess\n", + "from agent_review.runner import os\n", + "from agent_review import runner\nrunner.subprocess.run(['x'])\n", + "from agent_review import runner\nrunner.os.system('id')\n", + "import os\ngetattr(os, 'system')('id')\n", + "import os\ngetattr(os.path, 'system')('id')\n", + "import os\nx = os\ngetattr(x, 'system')('id')\n", + "import os\nf(os)\n", + "from agent_review import runner\nmodules = [runner]\n", + "import sys\nsetattr(sys.stdout, 'write', None)\n", + "import sys\ns = setattr\ns(sys.stdout, 'write', None)\n", + "f = getattr\n", + "fs = [delattr]\n", + "from agent_review import runner\nrunner.run(runner.Zone.SANDBOX, ['git'])\n", + "from agent_review import runner\nrunner.run(runner.Zone.TAINTED_HOST, ['ls'])\n", + "import os as _\n", + "import sys\nsys.modules['os']\n", + "globals()['__builtins__']\n", + "vars()\n", + ], +) +def test_ast_problems(source: str) -> None: + assert ws.ast_problems({"lib/agent_review/x.py": source}) + + +def test_subprocess_and_gh_only_in_their_modules() -> None: + assert ws.ast_problems({ws.RUNNER_MODULE: "import subprocess\n"}) == [] + assert ws.ast_problems({ws.GH_MODULE: "argv = ['gh', 'api']\n"}) == [] + assert ws.ast_problems({ws.RUNNER_MODULE: "subprocess.run(['x'], shell=False)\n"}) + assert ws.ast_problems({"bin/probe": "import subprocess\n"}) + + +def test_zones_only_in_their_modules() -> None: + sandbox = "from agent_review import runner\nrunner.run(runner.Zone.SANDBOX, ['git'])\n" + assert ws.ast_problems({"lib/agent_review/run_review.py": sandbox}) == [] + assert ws.ast_problems({"lib/agent_review/sandbox_git.py": sandbox}) == [] + assert ws.ast_problems({ws.GH_MODULE: sandbox}) + assert ws.ast_problems({"lib/agent_review/collect_result.py": sandbox}) + assert ws.ast_problems({"lib/agent_review/run_review.py": sandbox.replace("SANDBOX", "TRUSTED_HOST")}) + assert ws.ast_problems({ws.RUNNER_MODULE: "Zone.TAINTED_HOST\n"}) == [] + + +def test_module_values_only_in_the_probe() -> None: + source = "from agent_review import files, runner\nMODULES = (files, runner)\n" + assert ws.ast_problems({"lib/agent_review/probe.py": source}) == [] + assert ws.ast_problems({"lib/agent_review/x.py": source}) + + +def test_ordinary_code_is_allowed() -> None: + source = ( + "import re\nimport os.path\nimport pathlib\nimport sys\nfrom os import fspath\n" + "re.compile('x')\nos.fspath('x')\ngetattr(sys.flags, 'isolated')\nsys.executable\nos.execute = 1\n" + ) + assert ws.ast_problems({"lib/agent_review/x.py": source}) == [] + + +def entry(module: str) -> str: + return ws.render_entry(module.replace("_", "-")) + + +def test_token_reach() -> None: + lib = { + "lib/agent_review/__init__.py": "", + "lib/agent_review/gh.py": "from agent_review import runner\n", + "lib/agent_review/runner.py": "", + "lib/agent_review/helper.py": "import agent_review.gh\n", + "lib/agent_review/authorize.py": "from agent_review import gh\n", + "lib/agent_review/collect_result.py": "from agent_review import runner\n", + "lib/agent_review/run_review.py": "from agent_review.helper import x\n", + "lib/agent_review/probe.py": "import agent_review\n", + } + sources = { + **lib, + "bin/authorize": entry("authorize"), + "bin/collect-result": entry("collect_result"), + "bin/run-review": entry("run_review"), + "bin/probe": entry("probe"), + } + problems = ws.token_reach_problems(sources) + assert problems == [ + "bin/run-review: reaches agent_review.gh (the token); only ['authorize', 'publish-comment'] may" + ] + # Through the package's __init__ too. + sources["lib/agent_review/__init__.py"] = "from agent_review import gh\n" + assert any(p.startswith("bin/probe:") for p in ws.token_reach_problems(sources)) + + +def test_probe_does_not_reach_gh() -> None: + modules = {m: t for rel, t in REPO["python"].items() if (m := ws._module_name(rel))} + closure = ws.import_closure(REPO["python"]["bin/probe"], modules) + assert "agent_review.probe" in closure + assert "agent_review.runner" in closure + assert "agent_review.gh" not in closure + + +# --- Sandbox output ----------------------------------------------------------------- + +SHELL = REPO["shell"] +COMMON_SH = SHELL[ws.COMMON_SH] + + +def test_real_sandbox_output_filters_pass() -> None: + assert ws.sandbox_output_problems(WORKFLOW, SHELL) == [] + + +@pytest.mark.parametrize( + "old", + [" -e 's/##\\[/#\\xe2\\x80\\x8b#[/g'", " -e 's/^/awf| /'", " -e 's/\\r//g'", " -e 's/\\x00//g'"], +) +def test_awf_output_filter_is_required(old: str) -> None: + workflow = copy.deepcopy(WORKFLOW) + # The review jobs share some steps through YAML aliases; all four awf calls must fail. + assert edit_runs(workflow, ws.AWF_OUTPUT_FILTER, ws.AWF_OUTPUT_FILTER.replace(old, "")) + assert len(ws.sandbox_output_problems(workflow, SHELL)) == 4 + + +def test_awf_stderr_must_go_through_the_filter() -> None: + workflow = copy.deepcopy(WORKFLOW) + assert edit_runs(workflow, '"${WS}" 2>&1 \\\n', '"${WS}" \\\n') + found = ws.sandbox_output_problems(workflow, SHELL) + assert len(found) == 4 and all("stderr unfiltered" in p for p in found), found + + +FILTER = " " + ws.AWF_OUTPUT_FILTER + + +@pytest.mark.parametrize( + ("script", "expected"), + [ + ('sudo -E "${AWF_BIN}" --config c -- run-review --phase review "${WS}"\n', "has no '-- ' command line"), + ('sudo -E "${AWF_BIN}" -- run-review "${WS}" 2>&1 \\\n' + FILTER + "\n", "has no '-- ' command line"), + ('sudo -E "${AWF_BIN}" \\\n --config c\n-- run-review 2>&1 \\\n' + FILTER + "\n", "has no '-- '"), + ('sudo -E "${AWF_BIN}" \\\n -- run-review 2>&1 \\\n | sed\n', "is not followed by"), + ('sudo -E "${AWF_BIN}" \\\n -- run-review 2>/dev/null \\\n' + FILTER + "\n", "stderr unfiltered"), + ('sudo -E "${AWF_BIN}" \\\n -- run-review 2>&1 \\\n' + FILTER + '\n"${AWF_BIN}" -- x\n', "line 4 has no"), + ], +) +def test_every_awf_call_is_filtered(script: str, expected: str) -> None: + workflow = {"jobs": {"review": {"steps": [{"name": "Run", "run": script}]}}} + found = ws.sandbox_output_problems(workflow, SHELL) + assert len(found) == 1 and expected in found[0], found + + +@pytest.mark.parametrize( + "line", + ['sudo -E "$AWF_BIN" -- /usr/bin/true', "sudo -E ${AWF_BIN} -- true", "sudo -E awf -- true", 'x="${AWF_BIN}x"'], +) +def test_awf_is_named_only_as_the_call(line: str) -> None: + workflow = copy.deepcopy(WORKFLOW) + step = next( + s for s in workflow["jobs"]["review"]["steps"] if s.get("name") == "Fetch the pull request in the sandbox" + ) + step["run"] = line + "\n" + step["run"] + found = ws.sandbox_output_problems(workflow, SHELL) + # The line also precedes the call, which is reported too. + assert sum("line 1 names awf other than as the call" in p for p in found) == 2, found + + +@pytest.mark.parametrize( + ("name", "line"), + [ + ("Fetch the pull request in the sandbox", 'cat "${WS}/prompt.md"'), + ("Run the review in the sandbox", 'echo "rc=${rc}"'), + ("Run the review in the sandbox", "exit 0; cat x"), + ], +) +def test_only_status_lines_follow_the_awf_call(name: str, line: str) -> None: + """A line after the call could print pull request text to the log, unfiltered.""" + workflow = copy.deepcopy(WORKFLOW) + step = next(s for s in workflow["jobs"]["review"]["steps"] if s.get("name") == name) + step["run"] = step["run"] + line + "\n" + found = ws.sandbox_output_problems(workflow, SHELL) + assert found and all("after the awf call is not one of" in p for p in found), found + + +@pytest.mark.parametrize( + ("old", "new"), + [ + ('"${WS}" 2>&1 \\\n', '"${WS}" 1>&2 2>&1 \\\n'), + ('"${WS}" 2>&1 \\\n', '"${WS}" >/dev/stderr 2>&1 \\\n'), + ('"${WS}" 2>&1 \\\n', '"${WS}" < /dev/null 2>&1 \\\n'), + ('--image-tag "${IMAGE_TAG}" \\\n', '--image-tag "$(cat "${WS}/prompt.md")" \\\n'), + ('--image-tag "${IMAGE_TAG}" \\\n', "--image-tag `id` \\\n"), + ('--image-tag "${IMAGE_TAG}" \\\n', "--image-tag x; cat y; true \\\n"), + ('sudo -E "${AWF_BIN}" \\\n', 'cat y && sudo -E "${AWF_BIN}" \\\n'), + ], +) +def test_the_awf_call_has_no_shell_syntax_of_its_own(old: str, new: str) -> None: + """A redirection or substitution in the call writes around the filter.""" + workflow = copy.deepcopy(WORKFLOW) + assert edit_runs(workflow, old, new) + found = ws.sandbox_output_problems(workflow, SHELL) + assert len(found) == 4 and all("which can bypass the filter" in p for p in found), found + + +@pytest.mark.parametrize("line", ['cat "${WS}/prompt.md"', "set -x", 'export OPENAI_API_KEY="${KEY}"; env']) +def test_only_the_key_lines_precede_the_awf_call(line: str) -> None: + """The fetch sandbox has written the workspace: printing from it before the call is unfiltered.""" + workflow = copy.deepcopy(WORKFLOW) + step = next(s for s in workflow["jobs"]["review"]["steps"] if s.get("name") == "Run the review in the sandbox") + step["run"] = step["run"].replace("unset KEY\n", f"unset KEY\n{line}\n") + found = ws.sandbox_output_problems(workflow, SHELL) + assert found and all("before the awf call is not one of" in p for p in found), found + + +def test_a_filtered_awf_call_passes() -> None: + script = ( + 'sudo -E "${AWF_BIN}" \\\n --config c \\\n -- run-review "${WS}" 2>&1 \\\n' + + FILTER + + '\n # its status\n exit "${PIPESTATUS[0]}"\n' + ) + workflow = {"jobs": {"review": {"steps": [{"name": "Run", "run": script}]}}} + assert ws.sandbox_output_problems(workflow, SHELL) == [] + + +def test_diag_filter_is_required() -> None: + for rule in ("-e 's/##\\[/#\\xe2\\x80\\x8b#[/g' ", "-e 's/\\x00//g' "): + weakened = COMMON_SH.replace(rule, "") + assert weakened != COMMON_SH + assert ws.sandbox_output_problems(WORKFLOW, {**SHELL, ws.COMMON_SH: weakened}) + + +@pytest.mark.parametrize( + "change", + [ + # The filter only in a comment, 'diag' unfiltered. + lambda sh: sh.replace("diag() {", f"# {ws.DIAG_FILTER}\ndiag() {{").replace( + "cut -c1-400 |\n", "cut -c1-400 >&2\n#" + ), + # Output that bypasses the filter. + lambda sh: sh.replace("diag() {\n", "diag() {\n tee /dev/stderr |\n echo x >&2\n", 1), + # No 'diag' at all. + lambda sh: sh.replace("diag() {", "diag2() {"), + ], +) +def test_diag_must_be_one_filtered_pipeline(change: Any) -> None: + weakened = change(COMMON_SH) + assert weakened != COMMON_SH + found = ws.sandbox_output_problems(WORKFLOW, {**SHELL, ws.COMMON_SH: weakened}) + assert len(found) == 1 and "'diag' is" in found[0], found + + +@pytest.mark.parametrize( + ("path", "definition"), + [ + (ws.COMMON_SH, "diag() { cat >&2; }"), + (ws.COMMON_SH, "function diag { cat >&2; }"), + ("harnesses/stub/run.sh", " diag () {\n cat >&2\n}"), + ], +) +def test_diag_must_be_defined_once(path: str, definition: str) -> None: + """Bash runs the last definition, so a second one would replace the filtered 'diag'.""" + shell = {**SHELL, path: SHELL[path] + "\n" + definition + "\n"} + found = ws.sandbox_output_problems(WORKFLOW, shell) + assert len(found) == 1 and "'diag' is defined in" in found[0], found + + +def test_diag_breaks_legacy_commands(tmp_path: pathlib.Path) -> None: + script = tmp_path / "t.sh" + script.write_text( + f'. "{ws.AR_DIR}/harnesses/common.sh"\n' + 'printf "a ##[warning]x\\n::error::y\\nb #\\0#[error]z\\n" | ADAPTER_NAME=t diag\n' + ) + result = subprocess.run(["/usr/bin/bash", str(script)], capture_output=True, timeout=30, check=True) + assert result.stderr == "t| a #\u200b#[warning]x\nt| ::error::y\nt| b #\u200b#[error]z\n".encode() + + +# --- The collect gate ------------------------------------------------------------- + +GATE = "always() && steps.key.outputs.skipped != 'true' && steps.teardown.outcome == 'success'" + + +def gate_workflow(condition: object, teardown_id: str = "teardown") -> dict[str, Any]: + collect: dict[str, object] = {"name": "Collect the result", "run": "true\n"} + if condition is not None: + collect["if"] = condition + steps = [{"name": "Stop the sandbox", "id": teardown_id, "run": "true\n"}, collect] + return {"jobs": {"review": {"steps": steps}, "review-keyless": {"steps": copy.deepcopy(steps)}}} + + +def test_real_collect_gate_passes() -> None: + assert ws.collect_gate_problems(WORKFLOW) == [] + assert ( + sum( + step.get("name") == "Collect the result" + for job in WORKFLOW["jobs"].values() + for step in job.get("steps", []) + ) + == 2 + ) + + +@pytest.mark.parametrize( + "condition", + [ + GATE, + f"${{{{ {GATE} }}}}", + "steps.teardown.outcome == 'success'", + "always() && steps.teardown.outcome == 'success'", + ], +) +def test_collect_gate_accepts(condition: str) -> None: + assert ws.collect_gate_problems(gate_workflow(condition)) == [] + + +@pytest.mark.parametrize( + "condition", + [ + None, + "always()", + "always() && steps.key.outputs.skipped != 'true'", + "always() && steps.teardown.outcome != 'success'", + "always() && steps.teardown.outcome == 'failure'", + f"{GATE} || always()", + "always() || steps.teardown.outcome == 'success'", + "always() && !(steps.key.outputs.skipped == 'true' && steps.teardown.outcome == 'success')", + "always() && (steps.teardown.outcome == 'success')", + "always() && steps.teardown.conclusion == 'success'", + ], +) +def test_collect_gate_rejects(condition: str | None) -> None: + assert len(ws.collect_gate_problems(gate_workflow(condition))) == 2 + + +def test_collect_gate_needs_the_teardown_step() -> None: + found = ws.collect_gate_problems(gate_workflow(GATE, teardown_id="stop")) + assert len(found) == 2 + assert all("no earlier step with id 'teardown'" in p for p in found) + + +def test_collect_gate_needs_a_collect_step() -> None: + assert ws.collect_gate_problems({"jobs": {"review": {"steps": []}}}) == ["no 'Collect the result' step found"] + + +def test_collect_gate_in_the_real_workflow_is_required() -> None: + workflow = copy.deepcopy(WORKFLOW) + for job in workflow["jobs"].values(): + for step in job.get("steps", []): + if step.get("name") == "Collect the result": + step["if"] = step["if"].replace(" && steps.teardown.outcome == 'success'", "") + assert len(ws.collect_gate_problems(workflow)) == 2 + + +# --- PATH on the host ------------------------------------------------------------------ + + +def host_steps(workflow: dict[str, Any]) -> list[dict[str, Any]]: + return [ + step + for job in workflow["jobs"].values() + for step in job.get("steps", []) + if ws.PYTHON_CALL in step.get("run", "") and '"${AWF_BIN}"' not in step.get("run", "") + ] + + +def test_real_host_paths_pass() -> None: + assert ws.host_path_problems(WORKFLOW) == [] + names = {step["name"] for step in host_steps(WORKFLOW)} + assert {"Authorize", "Render the review", "Publish the review", "Collect the result"} <= names + + +@pytest.mark.parametrize("name", ["Authorize", "Render the review", "Publish the review", "Collect the result"]) +@pytest.mark.parametrize("path", [None, "/usr/local/bin:/usr/bin:/bin", "/usr/bin", ""]) +def test_host_call_without_the_fixed_path_fails(name: str, path: str | None) -> None: + workflow = copy.deepcopy(WORKFLOW) + for step in host_steps(workflow): + if step["name"] == name: + env = step.setdefault("env", {}) + if path is None: + env.pop("PATH", None) # the review jobs share this step (a YAML alias) + else: + env["PATH"] = path + found = ws.host_path_problems(workflow) + assert any(f"/{name}: calls an entry point on the host with PATH" in p for p in found), found + + +def test_awf_steps_are_exempt_and_a_missing_host_step_fails() -> None: + # The AWF steps call run-review inside the sandbox and set no PATH. + awf = [s for j in WORKFLOW["jobs"].values() for s in j.get("steps", []) if '"${AWF_BIN}"' in s.get("run", "")] + assert awf and all("PATH" not in (s.get("env") or {}) for s in awf) + workflow = copy.deepcopy(WORKFLOW) + workflow["jobs"]["authorize"]["steps"] = [ + s for s in workflow["jobs"]["authorize"]["steps"] if s.get("name") != "Authorize" + ] + assert ws.host_path_problems(workflow) == ["authorize/Authorize: no host call of an entry point"] + + +# --- After the sandbox (invariant 3) ------------------------------------------------------------- + + +def after_agent(workflow: dict[str, Any], job: str = "review") -> list[dict[str, Any]]: + steps: list[dict[str, Any]] = workflow["jobs"][job]["steps"] + return steps[[step.get("id") for step in steps].index("agent") + 1 :] + + +def step_named(workflow: dict[str, Any], name: str, job: str = "review") -> dict[str, Any]: + return next(step for step in after_agent(workflow, job) if step.get("name") == name) + + +def test_real_post_sandbox_steps_pass() -> None: + assert ws.post_sandbox_problems(WORKFLOW) == [] + names = [step["name"] for step in after_agent(WORKFLOW)] + assert names[:4] == ["Stop the sandbox", "Collect the result", "Upload the result", "Report token usage"] + + +@pytest.mark.parametrize( + ("name", "change", "expected"), + [ + ("Stop the sandbox", {"env": {"PATH": "/usr/bin:/bin", "GH_TOKEN": "x"}}, "'GH_TOKEN'"), + ("Stop the sandbox", {"env": {"PATH": "/usr/bin:/bin", "T": "${{ github.token }}"}}, "'github.token'"), + ( + "Report token usage", + {"env": {"PATH": "/usr/bin:/bin", "T": "${{ secrets.inference_api_key }}"}}, + "'secrets.'", + ), + ( + "Upload the result", + {"with": {"name": "x", "path": "p", "github-token": "${{ github.token }}"}}, + "'github.token'", + ), + ("Report token usage", {"shell": None}, "shell is not"), + ("Make the AWF audit log readable", {"shell": "bash"}, "shell is not"), + ("Collect the result", {"env": {}}, "env PATH is not"), + ("Stop the sandbox", {"env": {"PATH": "/home/runner/.local/bin:/usr/bin:/bin"}}, "env PATH is not"), + ("Upload the result", {"path": "${{ runner.temp }}"}, "the result upload's path is not"), + ("Upload the result", {"path": "${{ github.workspace }}/agent-review/out"}, "the result upload's path is not"), + ("Upload the result", {"name": "renamed"}, "0 result upload(s)"), + ("Upload the AWF audit log", {"uses": "actions/cache@0123456789abcdef0123456789abcdef01234567"}, "action"), + ], +) +def test_post_sandbox_rules_reject(name: str, change: dict[str, Any], expected: str) -> None: + workflow = copy.deepcopy(WORKFLOW) + step = step_named(workflow, name) + for key, value in change.items(): + if key in ("path", "name"): + step["with"][key] = value + elif value is None: + step.pop(key) + else: + step[key] = value + found = ws.post_sandbox_problems(workflow) + assert any(expected in p and p.startswith("review") for p in found), found + + +def test_post_sandbox_rules_cover_the_keyless_job_too() -> None: + workflow = copy.deepcopy(WORKFLOW) + # Unshare the aliased step, then break it in the keyless job only. + steps = workflow["jobs"]["review-keyless"]["steps"] + index = next(i for i, step in enumerate(steps) if step.get("name") == "Report token usage") + steps[index] = {**steps[index], "env": {}} + assert ws.post_sandbox_problems(workflow) == ["review-keyless/Report token usage: env PATH is not '/usr/bin:/bin'"] + workflow["jobs"]["review"]["steps"] = [s for s in workflow["jobs"]["review"]["steps"] if s.get("id") != "agent"] + assert "review: no step with 'id: agent'" in ws.post_sandbox_problems(workflow) + + +@pytest.mark.parametrize("job", ["review", "review-keyless"]) +@pytest.mark.parametrize( + ("key", "value", "expected"), + [ + ("env", {"GH_TOKEN": "x"}, "'GH_TOKEN' in env/GH_TOKEN"), + ("env", {"T": "${{ github.token }}"}, "'github.token' in env/T"), + ("env", {"K": "${{ secrets.inference_api_key }}"}, "'secrets.' in env/K"), + ("defaults", {"run": {"shell": "GH_TOKEN=${{ github.token }} bash {0}"}}, "in defaults/run/shell"), + ], +) +def test_post_sandbox_rules_check_the_job_env(job: str, key: str, value: dict[str, Any], expected: str) -> None: + # A job-level 'env:' or 'defaults:' reaches every step after the sandbox too. + workflow = copy.deepcopy(WORKFLOW) + workflow["jobs"][job][key] = {**(workflow["jobs"][job].get(key) or {}), **value} + found = ws.post_sandbox_problems(workflow) + assert any(p.startswith(f"{job}: ") and expected in p for p in found), found + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ({"GH_TOKEN": "${{ github.token }}"}, "workflow: token reference 'GH_TOKEN' in env/GH_TOKEN"), + ({"T": "${{ github['token'] }}"}, 'token reference "github[\'token" in env/T'), + ({"T": "${{ secrets['K'] }}"}, "token reference 'secrets[' in env/T"), + ({"GITHUB_TOKEN": "x"}, "workflow: token reference 'GITHUB_TOKEN' in env/GITHUB_TOKEN"), + ], +) +def test_post_sandbox_rules_check_the_workflow_env(value: dict[str, str], expected: str) -> None: + workflow = copy.deepcopy(WORKFLOW) + workflow["env"] = value + found = ws.post_sandbox_problems(workflow) + assert any(expected in p for p in found), found + + +@pytest.mark.parametrize( + "value", + [ + "${{ toJSON(github) }}", + "${{ github }}", + "${{ github.* }}", + "${{ format('{0}', github) }}", + "${{ GitHub.Token }}", + "${{ github [ 'TOKEN' ] }}", + "${{ github[format('{0}', 'token')] }}", + "${{ toJSON(secrets) }}", + "${{ secrets['k'] }}", + "${{ Secrets.K }}", + ], +) +def test_whole_contexts_are_token_references(value: str) -> None: + assert ws.context_refs(value), value + workflow = copy.deepcopy(WORKFLOW) + step_named(workflow, "Collect the result")["env"]["T"] = value + found = ws.post_sandbox_problems(workflow) + assert any(p.startswith("review/Collect the result: token reference") for p in found), found + + +@pytest.mark.parametrize( + "value", + [ + "${{ github.event.pull_request.number }}", + "${{ github['event_name'] }}", + "${{ github.workspace }}/x", + "${{ steps.github.outputs.x }}", + "${{ contains(github.event_name, 'github') }}", + "https://github.com/o/r", + ], +) +def test_named_github_properties_are_not_token_references(value: str) -> None: + assert ws.context_refs(value) == [] + + +def test_secret_refs_are_only_secrets() -> None: + assert ws.secret_refs("${{ toJSON(secrets) }} ${{ github }} ${{ secrets.k }}") == ["secrets", "secrets.k"] + assert ws.secret_refs("${{ toJSON(github) }}") == [] + + +@pytest.mark.parametrize("job", ["review", "review-keyless"]) +@pytest.mark.parametrize("state_file", ["GITHUB_ENV", "GITHUB_PATH"]) +def test_a_token_step_must_not_write_step_state(job: str, state_file: str) -> None: + """A step that holds the token could pass it on to every later step through $GITHUB_ENV.""" + workflow = copy.deepcopy(WORKFLOW) + steps = workflow["jobs"][job]["steps"] + index = next(i for i, step in enumerate(steps) if "GH_TOKEN" in (step.get("env") or {})) + steps[index] = {**steps[index], "run": steps[index]["run"] + f'\necho "T=$GH_TOKEN" >> "${state_file}"\n'} + found = ws.post_sandbox_problems(workflow) + assert any(p.startswith(f"{job}/") and "writes $GITHUB_ENV or $GITHUB_PATH" in p for p in found), found + + +@pytest.mark.parametrize( + "name", ["BASH_ENV", "ENV", "SHELLOPTS", "BASHOPTS", "BASH_FUNC_cat%%", "LD_PRELOAD", "NODE_OPTIONS"] +) +@pytest.mark.parametrize( + "where", ["workflow", "review", "review/Collect the result", "review-keyless/Fetch trusted files"] +) +def test_no_startup_variable_in_the_review_jobs(name: str, where: str) -> None: + """BASH_ENV runs a file before the step's script, '--noprofile --norc' notwithstanding.""" + workflow = copy.deepcopy(WORKFLOW) + if where == "workflow": + node = workflow + elif "/" not in where: + node = workflow["jobs"][where] + else: + job, name_ = where.split("/") + node = next(s for s in workflow["jobs"][job]["steps"] if s.get("name") == name_) + node["env"] = {**(node.get("env") or {}), name: "${{ github.workspace }}/agent-review/out/env.sh"} + found = ws.post_sandbox_problems(workflow) + assert any(p.startswith(f"{where}: sets {name!r}") for p in found), found + + +@pytest.mark.parametrize("where", ["workflow", "review", "review-keyless", "review/Fetch trusted files"]) +def test_no_startup_variable_in_a_shell(where: str) -> None: + """A default shell reaches the agent step, which runs after the fetch sandbox and holds the key.""" + workflow = copy.deepcopy(WORKFLOW) + shell = "env BASH_ENV=${{ github.workspace }}/agent-review/out/e.sh bash -e {0}" + if where == "workflow": + workflow["defaults"] = {"run": {"shell": shell}} + elif "/" not in where: + workflow["jobs"][where]["defaults"] = {"run": {"shell": shell}} + else: + job, name = where.split("/") + next(s for s in workflow["jobs"][job]["steps"] if s.get("name") == name)["shell"] = shell + found = ws.post_sandbox_problems(workflow) + assert any(p.startswith(f"{where}: shell ") and "names 'BASH_ENV'" in p for p in found), found + + +@pytest.mark.parametrize("line", ['echo "BASH_ENV=${WS}/out/x" >> "$GITHUB_ENV"', "echo LD_PRELOAD=x >> $GITHUB_ENV"]) +def test_no_startup_variable_through_github_env(line: str) -> None: + workflow = copy.deepcopy(WORKFLOW) + step = next(s for s in workflow["jobs"]["review"]["steps"] if s.get("name") == "Render the AWF configuration") + step["run"] = step["run"] + line + "\n" + found = ws.post_sandbox_problems(workflow) + assert any("writes $GITHUB_ENV or $GITHUB_PATH and names a startup variable" in p for p in found), found + + +def test_steps_before_the_agent_may_hold_the_token() -> None: + # 'Fetch trusted files' and 'Prepare the sandbox inputs' use GH_TOKEN before the sandbox runs. + assert ws.post_sandbox_problems(WORKFLOW) == [] + before = WORKFLOW["jobs"]["review"]["steps"] + assert any("GH_TOKEN" in (step.get("env") or {}) for step in before[: [s.get("id") for s in before].index("agent")]) diff --git a/agent-review/tests/requirements.in b/agent-review/tests/requirements.in new file mode 100644 index 0000000..cb77930 --- /dev/null +++ b/agent-review/tests/requirements.in @@ -0,0 +1,6 @@ +# Test-only tools for the self-test's 'python' job, never imported at run time. +# Compile: uv pip compile --generate-hashes --python-version 3.12 --universal requirements.in -o requirements.txt +mypy +pytest +pyyaml +types-pyyaml diff --git a/agent-review/tests/requirements.txt b/agent-review/tests/requirements.txt new file mode 100644 index 0000000..60503ed --- /dev/null +++ b/agent-review/tests/requirements.txt @@ -0,0 +1,369 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile --generate-hashes --python-version 3.12 --universal requirements.in -o requirements.txt +ast-serialize==0.13.1 \ + --hash=sha256:02686b281ec9b8e9614f6f0db27e12e4cac515f336c5d05b678bc9eb73ff2af5 \ + --hash=sha256:032b09d86c785c3984e975378b7861f2a68ac44e22ba7b07b93a536b2524eeb8 \ + --hash=sha256:0d764913374ba21df8cd618045b371ed104ce55c6276de7c59e554a4f5ba26fd \ + --hash=sha256:121e1d08d58b75c15491cc3003609cbad71ac2b0016043c36d30a6b2032b6605 \ + --hash=sha256:1b158f1c9e3a0d386913924c57995d6df78224868a4d0f215bdd41587c97b34a \ + --hash=sha256:2015fd0165e463aac3b1aadc6a1fa1e5820c14ca950821f4fe02f8a3f6a388d6 \ + --hash=sha256:23d768369b89d551077dc173da6892fad00443338417523b6732f4e8ba4a7ed5 \ + --hash=sha256:2876444a5f87a7c76f371af3c07c2fda563a08bc8af52568df812e8aba4bf568 \ + --hash=sha256:29422d7bcd9e7f39411571c36cec45ce8a7a9b3ad4b2e7aa64497c15a9e397f6 \ + --hash=sha256:2bad302ae2427454ef9dab71bd5c3ad67188860c39d36daee38f72031edb39c4 \ + --hash=sha256:2f9a9ce8b0994f757b941f7f7fe384a6666b4162b941ebc5c248081baea18e47 \ + --hash=sha256:30cf89b6a6844542d116c758725d13de5b97b9410a51ee577715f761270d0c1c \ + --hash=sha256:3e129d44b0cffbea24a7f40117ce49e30993c3d119e584d4817ebd6f87246456 \ + --hash=sha256:401cc84e8888d4d76f2c8d296fa006ed1a5ff993b6aff90dd777c03973efd025 \ + --hash=sha256:43e8ddd63e80fc280c2f790157386f27f9b9f6ccb9c4f8e803b863cbfb085769 \ + --hash=sha256:48f11d96c9ec71119612f8e79a8c55c12f2b136716d68347433c561d27a25f43 \ + --hash=sha256:4bcf1d5f4eefecaa325a34ecf079b2741189e7d0821523f92cb343a389a67489 \ + --hash=sha256:4e385b17d5bde892a6184003a9aff3518387908b73f8f5ea539313c07c8c0ede \ + --hash=sha256:4f98da562e5901d69c7dd30885594c5438f859edf354e9ac7517d188fb026c3a \ + --hash=sha256:523d45bab16ddaf1399c04c4fe81bbf180f81e33c2f7bcbe76be56b0f7311ab4 \ + --hash=sha256:5d99910e6b9a9b9360bcca2ae99aee36cc912ce058df2a57d1c33099b6cb2593 \ + --hash=sha256:5db12d843d931b9d1f1519ce66b9cbfe72d8563b75c1204d255322254d1964dd \ + --hash=sha256:638333fb8ae72c62753f9e794fda20290883ddc65b0d85e26e08f8bb227567ad \ + --hash=sha256:68f8829d114dab6c9db4a8bbb8d0e342958faee1b5e15a29022678df639960f8 \ + --hash=sha256:6eb0be64c9b8f1ed26637eef345abe75ea90351c92c85a8aec7838b3af971011 \ + --hash=sha256:6ffb0f548a7dc126067fdfb7b2325ab5dfcdeecc29faf5e0f0461c96d6ebfa3d \ + --hash=sha256:732aaae9e498c973fc63fd7f308009b57c4afa6ff59d0b674d894e57d0bca01a \ + --hash=sha256:75d7750fe98f6f35a96c43aba8d98a2e623e22c778a0c17ab9ede92eb10f5d82 \ + --hash=sha256:77a6201b69ce42e919f2fd9a559138d5410b5d8afff7c3a6b1f500b0481ff7d8 \ + --hash=sha256:7a5c38bdb93669c596f94fb7204dd6ebe4fadb19058ac9a2faf2948c2a175f96 \ + --hash=sha256:7f2427bddfca208e84de700044fadf9aef2769a70bae740a1bdabb89ee9e1117 \ + --hash=sha256:7f3e8a3eff69af640db985360fef35073fb46956dfc3e5c614cf00920d2746dd \ + --hash=sha256:847cad4c22953823f5e76d0b126c6f9da670cfa45b1df41b9324e22189d77611 \ + --hash=sha256:87427913c325adc811e81e7c9a757b061f47ef1e29114ac479aa0953a2687a98 \ + --hash=sha256:885a62ec6481ce58ab24c6357360d7a82023b62dd7e5e7ceccf59e9662a3272b \ + --hash=sha256:8899c038b1c15ae8b98e379057fb3ef398ceb0b21d1737a8156dd5a0923b7e51 \ + --hash=sha256:88df960e67184a71874e5b2ee014f87d1254a0dbc1f903c7bd7b1ab7733ecaef \ + --hash=sha256:8c8ebd419811c435812d242fb2a173e57dfede198c9ac9a0a584666ebc9b9331 \ + --hash=sha256:9221e09496fb942901993c1812ee87950cc0ecbb514c7c0f1f5fa6d78f701ed8 \ + --hash=sha256:929eda0c419e622ab49df3a4c45f81c57dcc10874bbad55d0470a4a03324dac3 \ + --hash=sha256:9f99786e0d62082a5b121b3437f3167562133711df22128de1e9886f57f0b226 \ + --hash=sha256:a01b515b25a03184eff4acef25b981ae007916379682e908fc8785b342a0bf3e \ + --hash=sha256:a789cbe14d0a0e9ec9b32a456e5abc81ad8799479c3cfd88a29e3442262aebe6 \ + --hash=sha256:a8ab2c2585b2e22e48cd4aff2136fce4eab4ced569b85f150ef9a5a5d6f34d49 \ + --hash=sha256:aca07de3ca8e3d9f2b716c3c31f4f384fe4bd2d03e09912417cff7a3e08036f7 \ + --hash=sha256:acf4e9f055d75058ab01536da330648746f2f82b7697a85230547f2d5ebe895c \ + --hash=sha256:ad88921f95b92bc144d9ad059a0e16f8c1ae69f5239f2d3c6536fd2774f73dfe \ + --hash=sha256:bf53a3ba1cbe45399fc1e4ccd684b8f2a11cca450f89706b79122f478534c6f5 \ + --hash=sha256:c652d9f5d52d8b81eff3ff2c95c9dd0f281de45f6ad5d3fa95527550c396454a \ + --hash=sha256:ca9acc67f796aa2554fa3037dccc022a4b08b38b2ad153edfac9c9bb7cb1f3c6 \ + --hash=sha256:cc34c670747d85d4232834665e247009413eaebe47c69eaf60a5c439aaecaed9 \ + --hash=sha256:d9c1a920b2aa0c1e016bed7721689717034ca0dba64ac3a3ff243b003d4e8dd8 \ + --hash=sha256:ddf7cbc9c8abf70102c4a088efe154bb86bfb825b0a10e556d2b15972cf99bd7 \ + --hash=sha256:e14c4de98f965647a74e6eaf37e20207124e45451ccd36e84a6f6ebab45e0372 \ + --hash=sha256:eb41e1906502ac80d24ff343f45008552a3f5b5158607959fe6a07dbfc6eb037 \ + --hash=sha256:f8b17e2921e56621bcb46792bd3e0b82ca3b85de78d5936e7b8174ba1758b0aa \ + --hash=sha256:fb8021f4dc3296de18737e3b8b34994411da725374d74a0b9eb32a738f2a23d0 + # via mypy +colorama==0.4.6 ; sys_platform == 'win32' \ + --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \ + --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 + # via pytest +iniconfig==2.3.1 \ + --hash=sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960 \ + --hash=sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7 + # via pytest +librt==0.16.0 ; platform_python_implementation != 'PyPy' \ + --hash=sha256:001bfd59a7d45b17e3e75f2a8c6405280b35e7b84471792778e718c4f368950e \ + --hash=sha256:0058f9d68721094105917254c72ac0569117bb7b13b9769cf45d26d89f9d21cd \ + --hash=sha256:02118f56a9c36ddd07dfd9b919d9ecc117ba20a90987d56aa4c429fa34509188 \ + --hash=sha256:0253721561787b8df8443eb347b7a6461015354e5bdd37ee38a41fef220d2bb0 \ + --hash=sha256:02d89c813d5ff74b17df72d3a34819d132cd168e56b81bf755b809bd9e46b8c4 \ + --hash=sha256:0314058469f4d2fd279ce7c62ac274ac82c3918ef7db62ef0697c4c359370155 \ + --hash=sha256:0dbe4096a7ecc00fa835d24510ad8545a4efef738dac96e0e63516783ccde905 \ + --hash=sha256:0ead24d2562a49473dddd9efef8581f020007eb0054389c3ee3ffad38b1ca4c9 \ + --hash=sha256:13b4e8aba90b0b1c82474e9844aa9ffe7ad3faa484350e1da64cb8188d903134 \ + --hash=sha256:14ed6ebe3e4f85f326d7920011ad30ff49ed9334e62cf88caef9ba973d9e3a92 \ + --hash=sha256:17bac7f7a16b328fff77e440287693eb017abde913595b5827ebccbc21ecd8a6 \ + --hash=sha256:1b384b90ab79a7bc30b566895809a636e0666f21f3cf12b54823d025b7e83839 \ + --hash=sha256:1bc17e54e5305f8d40b7ca203671ff5a9e59c1d0f8ea0f625dcca53a3984de11 \ + --hash=sha256:1d28ae980ae2218f9c5b95d191e947296f918c9bf0b400d467a9430275bbe678 \ + --hash=sha256:1e511762a074005bb0aa569166779834e75e438370226930d0ce1866d4b6a33b \ + --hash=sha256:20fe0bf9053885e21c62b3e091fb5e73e1c54d1daf2e70eb388d70763bcd4220 \ + --hash=sha256:242e00b3d4fa37c3d3c1ca5f5c9adb7d909ddb1eac9c41f2787320d00caa0af2 \ + --hash=sha256:25a58a19ea8d83b68209f04912df765e9260635ef77646542ed4b4abe6bc7940 \ + --hash=sha256:273d00be33792a15189331df10f1f1331621b043881e66c6c4377f7f776e1291 \ + --hash=sha256:28e038895b998d7a0c7798922ce8a1dc157675df5cf1c9ef0aca809ed804b7a1 \ + --hash=sha256:2bec3818c7da7c96ceae0ef5915a3d16c52dd08f3ea913bf1fe8568c447c7978 \ + --hash=sha256:2c4aa329c17bd1aaea4f6e89335d8ccd494b3a5830b6654462273e50e11023f0 \ + --hash=sha256:300c3ffdc459f4a779a8411ecb188e3ac0b1ff3a3a7b099642555dedae06c69b \ + --hash=sha256:30b7beaf3f4487b7d8adef1f158b49067cb4d5a19fa7a3bf31a4e7a820e435c5 \ + --hash=sha256:314e703f0c19320dc8094e7a784b9cf29e1b67402515abf580069a6363c0b4f1 \ + --hash=sha256:33f41443a1f4e1f099331b3d8120e409fbff84b9760bc1cc9ea496f37ddaa5cc \ + --hash=sha256:349c0bcb87ebd07481b6ff781e25cdc699723dbe2212e57dabb27f7a13b7b87d \ + --hash=sha256:36e53948e99bbe3ffea257124cfcae1cfb01831555c9a9c903c9f9a72db7fd07 \ + --hash=sha256:375bfe6b572a8f6cfc398709356046173bf27e64c4c5edaf5f7062f051fb4bf9 \ + --hash=sha256:378dfaffb38e59c24a87cde5713cd865d51ff7383fa12947f3907f306ea1ca55 \ + --hash=sha256:3931f7a3db322e7f44e02a280e3949326ce9579ad388ee8d691dc7c76da9fb70 \ + --hash=sha256:39ca4f2f2fe05de8e63493da592d84311adabe5bef52b193851981da9816b302 \ + --hash=sha256:39ec1d5a14e37baf1450a6cabf03fe552340808bf1ad9d71824ab90117716459 \ + --hash=sha256:3ddeb3c9dedb461bb457c6c7d9aa7fbf35329da313d1a7543d00c8d0f3473c96 \ + --hash=sha256:3e0c39bdc85370422e8b637be76eb1fd07d30967551b03e62267dd156f553152 \ + --hash=sha256:3e483a8d69ede8067db70c0e83007423b6925de6fd53afed01d66160f2e9398c \ + --hash=sha256:3f0b8114c44b2ac06ff5dacd08e07e8e807ff4f46083f2a1602685122559be41 \ + --hash=sha256:3ff4b2367926b69c6215635902cccb04048e73094e9862900d27cb2c6bbff143 \ + --hash=sha256:4323193ac0cd025f85af531df8ba91bf24d1973b401697347a6282e8fd3fcf5e \ + --hash=sha256:468df902df016a06eb0e40b0747dc8d14e47d7a38b18b63b1fb167d85cb94d63 \ + --hash=sha256:473eebc7866bb0a0c8849a292b5e7157c1aba5d14d0f0f610c52158d6d964262 \ + --hash=sha256:47ada6ea32636492c61aa8ad27ae3b9404bfe7a97e3ba946d1984236cc741da0 \ + --hash=sha256:4b6183e2e2e0ee00aac2ec07c7f7d151c97e85666b304f574b71cff0f9fccc4e \ + --hash=sha256:4e29522c62e28595ff7e324c6834ade51127707f0e255b18d1c1cf03d39c1048 \ + --hash=sha256:4eb1313a19847089ee81e88742abedf285c60538816640b99742d8534b81d26a \ + --hash=sha256:52327da75a94012e7f932f913d20d3876bed3c102be00e6c3e8600ff7bdd58a7 \ + --hash=sha256:54d11f726aae9df5a6ffbbf0a03a52449bbac84a53ef03669cb41cdfd4ae41bf \ + --hash=sha256:5696d7f52e7b37217cb3a8f92c744fe835942602fdd4c1a8bc4741d3bfdce15e \ + --hash=sha256:5750a105b42a416f930edc59054927a406effb2550cd5bab92ad7a5842ed5d05 \ + --hash=sha256:5810ba811297fdf37a1531a57667cb8ace0842013ca8606bf9eb7c24cf4be154 \ + --hash=sha256:5981c011b306781ce561e18e14230a14524a3d8109b97553666c942c18f31a96 \ + --hash=sha256:5a269c46ae327d8e6f8c1f85f7516cb52c0fa48127565a1105a4f4a05ff2a0b4 \ + --hash=sha256:5b976054553670829985ed767feb78fb6bcede0175327c4844dd5c281c1be659 \ + --hash=sha256:5bcc2c4726ced915b00de0c9856a4eeabfb3fddb93e10e0b8f735b7709358b6d \ + --hash=sha256:5cd5b092441053364af968ea12084692cb9d4a22f3ce9524e377880bf028761e \ + --hash=sha256:5f49cff01bd608ef7d97104cb035c75455e79c2d70bf4a506cf773338ac1860d \ + --hash=sha256:6072e92dd876ff6ceeb6cf371e35e51f479349837391341f479b08df4564242b \ + --hash=sha256:64c79520414a3fdfc6aabd7593e6169afa14d5f8d9908d4b498db068868b08dd \ + --hash=sha256:67e718c7a43f8db325abbbf1404e2d535f12f8f7a1a82259568385cc5274b82a \ + --hash=sha256:69ba927445cfaaffb4081003ef5224c55a5c2ab67ef956f416ef744916e44121 \ + --hash=sha256:6a63610fa76524edfa605b5b259a603915c7a6e10e54f003e5503030506e81de \ + --hash=sha256:6c5da27e8056439f927ea896735da60e616c477a8293feaa3233d4e7781a6726 \ + --hash=sha256:6c8893eae2fd13c5488d94056f3e6e5cf3142bfb1c4acaf136cb33d760c5964b \ + --hash=sha256:6d4a64283ee61824b5790de882bc68e2d9d7a5143537cb7a966f7354f71646d4 \ + --hash=sha256:6fe436af2eaf630474f491af5d032cbe45f93fcff5c3b9fe4ab194a7255b20ff \ + --hash=sha256:71b93b42784e25b975079573c642a8fedb049a7bb31d70a51721b1666b3b2ced \ + --hash=sha256:7393c9a48dcce4817dbd4b0d8ff6237efe9b0a0609f5b0adaef315f8541726b5 \ + --hash=sha256:77c7a2b4fe2c1369e0d5aa1cade26740a7b14be32fbc9a5535d617d20065c39d \ + --hash=sha256:7a1d272724b581bb6bc769dfdafed6da2ecc9886ba2450311de55a4ac2e1e9cd \ + --hash=sha256:7cc365f006891afb006b52d5ee5ee74c09306ffa20e2f8705a32a4450af2f3ba \ + --hash=sha256:7e510b7770bee609617a3374a96548eb114cae048023e3f049ee449e7ff2db32 \ + --hash=sha256:80039ba9b6a7d5f1a0175a4cca6bbefead87bd854c80abad1cb30afe47a830db \ + --hash=sha256:83d4041a3d9b2fd053a8a4e1f22878b3e5833e2712956382d5c048d791454e91 \ + --hash=sha256:845a511b60ca43b9880dcc84a9784c891d6a2098c829130b320846c69c9c0c68 \ + --hash=sha256:877698bf6bca5721d8be345f2fe09778e40ecadea8b58c73075f2b1a53666bf2 \ + --hash=sha256:8caf96a4ef8fb27d0ac0d1ad8337d26a240acd4a02fe4345d0a8f264753e8f99 \ + --hash=sha256:8ceafb70f2a4f0826f11031942e59c0728fd98da112dc346d4352bde1e486866 \ + --hash=sha256:8f36c58e33b304b525c6c9c5076399c6ebf1109e17b9051a05a407b091b9215b \ + --hash=sha256:8ff5d26c529336be9bd7ae04483235d77778ee7d6444a95353102b542601ce81 \ + --hash=sha256:909d8e3c1faee44cb762b1c519ff8613dcc5ceae5c99987a00917b5a31fd1d6a \ + --hash=sha256:92caf82ebef5e12d21c72242b70d1e92536f1711cf2a727a4c276de4b4469087 \ + --hash=sha256:931a0bb0fcac88f263e269e46eb30ba8e21402cd3c62ca40cb97034c0693fab1 \ + --hash=sha256:943c6bbecbdf7fa575a4f2952fcfd848c88ef95507c3fca411e89d4ac3ff8143 \ + --hash=sha256:94aed6a8308818b91677957d1bd03188869cd7aeb23c5dba7912a6c0402f7602 \ + --hash=sha256:94be5cb7bca4df6201f4183e9e4fa2086c655283d20b38cd84500a69057575a7 \ + --hash=sha256:953107e2f68d0f3512c48f898b0dbf0ce5cc52bba0f318d847c985dc555ee4cc \ + --hash=sha256:96f576f2711f8519152ec76d0e599243555c1f07679fa73606ca8c8c868c0be6 \ + --hash=sha256:a33e0dae1f8592146a4764d54ce842b278732d21a84e17c3bbe6b1bc158a2248 \ + --hash=sha256:a4aaefb4ba6c07e1aeebb2795c8958148f1d6f9af3b555b53d23d766edb6d67a \ + --hash=sha256:a8afb6557920860b7a3a596eb804cf37e09e7cf8a803db2478c202acc72d8c2e \ + --hash=sha256:aa9357a1b4d4fc787bb718a59cb1112c28c8a976d6bfa268b71cc0a4ab8f3a94 \ + --hash=sha256:ac38d6d8d66bf3d744148dbbc0b8e193e195a51e364ed55e224631f5721891fc \ + --hash=sha256:ad37d5b9abd49c9a655dcda7ea52a8a752884062ef1ee71ae17c2f2a0f81fe6a \ + --hash=sha256:aea7b1f2b125dad5de85f049136651bff256c883c65e6b9209b2da0a1ac3cdef \ + --hash=sha256:afced3dfc17cd805ecf7a3d77996a71cf5f2c75aa66eb0c21a9930f4fc992f86 \ + --hash=sha256:b0e3e721c75d2e79a76d4422c79d7ba705fe1bbafec907037fe7a657a480a0e3 \ + --hash=sha256:b6d085d70bce51d43c5c7c36d63490770180d8779e71c49305c87b4213918de7 \ + --hash=sha256:b95d5d92ab83d39e760a52091bb1baba664f3a2351e39b1e16801e5747c2f0e9 \ + --hash=sha256:b9d6d4b14e92d876f8026b54c20c445f36425214c1081dc76f74e40db386b82b \ + --hash=sha256:bc02954b1295de798bbdb0b4e2d8a28c2117de8b5c73dcbeb27dc32572dfb971 \ + --hash=sha256:bd3150023d3dc2bc70f3784e59ffa1140d56ddba3d8125b3d6f9f85221279bfc \ + --hash=sha256:be56ba9c884143495b517f23fe794ae367d58cd89ea0fdd6d437e3c024a87f9f \ + --hash=sha256:c17194318e4c0c0348b36f36c2ec7534436fe0a4c15582403162a4f08c80797a \ + --hash=sha256:c3d1bb7841a816ace6449bb26d3f9560dbfa20e71c568d23f0f62bf1e68f50b1 \ + --hash=sha256:c43bd6e642d8a248c114327f98dd25ac5a7cb5aa168ef02f0559b91874df16b8 \ + --hash=sha256:c5db585d43449a5f54303d4b2774e45e1babd975cfe1630a3d708c0b80c3e560 \ + --hash=sha256:c5e6144e68b577f157519f2ba88ca20e3ed61c29b00e5cdfa76cd2d45acf059a \ + --hash=sha256:c6f1b27bf1632a7e016af9f145f82be95e1edd7721a646505c21059257cb5a04 \ + --hash=sha256:c71d1b76210a36729fedfc5115069b50a3d8619054745f8758fe5d6f19e86671 \ + --hash=sha256:c72c5295a84bd249526da9bdca38f2e176d15c31c13bb0063c5053f4ca023421 \ + --hash=sha256:ca8052401c55d7511dda6760719fda7618067e83535d7d0010096d216c34b667 \ + --hash=sha256:d1aabe3925cbb4a08d15b7b20ba4011b53019da0c4173a25155139b7b1baed65 \ + --hash=sha256:d3c94211ee0c4f8d649ec06b7c115c0ec4eadb873a0e3154ca15cef3f814b071 \ + --hash=sha256:d46ca272b251d033dd4527b0dec5f261a28a52bd5fa0f99c117b0a1f8588cc2d \ + --hash=sha256:d608f0bf3b8cbddd0067fe02cb8cab7d13e8eb9386b23a1843d4363044fd9e22 \ + --hash=sha256:d6a365f2ab45a984d0e00eee0dd17f599ceab8cadab6ea07b6111c8132fc0e42 \ + --hash=sha256:d92db7a0f6aee44f1baee94750457e8d2d1c6ccea41842de6268d34e8dc7eddd \ + --hash=sha256:df183721229ae51eef90108c115b43e98cb169b6155d34480338e5fc6616df00 \ + --hash=sha256:e05108e0849966f53a8d2d3112a7af881d0efaa479bc735bba91108f9f2350a7 \ + --hash=sha256:e1967e36ac4cae0c7e9615ad32e1a513cdacff79f9e8afb28bedc91caf48b4f3 \ + --hash=sha256:e42f8e098b9c5396fefa05fb1cc7e33b0e08fc51da106b5de4a45fd22aac6743 \ + --hash=sha256:e56aaf8c167548dc8e5d6f3bd0f48dcdd299a23c73be3f744aab79d99e9c7f5d \ + --hash=sha256:e9ce0bc440e7fd09b5f51f372f0f6640658f854b8fb05260f819cc669c93c42d \ + --hash=sha256:ebefd60b42e2a82b32d136bb5f7c94eadfcd29f772b547df6f3291d1ed855a1c \ + --hash=sha256:ef46c1a29ffb8c72e882e22618ec618778eacd0578fb22c6e7cf9c11d15f357b \ + --hash=sha256:efc49c462d4516b8a58b00b490078fa64689fd1fe66970cc190131d7afb8027e \ + --hash=sha256:f01f3805f2dae4781c0c34b440e31740d082950bdaf89a6f601ad589a28af57a \ + --hash=sha256:f06c689cb14afd9b612727553a5ec5a40febf113ca41c4413a2b0b334285884b \ + --hash=sha256:f1e8591bd8a5a628cd7f07954c6a1592359a878bf032957a8e9057a41d644311 \ + --hash=sha256:f4462528b6000afe8f16907b5c7c2553abf1df005ba5140e6eb394541c3624c3 \ + --hash=sha256:f7be7cf555bc30ec12622e9447299cc4a9b8ff307548b634794353db0c2065dc \ + --hash=sha256:f81b5b19ce748ef68d4746656b7929762eb2fe99269b266e4be07e2ee4de7144 \ + --hash=sha256:f9807485a908f00355820f18e91e045ffdcdc5adb68aaec40a1e2b88c5f7bba1 \ + --hash=sha256:fbe4fb8c5445f7496d7f7f6bb0807875d09d47e6771ffa175fb2df2895fb86ba \ + --hash=sha256:fe4372c52d4849096c6cc1cda2817d293ec51440c890474ed59ef38d46556f18 \ + --hash=sha256:fe52bf4641069e7978a14253b036cb9002def1926317e710f2e249f8a8c47742 \ + --hash=sha256:ff7baa55f8e7c69851419e50a666015d02a74198716fd45c0125a2112e0a389f + # via mypy +mypy==2.4.1 \ + --hash=sha256:01b7718552d017f88d1151f3cc9d6556d778a90bd58060a2c3d87d070f9099fb \ + --hash=sha256:0724cf95fabc87ca4a2d5b7f276b43f51afce8a3804bde704490b008e377e50b \ + --hash=sha256:080cf64a60b90a73435542feecf4171904cc5710658165b40c6869115d4aa100 \ + --hash=sha256:0c5bf267645351887b72903fd2f5fbddcf85234e0e6c4ad94e2fcfb4f0c3f971 \ + --hash=sha256:0e95ad0bec03ced9a73b42514208abd24c789e67f0e1eba476e276dd7a2dea3a \ + --hash=sha256:0f0a8b8f5dee799195a3f2670a5b2617ac7193d3563f52dbef42ad6770c6a9db \ + --hash=sha256:133886ef1a7a8cf673df55d865e41580c6c46aa9b8e31e1325dfe315c038f745 \ + --hash=sha256:1784648d6ec8c2b5465e3f26241b845a0b3cb4e56c993c64abe16989e7698999 \ + --hash=sha256:1fb70621535c22fd4b1a0450d37ed1d6c5eb39656a1cebfb189084c12de54ba7 \ + --hash=sha256:2875280687e64740e6ddcef43bd4c5852ad45ff34549740f6aea3f0373870b93 \ + --hash=sha256:2b4e0aa029ad0c1d42cc494daf86d1e0efd15dab4db7bd096ece29e8a9689c6a \ + --hash=sha256:3467b1d13000812ab85dc2a3834b9379ec77798ca1bcabe434e23fb21fead692 \ + --hash=sha256:3f1613bfe6726169a5680ec3dad5fe1f6d96285c12aded51ad432eadedd39d45 \ + --hash=sha256:4af5ad558033bf71a44a1be149ed61633522824f84c1b6bc2445d3fe2d2a5296 \ + --hash=sha256:4c194c5d878130fca1ae662dfb1feb6274afbab0b40032c80147377e0ea803d5 \ + --hash=sha256:4e18d0da3898b3bcd16192f15a206e7b8b8dd0f4a0b3e51aa5bd5c2afe749e2c \ + --hash=sha256:51f742d4154824837ca6e92aa81f00eec222700a3c337bd258e5562a3880d75a \ + --hash=sha256:63b590965691e540a335fa74dadf31a7069142f6b72e234689bbd244edf55623 \ + --hash=sha256:63c6ff0e7ea546943001a91639c9f0c64b60d239268fa5d29e4a6c87f82c2373 \ + --hash=sha256:680ba5d9f0e3fe0c746b3d14df15f2a718e4bc308a1145616a1ea691ce7c354b \ + --hash=sha256:6f7225951a277dd0d6add900731d487174b7d24ac133c09d670ed63b4d8cb90d \ + --hash=sha256:70196470ac300f444a302a738541101893c2c57804078b33690286a7899149e9 \ + --hash=sha256:70971cc0bcb1d3f03d2eb68fa430a6481ccc03558dc001d9534d7e5fa274c392 \ + --hash=sha256:71eda06e5bae51976ce869fda429159c9cec678bd02f25bb197f0265c8f991be \ + --hash=sha256:727890a32f1858c09549eb55a8b234fe990d460450b28f03e8213ef925f1247c \ + --hash=sha256:7344869cad05f073b8cae2826774fa0161e3eb2f5c685b76813574008d77d750 \ + --hash=sha256:79a1e79199e980fb41f219cb3d4746d25c64b0b623840d3ed57df1cdc13a6502 \ + --hash=sha256:8e437811ebd26d3e6258efb562a711b385c139be597dffed5e735c801d15c77f \ + --hash=sha256:9d7dafd56179d296651df9e1844b91c9517c379398f017a2a435d077a28943c1 \ + --hash=sha256:9ed1195502cca32be5ef756b1693477f4991db2f2e34eaa90cc4ad6bea4f9531 \ + --hash=sha256:a20ff6cd2af7a670c64f089bfa5fbcebe8ff3bf896c5e6ac7c9862c7960e4494 \ + --hash=sha256:a2d4a51db92059eecc2c33b2a5194b28585ebfd917292c015fe87a77dbff6cd2 \ + --hash=sha256:a5b5da107dc2c93fb0a22f7a45dbaea5dc131afc7056b5468d78e819f9a138e6 \ + --hash=sha256:acdd82cb3a2eb10720e87706a128d75785d005a8c47e36a4973221524f41fc56 \ + --hash=sha256:b69a15fc2e75858d6b15e91ed3a0dcff1a533265183b64734138791fe0f49aa5 \ + --hash=sha256:be4c03f33c55500191df2ed4a9b5e7edbdd1fff067fe361a5a9b1b5d3262da6e \ + --hash=sha256:beb254fec368c4e7f7f82a5f310c6470b893ec88a90b66426da971c6826b0453 \ + --hash=sha256:c3a4d0c47053cc90035dd3a2c321112b593ad42935d0cbfd747288e1564fa8ca \ + --hash=sha256:c45485061ba08f700acc12cfc8b177e6997e6bc353605babfc0abb081e079456 \ + --hash=sha256:c535efcb91f7e66f41b9bd2b5dbd78900a7609ce88f4c020d668e4c82d082b0b \ + --hash=sha256:c6c7210e40dd423af7d65cbe428b5906d11dc60659337bdae4e5fdf02ce32ed7 \ + --hash=sha256:d4c343b2a720741a016d720b255e75581a50e2bede61d53250484e18562a1d64 \ + --hash=sha256:d63737426a048a27705a4eedb828669f4bc0873612a1b46b0b9fe892b2ebaaaf \ + --hash=sha256:d6e081b466e88d4343adffe11aff0f02df34b5b9070b4b700053a0b7294c0be1 \ + --hash=sha256:d923cec43316f0e6736b8298fd00abeaaf348a091c20e7296b3aebceecb63eca \ + --hash=sha256:db599d03e7d60d15f2e0a11665c18bc52a88699fcab990fdf8cecd5be8ac801c \ + --hash=sha256:de95648e0a6d46fa9929b956ed2c87c5dc9933d4d59945e6390e9d753c74e7c1 \ + --hash=sha256:ea0714d2bccaf6d010c970e1d3ba2c9c2add79d2030aad2ef03167d788948276 \ + --hash=sha256:ec416d5d2ae689e681f5727e328723f18d8b5dc8c903a146b7851dc5727aad8a \ + --hash=sha256:ef8d5be90032261197ac388d945d8ff4f476c95880798a1911760af64ddfe71f \ + --hash=sha256:f44dd4c5ab22df21206dd926c98381ebdbf5bfd696df37dd38ded2d23143fcb6 \ + --hash=sha256:f9118a3f50de264b614861bb11814833a742138ac3c8e2e49a860b6977fb2704 + # via -r requirements.in +mypy-extensions==1.2.0 \ + --hash=sha256:993e7a20aa5671eb41a7132cf555af30062da99729601601b9a8382b11cae768 \ + --hash=sha256:c6e275a07f1c2fc096b62940452d0eaa3f3af7de45d704787866240a7c6d5a51 + # via mypy +packaging==26.3 \ + --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ + --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c + # via pytest +pathspec==1.1.1 \ + --hash=sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a \ + --hash=sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189 + # via mypy +pluggy==1.7.0 \ + --hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec \ + --hash=sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8 + # via pytest +pygments==2.21.0 \ + --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \ + --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c + # via pytest +pytest==9.2.0 \ + --hash=sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588 \ + --hash=sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b + # via -r requirements.in +pyyaml==6.0.3 \ + --hash=sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c \ + --hash=sha256:0150219816b6a1fa26fb4699fb7daa9caf09eb1999f3b70fb6e786805e80375a \ + --hash=sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3 \ + --hash=sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956 \ + --hash=sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6 \ + --hash=sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c \ + --hash=sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65 \ + --hash=sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a \ + --hash=sha256:1ebe39cb5fc479422b83de611d14e2c0d3bb2a18bbcb01f229ab3cfbd8fee7a0 \ + --hash=sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b \ + --hash=sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1 \ + --hash=sha256:22ba7cfcad58ef3ecddc7ed1db3409af68d023b7f940da23c6c2a1890976eda6 \ + --hash=sha256:27c0abcb4a5dac13684a37f76e701e054692a9b2d3064b70f5e4eb54810553d7 \ + --hash=sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e \ + --hash=sha256:2e71d11abed7344e42a8849600193d15b6def118602c4c176f748e4583246007 \ + --hash=sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310 \ + --hash=sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4 \ + --hash=sha256:3c5677e12444c15717b902a5798264fa7909e41153cdf9ef7ad571b704a63dd9 \ + --hash=sha256:3ff07ec89bae51176c0549bc4c63aa6202991da2d9a6129d7aef7f1407d3f295 \ + --hash=sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea \ + --hash=sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0 \ + --hash=sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e \ + --hash=sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac \ + --hash=sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9 \ + --hash=sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7 \ + --hash=sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35 \ + --hash=sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb \ + --hash=sha256:5cf4e27da7e3fbed4d6c3d8e797387aaad68102272f8f9752883bc32d61cb87b \ + --hash=sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69 \ + --hash=sha256:5ed875a24292240029e4483f9d4a4b8a1ae08843b9c54f43fcc11e404532a8a5 \ + --hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b \ + --hash=sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c \ + --hash=sha256:6344df0d5755a2c9a276d4473ae6b90647e216ab4757f8426893b5dd2ac3f369 \ + --hash=sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd \ + --hash=sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824 \ + --hash=sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198 \ + --hash=sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065 \ + --hash=sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c \ + --hash=sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c \ + --hash=sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764 \ + --hash=sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196 \ + --hash=sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b \ + --hash=sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00 \ + --hash=sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac \ + --hash=sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8 \ + --hash=sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e \ + --hash=sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28 \ + --hash=sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3 \ + --hash=sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5 \ + --hash=sha256:9c57bb8c96f6d1808c030b1687b9b5fb476abaa47f0db9c0101f5e9f394e97f4 \ + --hash=sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b \ + --hash=sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf \ + --hash=sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5 \ + --hash=sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702 \ + --hash=sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8 \ + --hash=sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788 \ + --hash=sha256:b865addae83924361678b652338317d1bd7e79b1f4596f96b96c77a5a34b34da \ + --hash=sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d \ + --hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc \ + --hash=sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c \ + --hash=sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba \ + --hash=sha256:c2514fceb77bc5e7a2f7adfaa1feb2fb311607c9cb518dbc378688ec73d8292f \ + --hash=sha256:c3355370a2c156cffb25e876646f149d5d68f5e0a3ce86a5084dd0b64a994917 \ + --hash=sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5 \ + --hash=sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26 \ + --hash=sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f \ + --hash=sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b \ + --hash=sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be \ + --hash=sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c \ + --hash=sha256:efd7b85f94a6f21e4932043973a7ba2613b059c4a000551892ac9f1d11f5baf3 \ + --hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \ + --hash=sha256:fa160448684b4e94d80416c0fa4aac48967a969efe22931448d853ada8baf926 \ + --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0 + # via -r requirements.in +types-pyyaml==6.0.12.20261113 \ + --hash=sha256:0828be2580fd94151182364f4d0158e4de62fdbeeb8d4296f7f7d2b6c22bb640 \ + --hash=sha256:3600749e613748afdc4327f0b17c3296cf880cdbc7335f320007abd9dd815f67 + # via -r requirements.in +typing-extensions==4.16.0 \ + --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ + --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 + # via mypy diff --git a/agent-review/tests/run_review_fixtures.py b/agent-review/tests/run_review_fixtures.py new file mode 100644 index 0000000..0384cff --- /dev/null +++ b/agent-review/tests/run_review_fixtures.py @@ -0,0 +1,194 @@ +"""Test fixtures for run-review: crafted repositories, trusted roots and workspaces. + +A crafted pull request lives in a local "upstream" repository. run-review +always fetches from ``https://github.com/.git`` with the ``file`` +transport refused; the tests redirect that URL with an inherited +``url..insteadOf`` (``GIT_CONFIG_COUNT``) and allow the ``file`` +transport with ``GIT_ALLOW_PROTOCOL``, which overrides ``protocol.*.allow``. +run-review has no test hook for this: it reads its environment as in +production (the sandbox zone inherits it). +""" + +import json +import os +import pathlib +import shutil +import subprocess +from collections.abc import Mapping, Sequence + +AR_DIR = pathlib.Path(__file__).resolve().parents[1] +PYTHON_CALL = ["/usr/bin/python3", "-I", "-S", "-B"] + +COMMIT_ENV = { + "GIT_AUTHOR_NAME": "t", + "GIT_AUTHOR_EMAIL": "t@example.invalid", + "GIT_AUTHOR_DATE": "2026-01-01T00:00:00Z", + "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@example.invalid", + "GIT_COMMITTER_DATE": "2026-01-01T00:00:00Z", + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", +} + +Tree = Mapping[str, str | bytes | None] + + +def git(repo: pathlib.Path, *args: str, stdin: bytes | None = None) -> bytes: + return subprocess.run( + ["/usr/bin/git", "-C", str(repo), *args], + env={**os.environ, **COMMIT_ENV}, + input=stdin, + capture_output=True, + check=True, + ).stdout + + +def write_tree(repo: pathlib.Path, tree: Tree) -> None: + """Applies ``tree`` to the work tree: text or bytes, '-> target' for a symlink, + 'gitlink ' for a submodule entry (index only), None to delete.""" + for rel, content in tree.items(): + path = repo / rel + if content is None: + git(repo, "rm", "-r", "-q", "--", rel) + continue + if isinstance(content, str) and content.startswith("gitlink "): + git(repo, "update-index", "--add", "--cacheinfo", f"160000,{content.split()[1]},{rel}") + continue + path.parent.mkdir(parents=True, exist_ok=True) + if path.is_symlink() or path.is_file(): + path.unlink() + elif path.is_dir(): + git(repo, "rm", "-r", "-q", "--", rel) + shutil.rmtree(path, ignore_errors=True) + if isinstance(content, str) and content.startswith("-> "): + path.symlink_to(content[3:]) + elif isinstance(content, bytes): + path.write_bytes(content) + else: + path.write_text(content) + git(repo, "add", "--", rel) + + +def commit(repo: pathlib.Path, tree: Tree, message: str = "c") -> str: + write_tree(repo, tree) + git(repo, "commit", "-q", "--allow-empty", "-m", message) + return git(repo, "rev-parse", "HEAD").decode().strip() + + +class Upstream: + """A crafted upstream repository: a fork point, a base and a head commit.""" + + def __init__(self, path: pathlib.Path, slug: str = "example-org/example") -> None: + self.path = path + self.slug = slug + path.mkdir(parents=True) + git(path, "init", "-q", "-b", "main") + git(path, "config", "uploadpack.allowAnySHA1InWant", "true") + + def make(self, fork: Tree, base: Tree, head: Tree, *, depth: int = 0) -> tuple[str, str, str]: + """(fork, base, head): base and head both branch off the fork point, + each ``depth`` commits further away than the one commit that applies its tree.""" + fork_sha = commit(self.path, fork, "fork") + git(self.path, "checkout", "-q", "-b", "pr") + for i in range(depth): + commit(self.path, {"pr-history.txt": f"{i}\n"}, f"pr {i}") + head_sha = commit(self.path, head, "head") + git(self.path, "checkout", "-q", "main") + for i in range(depth): + commit(self.path, {"base-history.txt": f"{i}\n"}, f"base {i}") + base_sha = commit(self.path, base, "base") + return fork_sha, base_sha, head_sha + + def env(self) -> dict[str, str]: + """Environment that makes run-review fetch from here instead of github.com.""" + return { + "GIT_ALLOW_PROTOCOL": "file", + "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": f"url.file://{self.path}.insteadOf", + "GIT_CONFIG_VALUE_0": f"https://github.com/{self.slug}.git", + } + + +def make_root( + directory: pathlib.Path, + *, + rules: str = "", + extra: str = "", + addendum: bytes = b"", + central: str | None = None, +) -> pathlib.Path: + """A trusted root as the review job lays it out under /opt/agent-review.""" + directory.mkdir(parents=True) + for name in ("bin", "lib", "harnesses"): + shutil.copytree(AR_DIR / name, directory / name, symlinks=True) + for name in ("prompt.md.tmpl", "instruction-files.txt"): + shutil.copy(AR_DIR / name, directory / name) + if central is not None: + (directory / "instruction-files.txt").write_text(central) + subprocess.run( + ["/usr/bin/bash", str(directory / "harnesses/stub/install.sh"), str(directory / "harness/stub")], + capture_output=True, + check=True, + ) + config = directory / "config" + config.mkdir() + (config / "rule-files.txt").write_text(rules) + (config / "extra-instruction-files.txt").write_text(extra) + (config / "prompt-addendum.md").write_bytes(addendum) + return directory + + +def set_adapter(root: pathlib.Path, script: str) -> None: + """Replaces the stub adapter's run.sh.""" + (root / "harnesses" / "stub" / "run.sh").write_text(script) + + +def make_ws( + directory: pathlib.Path, + *, + repo: str = "example-org/example", + pr: int | str = 7, + head: str, + base: str, + pr_json: bytes | Mapping[str, object] | None = None, + **params: object, +) -> pathlib.Path: + (directory / "in").mkdir(parents=True) + values: dict[str, object] = { + "repo": repo, + "pr": pr, + "head_sha": head, + "base_sha": base, + "harness": "stub", + "model": "none", + "harness_timeout_minutes": 5, + "stub_padding_kib": 0, + "project": "Example", + } + values.update(params) + (directory / "in" / "params.json").write_text(json.dumps(values)) + if pr_json is None: + pr_json = {"title": "A title", "body": "A body."} + data = pr_json if isinstance(pr_json, bytes) else json.dumps(pr_json).encode() + (directory / "in" / "pr.json").write_bytes(data) + return directory + + +def entry_argv(root: pathlib.Path) -> list[str]: + """The production command line of the root's run-review.""" + return [*PYTHON_CALL, str(root / "bin" / "run-review")] + + +def run_review( + root: pathlib.Path, args: Sequence[str], env: Mapping[str, str] | None = None, timeout: float = 600 +) -> subprocess.CompletedProcess[bytes]: + """Runs run-review; stdout and stderr together, as AWF's '2>&1'.""" + return subprocess.run( + [*entry_argv(root), *args], + env={**os.environ, "LC_ALL": "C.UTF-8", **(env or {})}, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL, + timeout=timeout, + check=False, + ) diff --git a/agent-review/tests/test-authorize.sh b/agent-review/tests/test-authorize.sh index b38219e..a442962 100755 --- a/agent-review/tests/test-authorize.sh +++ b/agent-review/tests/test-authorize.sh @@ -52,7 +52,7 @@ setup_prt() { # action [ "$1" != labeled ] || export EVENT_LABEL=agent-review } -run() { bash "${AR_DIR}/bin/authorize" >log 2>&1; } +run() { run_entry "${AR_DIR}/bin/authorize" >log 2>&1; } out() { sed -n "s/^$1=//p" "${GITHUB_OUTPUT}" | tail -n 1; } allowed() { run || { cat log; return 1; }; assert "allowed" test "$(out allowed)" = true; } denied() { # expected log text: exit 1, allowed=false diff --git a/agent-review/tests/test-collect-result.sh b/agent-review/tests/test-collect-result.sh index a20d74c..52201c2 100755 --- a/agent-review/tests/test-collect-result.sh +++ b/agent-review/tests/test-collect-result.sh @@ -6,7 +6,7 @@ set -uo pipefail # shellcheck source=lib.sh . "$(dirname "$0")/lib.sh" -collect() { /usr/bin/bash "${BIN_DIR}/collect-result" "$@"; } +collect() { run_entry "${BIN_DIR}/collect-result" "$@"; } setup_out() { mkdir -p "${TMP}/ws/out" @@ -75,7 +75,8 @@ test_rejects_fifo_without_blocking() { setup_out rm "${TMP}/ws/out/review.md" mkfifo "${TMP}/ws/out/review.md" - timeout 10 /usr/bin/bash "${BIN_DIR}/collect-result" "${TMP}/ws/out" "${TMP}/dest" >log && grep -q "not a regular file" log && + entry_command "${BIN_DIR}/collect-result" && + timeout 10 "${ENTRY_CMD[@]}" "${TMP}/ws/out" "${TMP}/dest" >log && grep -q "not a regular file" log && assert "fifo not copied" test ! -e "${TMP}/dest/review.md" } diff --git a/agent-review/tests/test-instruction-coverage.sh b/agent-review/tests/test-instruction-coverage.sh index fb4671a..b74ee29 100755 --- a/agent-review/tests/test-instruction-coverage.sh +++ b/agent-review/tests/test-instruction-coverage.sh @@ -15,7 +15,7 @@ AR_DIR=$(cd "$(dirname "$0")/.." && pwd) setup() { # rule-files addendum [extra-patterns] mkdir -p root/config ws/in - cp -r "${AR_DIR}/bin" "${AR_DIR}/harnesses" "${AR_DIR}/prompt.md.tmpl" "${AR_DIR}/instruction-files.txt" root/ + cp -r "${AR_DIR}/bin" "${AR_DIR}/lib" "${AR_DIR}/harnesses" "${AR_DIR}/prompt.md.tmpl" "${AR_DIR}/instruction-files.txt" root/ bash root/harnesses/stub/install.sh root/harness/stub printf '%s\n' "$1" >root/config/rule-files.txt printf '%s\n' "${3:-}" >root/config/extra-instruction-files.txt @@ -27,46 +27,47 @@ setup() { # rule-files addendum [extra-patterns] test_addendum_naming_a_rule_file_passes() { setup $'AGENTS.md\nCODING_GUIDELINES.md' 'Also follow `CODING_GUIDELINES.md` and `src/pkg/AGENTS.md`.' # Passes the coverage check, then stops because no fetch phase ran. - ! bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && + ! run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && assert "got past the coverage check" grep -q "run the fetch phase first" log } test_addendum_naming_an_unreset_file_fails_closed() { setup 'AGENTS.md' 'Follow `docs/style.md` for naming.' - ! bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && + ! run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && assert "names the uncovered file" grep -q "names 'docs/style.md', which no reset pattern covers" log } test_addendum_naming_a_file_covered_by_extra_patterns_passes() { setup 'AGENTS.md' 'Follow `docs/style/naming.md`.' 'docs/style/' - ! bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && + ! run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && assert "got past the coverage check" grep -q "run the fetch phase first" log } test_addendum_naming_a_central_instruction_file_passes() { setup '' 'Read `.github/copilot-instructions.md` first.' - ! bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && + ! run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && assert "got past the coverage check" grep -q "run the fetch phase first" log } test_invalid_rule_file_is_rejected() { setup '../etc/passwd' '' - ! bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && + ! run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && assert "rejects the entry" grep -q "Invalid configured path or pattern" log } test_addendum_with_a_placeholder_fails_closed() { - # Substituted before the PR title and body: '{{PR_BODY}}' here would put - # untrusted text outside its delimiters. + # Never expanded (one substitution pass), but refused as defence in + # depth: expanded, '{{PR_BODY}}' here would put untrusted text outside + # its delimiters. setup 'AGENTS.md' 'Project notes. {{PR_BODY}}' - ! bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && + ! run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && assert "rejects the placeholder" grep -q "The prompt addendum contains '{{'" log } test_addendum_naming_a_pattern_is_rejected() { # Covered by the pattern, but not a file the post-condition can check. setup 'AGENTS.md' 'Follow `docs/*.md`.' 'docs/' - ! bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && + ! run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && assert "rejects the pattern" grep -qF "names 'docs/*.md', which is not a plain repository path" log } diff --git a/agent-review/tests/test-publish-comment.sh b/agent-review/tests/test-publish-comment.sh index 9ad45f2..13f4b8e 100755 --- a/agent-review/tests/test-publish-comment.sh +++ b/agent-review/tests/test-publish-comment.sh @@ -12,10 +12,10 @@ ZWSP=$'\xe2\x80\x8b' RUN_URL="https://github.com/example-org/example/actions/runs/1" SHA=0123456789abcdef0123456789abcdef01234567 -sanitize() { bash "${PC}" sanitize; } +sanitize() { run_entry "${PC}" sanitize; } lacks() { ! grep -qE -- "$1" <<<"$2"; } # pattern text render() { - bash "${PC}" render --harness stub --version stub-1 --model none --head-sha "${SHA}" \ + run_entry "${PC}" render --harness stub --version stub-1 --model none --head-sha "${SHA}" \ --run-url "${RUN_URL}" --review "$1" } @@ -116,13 +116,13 @@ test_render_marker_header_and_limit() { test_render_rejects_invalid_head_sha() { echo "review" >review.md - ! bash "${PC}" render --harness stub --version stub-1 --model none --head-sha 'main' \ + ! run_entry "${PC}" render --harness stub --version stub-1 --model none --head-sha 'main' \ --run-url "${RUN_URL}" --review review.md >/dev/null 2>&1 } test_render_rejects_markdown_in_labels() { echo "review" >review.md - ! bash "${PC}" render --harness stub --version '1 [x](https://evil)' --model none --head-sha "${SHA}" \ + ! run_entry "${PC}" render --harness stub --version '1 [x](https://evil)' --model none --head-sha "${SHA}" \ --run-url "${RUN_URL}" --review review.md >/dev/null 2>&1 } @@ -152,7 +152,7 @@ post() { echo "" >body.md echo "text" >>body.md FAKE_DIR="${TMP}" PATH="${TMP}/bin:${PATH}" \ - bash "${PC}" post --repo example-org/example --pr 9 --harness stub --body-file body.md >/dev/null + run_entry "${PC}" post --repo example-org/example --pr 9 --harness stub --body-file body.md >/dev/null } test_post_updates_own_marked_comment() { @@ -186,7 +186,7 @@ test_post_refuses_body_without_marker() { install_fake_gh "" echo "no marker" >body.md ! FAKE_DIR="${TMP}" PATH="${TMP}/bin:${PATH}" \ - bash "${PC}" post --repo example-org/example --pr 9 --harness stub --body-file body.md >/dev/null 2>&1 + run_entry "${PC}" post --repo example-org/example --pr 9 --harness stub --body-file body.md >/dev/null 2>&1 } for t in $(declare -F | awk '$3 ~ /^test_/ {print $3}'); do run_test "$t"; done diff --git a/agent-review/tests/test-run-review.sh b/agent-review/tests/test-run-review.sh index b99bd20..567012d 100755 --- a/agent-review/tests/test-run-review.sh +++ b/agent-review/tests/test-run-review.sh @@ -18,7 +18,7 @@ setup() { # [padding-kib [head-sha base-sha]] local head=${2:-${HEAD_SHA}} base=${3:-${BASE_SHA}} # The trusted root, as the review job lays it out under /opt/agent-review. mkdir -p root ws/in - cp -r "${AR_DIR}/bin" "${AR_DIR}/harnesses" "${AR_DIR}/prompt.md.tmpl" "${AR_DIR}/instruction-files.txt" root/ + cp -r "${AR_DIR}/bin" "${AR_DIR}/lib" "${AR_DIR}/harnesses" "${AR_DIR}/prompt.md.tmpl" "${AR_DIR}/instruction-files.txt" root/ bash root/harnesses/stub/install.sh root/harness/stub # Caller configuration, as the review job writes it. mkdir -p root/config @@ -35,7 +35,7 @@ setup() { # [padding-kib [head-sha base-sha]] test_reviews_pr_and_resets_instruction_files() { setup 0 - bash root/bin/run-review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } + run_entry root/bin/run-review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } local repo="${TMP}/ws/repo" ctx="${TMP}/ws/repo/.agent-review-context" assert "review written" test -s ws/out/review.md && assert "meta ok" test "$(jq -r .status ws/out/meta.json)" = ok && @@ -55,7 +55,7 @@ test_reviews_pr_and_resets_instruction_files() { test_truncates_oversized_review() { setup 100 - bash root/bin/run-review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } + run_entry root/bin/run-review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } assert "truncated flag" test "$(jq -r .truncated ws/out/meta.json)" = true && assert "under 60000 bytes" test "$(stat -c %s ws/out/review.md)" -le 60000 } @@ -64,8 +64,8 @@ test_truncates_oversized_review_in_two_phases() { # The workflow runs the phases in separate sandbox runs (separate processes), # so everything the review phase uses must be defined outside the fetch phase. setup 100 - bash root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 || { cat log; return 1; } - bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } + run_entry root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 || { cat log; return 1; } + run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } assert "truncated flag" test "$(jq -r .truncated ws/out/meta.json)" = true && assert "under 60000 bytes" test "$(stat -c %s ws/out/review.md)" -le 60000 && assert "truncation note" grep -q 'Review truncated' ws/out/review.md @@ -77,7 +77,7 @@ test_removes_instruction_files_added_by_the_pr() { local head=64c83aa07ab0e2c00b385faccb8b4ca57945829a base=b84a46734f164516a4c28c486e4e4b71dd2eb2d8 local repo="${TMP}/ws/repo" ctx="${TMP}/ws/repo/.agent-review-context/pr-instruction-files" p setup 0 "${head}" "${base}" - bash root/bin/run-review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } + run_entry root/bin/run-review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } for p in .claude/settings.json .github/copilot-instructions.md .opencode/opencode.jsonc \ AGENTS.md CLAUDE.md src/gt4py/next/AGENTS.md src/gt4py/next/CLAUDE.md; do assert "${p} removed" test ! -e "${repo}/${p}" && @@ -101,13 +101,15 @@ setup_followed() { # extra-pattern printf 'Also follow `src/gt4py/next/AGENTS.md`.\n' >root/config/prompt-addendum.md } -test_post_condition_catches_a_pattern_that_misses_the_file() { - # Bash matching says 'gt4py/*.md' covers src/gt4py/next/AGENTS.md ('*' - # crosses '/'), git's ':(glob)' does not, so the reset keeps the PR's - # file: the post-condition must stop the run before the prompt exists. +test_coverage_check_refuses_a_pattern_that_misses_the_file() { + # 'gt4py/*.md' does not cover src/gt4py/next/AGENTS.md: in git's + # ':(glob)' pathspecs '*' does not cross '/'. The coverage check asks + # git, like the reset, so the run fails closed before the fetch. The + # post-condition behind it is tested with the reset subverted in + # tests/python/test_run_review.py. setup_followed 'gt4py/*.md' - ! bash root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 && - assert "names the file" grep -q "Followed file 'src/gt4py/next/AGENTS.md' is not in the base commit but is in the checkout" log && + ! run_entry root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 && + assert "names the file" grep -q "names 'src/gt4py/next/AGENTS.md', which no reset pattern covers" log && assert "no prompt" test ! -e ws/prompt.md } @@ -115,7 +117,7 @@ test_post_condition_passes_when_the_pattern_matches() { # Positive control: 'next/*.md' matches at that depth, so the PR's file is # removed (the base has none). setup_followed 'next/*.md' - bash root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 || { cat log; return 1; } + run_entry root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 || { cat log; return 1; } assert "file removed" test ! -e ws/repo/src/gt4py/next/AGENTS.md && assert "PR version kept as data" test -s ws/repo/.agent-review-context/pr-instruction-files/src/gt4py/next/AGENTS.md.txt && assert "checked" grep -q "1 rule file(s) and 1 file(s) named by the addendum are their base versions" log @@ -126,7 +128,7 @@ test_rule_file_added_only_by_the_pr() { setup 0 "${REAL_HEAD}" "${REAL_BASE}" printf 'src/gt4py/next/AGENTS.md\n' >root/config/rule-files.txt : >root/config/prompt-addendum.md - bash root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 || { cat log; return 1; } + run_entry root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 || { cat log; return 1; } assert "file removed" test ! -e ws/repo/src/gt4py/next/AGENTS.md && assert "checked" grep -q "1 rule file(s) and 0 file(s) named by the addendum are their base versions" log } @@ -136,7 +138,7 @@ test_review_phase_runs_offline_after_fetch() { # read must be in the checkout already. 'protocol.allow=never' (and # GIT_ALLOW_PROTOCOL for the driver) makes any lazy fetch fail. setup 0 - bash root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 || { cat log; return 1; } + run_entry root/bin/run-review --phase fetch "${TMP}/ws" >log 2>&1 || { cat log; return 1; } local repo="${TMP}/ws/repo" offline=(git -c protocol.allow=never -C "${TMP}/ws/repo") assert "no review after fetch" test ! -e ws/out/review.md && assert "prompt rendered" test -s ws/prompt.md && @@ -145,7 +147,7 @@ test_review_phase_runs_offline_after_fetch() { assert "show base file offline" "${offline[@]}" show "${BASE_SHA}:AGENTS.md" >/dev/null && assert "grep offline" "${offline[@]}" grep -q -e import -- '*.py' && assert "blame offline" "${offline[@]}" blame -- AGENTS.md >/dev/null && - GIT_ALLOW_PROTOCOL=none bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 || + GIT_ALLOW_PROTOCOL=none run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } assert "review written offline" test -s ws/out/review.md && assert "meta ok" test "$(jq -r .status ws/out/meta.json)" = ok @@ -155,7 +157,7 @@ test_drops_text_before_the_first_heading() { setup 0 # A stub variant that opens its answer with a note, as models do. sed -i 's/^{$/{ echo "Writing the final review now."; echo;/' root/harnesses/stub/run.sh - bash root/bin/run-review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } + run_entry root/bin/run-review "${TMP}/ws" >log 2>&1 || { cat log; return 1; } assert "starts with the summary" test "$(head -n 1 ws/out/review.md)" = "### Summary" && assert "note dropped" test "$(grep -c 'Writing the final review' ws/out/review.md)" -eq 0 && assert "no leftover" test ! -e ws/out/review.body @@ -163,7 +165,7 @@ test_drops_text_before_the_first_heading() { test_review_phase_needs_the_fetch_phase() { setup 0 - ! bash root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && + ! run_entry root/bin/run-review --phase review "${TMP}/ws" >log 2>&1 && assert "explains why" grep -q "run the fetch phase first" log } diff --git a/agent-review/tests/test-workflow-structure.py b/agent-review/tests/test-workflow-structure.py index 2691afb..970091c 100644 --- a/agent-review/tests/test-workflow-structure.py +++ b/agent-review/tests/test-workflow-structure.py @@ -1,33 +1,36 @@ """Structural checks of the agent review workflow (security review, M3/S7). +The checks and what they enforce are described in workflow_structure.py. Reads the workflow files with YAML aliases resolved (PyYAML), the way GitHub -does, and checks properties that must survive every edit: - -- only the keyed 'review' job declares an environment; -- a job without 'environment:' references no secret, except the one boolean - check in 'authorize' that the key is not a shared secret; -- only 'publish' has a write permission; -- no expression ('${{') inside any 'run:' script, in any workflow file; -- 'review-keyless' runs the same steps as 'review' except the listed ones; -- the keyed job's event backstop, concurrency group and per-call artifact - names. +does, and the tracked files under agent-review/ (git ls-files). Offline. Run: python3 agent-review/tests/test-workflow-structure.py """ -import pathlib import sys -import yaml - -ROOT = pathlib.Path(__file__).resolve().parents[2] -WORKFLOWS = ROOT / ".github" / "workflows" -REVIEW_WORKFLOW = WORKFLOWS / "agent-review.yml" - -# The only 'secrets.' reference allowed in a job without an environment. -SHARED_KEY_CHECK = ("authorize", "Authorize", "HAS_SHARED_KEY", "${{ secrets.inference_api_key != '' }}") -# Steps of 'review-keyless' that differ from those of 'review'. -KEYLESS_DIFFERENT = {"Check the inference key": "Check the harness wire"} +from workflow_structure import ( + KEYLESS_DIFFERENT, + REVIEW_WORKFLOW, + SHARED_KEY_CHECK, + WORKFLOWS, + ast_problems, + call_site_problems, + collect_gate_problems, + entry_problems, + host_path_problems, + load, + post_sandbox_problems, + python_word_problems, + repository, + sandbox_output_problems, + secret_refs, + shebang_problems, + shell_python_problems, + strings, + token_reach_problems, + tree_problems, +) failures: list[str] = [] @@ -38,24 +41,13 @@ def check(condition: bool, message: str) -> None: failures.append(message) -def strings(node, path=()): - """Yields (path, string) for every string value in a YAML tree.""" - if isinstance(node, dict): - for key, value in node.items(): - yield from strings(value, path + (str(key),)) - elif isinstance(node, list): - for index, value in enumerate(node): - yield from strings(value, path + (str(index),)) - elif isinstance(node, str): - yield path, node - +def check_problems(problems: list[str], message: str) -> None: + check(not problems, message) + for problem in problems: + print(f" {problem}") -def load(path: pathlib.Path) -> dict: - with path.open() as f: - return yaml.safe_load(f) - -def check_runs_have_no_expressions(path: pathlib.Path) -> None: +def check_runs_have_no_expressions(path) -> None: workflow = load(path) offenders = [ f"{job_id}/{step.get('name', index)}" @@ -82,7 +74,7 @@ def main() -> int: continue refs = [] for path, value in strings(job): - if "secrets." not in value: + if not secret_refs(value): continue step_name = job["steps"][int(path[1])].get("name") if path[0] == "steps" else None if (job_id, step_name, path[-1], value) == SHARED_KEY_CHECK: @@ -168,6 +160,28 @@ def main() -> int: for path in sorted(WORKFLOWS.glob("*.yml")): check_runs_have_no_expressions(path) + repo = repository() + kinds = repo["kinds"] + print("agent-review/ (Python runtime rules, docs/adr/0004-python-runtime.md)") + print(" entry points: " + ", ".join(f"{name} ({kind})" for name, kind in sorted(kinds.items()))) + check_problems(call_site_problems(workflow, kinds), "call sites: roots per job and step, call form per file") + check_problems(python_word_problems(workflow, kinds), "agent-review.yml: no other Python, no pip, no setup-python") + check_problems(shell_python_problems(repo["shell"], kinds), "shell files: Python only in the exact call form") + check_problems(host_path_problems(workflow), "host calls of entry points: 'PATH: /usr/bin:/bin' on the step") + check_problems( + post_sandbox_problems(workflow), "after the sandbox: no token, fixed shell and PATH, the result path" + ) + check_problems( + sandbox_output_problems(workflow, repo["shell"]), + "sandbox output: prefixed, no carriage return, no legacy '##[' (awf steps and diag)", + ) + check_problems(collect_gate_problems(workflow), "'Collect the result' runs only after a successful teardown") + check_problems(entry_problems(repo["entries"], repo["lib"]), "bin/: only the exact Python entry-point template") + check_problems(tree_problems(repo["index"]), "tree: no symlink, .pth, .pyc, __pycache__, *customize.py") + check_problems(shebang_problems(repo["first_lines"]), "no Python shebang outside lib/agent_review/ and tests/") + check_problems(ast_problems(repo["python"]), "Python: allowlisted imports, no dynamic code, no shell") + check_problems(token_reach_problems(repo["python"]), "token reach: agent_review.gh only from authorize, publish") + print(f"{len(failures)} failed.") return 1 if failures else 0 diff --git a/agent-review/tests/workflow_structure.py b/agent-review/tests/workflow_structure.py new file mode 100644 index 0000000..2e06c16 --- /dev/null +++ b/agent-review/tests/workflow_structure.py @@ -0,0 +1,971 @@ +"""Structural checks of the agent review workflow and its Python code. + +The one complete list of what the structure test enforces; the docs state +each invariant and point here. Run through test-workflow-structure.py (the +CLI). The checks are functions returning a list of problems, so +tests/python/test_workflow_structure.py can feed them crafted inputs as +well as the real files; the checks marked (CLI) live in the script and run +against the real workflow only. + +Workflow (agent-review.yml, read with YAML aliases resolved, as GitHub +does): + +- jobs and secrets (CLI): only the keyed 'review' job declares an + environment; a job without one references no secret ('secret_refs'), + except the boolean check in 'authorize' that the key is not a shared + secret; only 'publish' has a write permission; no expression ('${{') + inside any 'run:' script, in any workflow file; 'review-keyless' runs + the same steps as 'review' except the listed ones; the keyed job's event + backstop and concurrency group; artifact names carry the call id; only + 'authorize' reads the 'api_base' input (invariants 1 and 12); +- host PATH: every step that calls an entry point on the host sets + 'PATH: /usr/bin:/bin' (host_path_problems); +- after the sandbox (invariant 3, post_sandbox_problems): the steps after + the agent's run, and what they inherit, hold no token or secret + reference; no step of the review jobs sets a variable that runs code + before a step's script; every 'run:' step uses the fixed shell and + PATH; only 'actions/upload-artifact'; the result upload's exact path; +- sandbox output (invariant 11, sandbox_output_problems): every awf call + sends stdout and stderr through the exact filter and nothing else in + its step can print; 'diag' is defined once, as one filtered pipeline; +- the collect gate (collect_gate_problems): 'Collect the result' runs only + if 'Stop the sandbox' succeeded, because collect-result's single-link + check relies on no sandbox process being alive. + +Python (invariant 13, docs/adr/0004-python-runtime.md): + +- call sites (call_site_problems, python_word_problems, + shell_python_problems): every reference to '/bin/' uses the + root allowed for its job and step, names an entry point, and is exactly + '/usr/bin/python3 -I -S -B /bin/' at the start of a command, + with the file named inline; no other Python, 'pip' or 'setup-python' in + agent-review.yml; shell files under bin/ and harnesses/ call Python only + in that form, with the root from 'ar_root_line'; +- entry points (entry_problems): each file in bin/ is exactly the template, + mode 100644 (not executable), with a module that defines main(); +- the tree (tree_problems, shebang_problems): no symlink or submodule, no + '.pth', '.pyc' or '__pycache__', no '*customize.py'; lib/ holds only + agent_review/, and that only '.py' files; no '.py' file or Python + shebang outside lib/agent_review/ and tests/; +- imports and calls (ast_problems): only STDLIB_ALLOWED and agent_review.*; + none of BANNED_CALLS or BANNED_OS; subprocess only in runner.py; no + 'shell=' argument; no aliased or star import; no getattr, setattr or + delattr on a module or an attribute of one (except GETATTR_ALLOWED), nor + those three used as values; no module used as a value and no + sys.modules (except the probe); no standard-library module imported + through agent_review.*; each trust zone named only by ZONE_ALLOWED; +- token reach (token_reach_problems): only the 'authorize' and + 'publish-comment' entry points can import agent_review.gh, and only + gh.py names the 'gh' program. The token itself is in a step's env, + which the workflow decides; this keeps the code that runs there narrow. +""" + +import ast +import pathlib +import re +import subprocess +from collections.abc import Iterator, Mapping +from typing import Any + +import yaml + +ROOT = pathlib.Path(__file__).resolve().parents[2] +AR_DIR = ROOT / "agent-review" +WORKFLOWS = ROOT / ".github" / "workflows" +REVIEW_WORKFLOW = WORKFLOWS / "agent-review.yml" + +# The only 'secrets.' reference allowed in a job without an environment. +SHARED_KEY_CHECK = ("authorize", "Authorize", "HAS_SHARED_KEY", "${{ secrets.inference_api_key != '' }}") +# Steps of 'review-keyless' that differ from those of 'review'. +KEYLESS_DIFFERENT = {"Check the inference key": "Check the harness wire"} + +# --- Entry points ---------------------------------------------------------- + +PYTHON_CALL = "/usr/bin/python3 -I -S -B" +ENTRY_NAME = re.compile(r"[a-z][a-z0-9-]{0,31}", re.ASCII) +# Every Python entry point is exactly this text, apart from the module name. +# Keep it in sync with tests/lib.sh (the first line is the marker). +ENTRY_TEMPLATE = """\ +# agent-review Python entry point: run only as '/usr/bin/python3 -I -S -B /bin/'. +# The fixed template of agent-review/tests/workflow_structure.py; the code is in lib/agent_review/. +import sys + +if not (sys.flags.isolated and sys.flags.no_site and sys.flags.dont_write_bytecode and sys.flags.safe_path): + sys.stderr.write("agent-review entry points run only as '/usr/bin/python3 -I -S -B /bin/'.\\n") + sys.exit(2) + +import os # noqa: E402 + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "lib")) + +from agent_review.{module} import main # noqa: E402 + +sys.exit(main()) +""" +PYTHON_MARKER = ENTRY_TEMPLATE.split("\n", 1)[0] + + +def module_of(name: str) -> str: + return name.replace("-", "_") + + +def render_entry(name: str) -> str: + return ENTRY_TEMPLATE.replace("{module}", module_of(name)) + + +def entry_kind(name: str, text: str) -> str | None: + """'python' for exactly the template, else None: anything else in bin/ fails closed.""" + first = text.split("\n", 1)[0] + if first == PYTHON_MARKER and text == render_entry(name): + return "python" + return None + + +def entry_problems(entries: Mapping[str, tuple[str, str]], lib_sources: Mapping[str, str]) -> list[str]: + """``entries``: bin/ name -> (text, git mode); ``lib_sources``: path -> text.""" + problems = [] + for name, (text, mode) in sorted(entries.items()): + kind = entry_kind(name, text) + if not ENTRY_NAME.fullmatch(name): + problems.append(f"bin/{name}: invalid entry point name") + if kind is None: + problems.append(f"bin/{name}: not the exact Python entry-point template") + if kind != "python": + continue + if mode != "100644": + problems.append(f"bin/{name}: a Python entry point must have mode 100644, not {mode}") + source = lib_sources.get(f"lib/agent_review/{module_of(name)}.py") + if source is None: + problems.append(f"bin/{name}: no lib/agent_review/{module_of(name)}.py") + elif not any(isinstance(node, ast.FunctionDef) and node.name == "main" for node in ast.parse(source).body): + problems.append(f"bin/{name}: lib/agent_review/{module_of(name)}.py defines no main()") + return problems + + +# --- Call sites -------------------------------------------------------------- + +TRUSTED_ROOT = "${RUNNER_TEMP}/trusted" +OPT_ROOT = "/opt/agent-review" +ROOT_REF = re.compile(r"(\$\{RUNNER_TEMP\}/trusted|/opt/agent-review)/bin/([A-Za-z0-9_.-]+)", re.ASCII) +# The review jobs switch from the fetched files to the root-owned copy here. +OPT_FROM_STEP = "Prepare the sandbox inputs" +TRUSTED_JOBS = ("authorize", "prepare", "publish") +REVIEW_JOBS = ("review", "review-keyless") +# What may precede a reference: the text before it on its line. +EXISTENCE_CHECK = '[ -f "' +PYTHON_FORMS = {TRUSTED_ROOT: f'{PYTHON_CALL} "', OPT_ROOT: f"{PYTHON_CALL} "} +# What must follow a Python reference: the closing quote, or a separator. +PYTHON_AFTER = {TRUSTED_ROOT: re.compile(r'"(?: |$)'), OPT_ROOT: re.compile(r"(?: |$)")} + + +def python_call(root: str, name: str) -> str: + """The exact Python call of an entry point, as written in agent-review.yml.""" + quote = '"' if root == TRUSTED_ROOT else "" + return f"{PYTHON_FORMS[root]}{root}/bin/{name}{quote}" + + +def run_scripts(workflow: Mapping[str, Any]) -> Iterator[tuple[str, int, str, str]]: + """Yields (job, step index, step name, run script).""" + for job_id, job in workflow["jobs"].items(): + for index, step in enumerate(job.get("steps", [])): + if "run" in step: + yield job_id, index, step.get("name", str(index)), step["run"] + + +def allowed_root(workflow: Mapping[str, Any], job_id: str, index: int) -> str | None: + if job_id in TRUSTED_JOBS: + return TRUSTED_ROOT + if job_id in REVIEW_JOBS: + names = [s.get("name") for s in workflow["jobs"][job_id]["steps"]] + if OPT_FROM_STEP not in names: + return None + return OPT_ROOT if index >= names.index(OPT_FROM_STEP) else TRUSTED_ROOT + return None + + +def call_site_problems(workflow: Mapping[str, Any], kinds: Mapping[str, str | None]) -> list[str]: + """Roots and call forms of every '/bin/' in a 'run:' script.""" + problems = [] + for job_id, index, step_name, script in run_scripts(workflow): + where = f"{job_id}/{step_name}" + for line in script.split("\n"): + for m in ROOT_REF.finditer(line): + root, name = m.group(1), m.group(2) + before, after = line[: m.start()], line[m.end() :] + want_root = allowed_root(workflow, job_id, index) + if want_root is None: + problems.append(f"{where}: no allowed root for job '{job_id}'") + elif root != want_root: + problems.append(f"{where}: '{root}/bin/{name}', but this step may use only '{want_root}'") + kind = kinds.get(name) + if kind is None: + problems.append(f"{where}: bin/{name} is not a known entry point") + continue + if before.endswith(EXISTENCE_CHECK) and after.startswith('" ]'): + continue + start = len(before) - len(PYTHON_FORMS[root]) + bounded = start == 0 or (start > 0 and CALL_BOUNDARY.fullmatch(before[start - 1]) is not None) + if not before.endswith(PYTHON_FORMS[root]) or not bounded or PYTHON_AFTER[root].match(after) is None: + problems.append(f"{where}: bin/{name} is Python; call it exactly as {python_call(root, name)}") + return problems + + +def strings(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[str, ...], str]]: + """Yields (path, string) for every string value in a YAML tree.""" + if isinstance(node, dict): + for key, value in node.items(): + yield from strings(value, (*path, str(key))) + elif isinstance(node, list): + for index, value in enumerate(node): + yield from strings(value, (*path, str(index))) + elif isinstance(node, str): + yield path, node + + +PYTHON_WORD = re.compile(r"python", re.IGNORECASE) +# What may precede '/usr/bin/python3': a command boundary, never part of a +# word or path ('"${HOME}"/usr/bin/python3'). +CALL_BOUNDARY = re.compile(r"[\s(;|&]") +_BOUNDARY = r"(? list[str]: + """No Python in agent-review.yml except the exact call form of a Python entry point.""" + problems = [] + for path, value in strings(workflow): + where = "/".join(path) + allowed = { + m.start() + len("/usr/bin/") for m in YAML_PYTHON_CALL.finditer(value) if kinds.get(m.group(1)) == "python" + } + for m in PYTHON_WORD.finditer(value): + if m.start() not in allowed: + problems.append(f"{where}: 'python' outside the call form of a Python entry point") + for m in PIP_WORD.finditer(value): + problems.append(f"{where}: '{m.group(0)}'") + return problems + + +# In shell files the root is the variable 'ar_root', set from the file's own +# path by exactly ar_root_line() (the agent-review/ directory). +SHELL_ROOT_VAR = "ar_root" +SHELL_PYTHON_CALL = re.compile( + _BOUNDARY + re.escape(PYTHON_CALL) + r' "\$\{' + SHELL_ROOT_VAR + r'\}/bin/([a-z][a-z0-9-]*)"', re.ASCII +) + + +def ar_root_line(rel: str) -> str: + """The line that sets the root in the shell file ``rel`` (relative to agent-review/).""" + ups = "/".join([".."] * (len(rel.split("/")) - 1)) + return f'{SHELL_ROOT_VAR}=$(cd "$(dirname "${{BASH_SOURCE[0]}}")/{ups}" && pwd)' + + +def shell_python_problems(sources: Mapping[str, str], kinds: Mapping[str, str | None]) -> list[str]: + """In shell files: Python only as '/usr/bin/python3 -I -S -B "${ar_root}/bin/"'. + + Comment lines are skipped, but not the shebang. A file that calls Python + must set 'ar_root' with exactly ar_root_line(), and nothing else. + """ + problems = [] + for rel, text in sorted(sources.items()): + calls = False + for number, line in enumerate(text.split("\n"), 1): + if line.lstrip().startswith("#") and not (number == 1 and line.startswith("#!")): + continue + allowed = { + m.start() + len("/usr/bin/") + for m in SHELL_PYTHON_CALL.finditer(line) + if kinds.get(m.group(1)) == "python" + } + calls = calls or bool(allowed) + if any(m.start() not in allowed for m in PYTHON_WORD.finditer(line)): + problems.append( + f"{rel}:{number}: Python only as '{PYTHON_CALL} \"${{{SHELL_ROOT_VAR}}}/bin/\"'" + ) + if re.match(rf"\s*(?:export\s+|local\s+|readonly\s+|declare\s+\S+\s+)?{SHELL_ROOT_VAR}\b", line) and ( + line.strip() != ar_root_line(rel) + ): + problems.append(f"{rel}:{number}: set '{SHELL_ROOT_VAR}' only as '{ar_root_line(rel)}'") + if calls and ar_root_line(rel) not in [line.strip() for line in text.split("\n")]: + problems.append(f"{rel}: calls Python but does not set '{SHELL_ROOT_VAR}' as '{ar_root_line(rel)}'") + return problems + + +# --- PATH on the host ------------------------------------------------------------------ + +FIXED_PATH = "/usr/bin:/bin" +# The trusted-host steps, where 'gh' is looked up on PATH: they must exist. +FIXED_PATH_STEPS = (("authorize", "Authorize"), ("publish", "Render the review"), ("publish", "Publish the review")) + + +def host_path_problems(workflow: Mapping[str, Any]) -> list[str]: + """Every step that calls an entry point on the host sets 'PATH: /usr/bin:/bin' (ADR 0004). + + The runner's default PATH searches home directories first; on the + trusted host 'gh' is found on PATH. Calls inside AWF (the step runs + '"${AWF_BIN}"') are exempt: there PATH is the sandbox's own. + """ + problems = [] + seen = set() + for job_id, job in workflow["jobs"].items(): + for step in job.get("steps", []): + script = step.get("run", "") + if PYTHON_CALL not in script or '"${AWF_BIN}"' in script: + continue + name = step.get("name", "") + seen.add((job_id, name)) + path = (step.get("env") or {}).get("PATH") + if path != FIXED_PATH: + problems.append( + f"{job_id}/{name}: calls an entry point on the host with PATH {path!r}, not {FIXED_PATH!r}" + ) + problems += [ + f"{job}/{name}: no host call of an entry point" for job, name in FIXED_PATH_STEPS if (job, name) not in seen + ] + return problems + + +# --- After the sandbox (invariant 3) ------------------------------------------------------- + +TAINTED_SHELL = "/usr/bin/bash --noprofile --norc -e -o pipefail {0}" +RESULT_PATH = "${{ runner.temp }}/result" +RESULT_ARTIFACT = "agent-review-result-" +# A token or secret reference by name ('GH_TOKEN', 'github.token', "github['token']", +# 'secrets.X', "secrets['X']"). 'context_refs' also catches the forms that read +# a whole context. +TOKEN_REF = re.compile(r"GH_TOKEN|GITHUB_TOKEN|github\s*(?:\.\s*token|\[\s*['\"]token)|secrets\s*[.\[]", re.IGNORECASE) +# A use of the 'github' or 'secrets' context, with the property it reads if +# it names one ('github.event', "github['event']"). Not a property ('x.github') +# or a string literal ("'github'"). +CONTEXT_REF = re.compile( + r"(? list[str]: + """The uses of a context in ``value`` that can read a secret or the token. + + An allowlist: every use of 'secrets', and every use of 'github' except + a named property other than 'token'. 'toJSON(github)', 'github' and + 'github.*' hold the token too. Context and property names ignore case, + as in GitHub's expressions. Fails closed on prose that names a context. + """ + refs = [] + for match in CONTEXT_REF.finditer(value): + name = match.group(2) or match.group(3) + if match.group(1).lower() == "secrets" or name is None or name.lower() == "token": + refs.append(match.group(0)) + return refs + + +def secret_refs(value: str) -> list[str]: + """The uses of the 'secrets' context in ``value``.""" + return [ref for ref in context_refs(value) if ref[:7].lower() == "secrets"] + + +# Files whose lines become the environment or PATH of every later step. +STEP_STATE_FILES = ("GITHUB_ENV", "GITHUB_PATH") +# Variables that run code before a step's script: bash reads BASH_ENV +# (and ENV in POSIX mode) despite '--noprofile --norc', SHELLOPTS and +# BASHOPTS set options, BASH_FUNC_* define functions, LD_* load libraries, +# NODE_OPTIONS ('--require') loads a module into a JavaScript action. +STARTUP_VARIABLE = re.compile( + r"\b(?:BASH_ENV|ENV|SHELLOPTS|BASHOPTS|LD_PRELOAD|LD_LIBRARY_PATH|LD_AUDIT|NODE_OPTIONS)\b|\bBASH_FUNC_" +) + + +def _startup_problems(where: str, node: Any) -> list[str]: + """No 'env:' key in ``node`` is a startup variable, and its shell names none. + + ``node`` is the workflow, a job or a step; its shell is 'shell:' or + 'defaults: run: shell:' ('env BASH_ENV=… bash {0}'). + """ + problems = [ + f"{where}: sets {key!r}, which runs code before the step's script" + for key in (node.get("env") or {}) + if STARTUP_VARIABLE.match(str(key)) + ] + shells = [node.get("shell"), ((node.get("defaults") or {}).get("run") or {}).get("shell")] + problems += [ + f"{where}: shell {shell!r} names {match.group(0)!r}, which runs code before the step's script" + for shell in shells + if isinstance(shell, str) + for match in STARTUP_VARIABLE.finditer(shell) + ] + return problems + + +def _token_problems(where: str, node: Any, path: tuple[str, ...] = ()) -> list[str]: + found = [ + (key_path, match.group(0)) + for key_path, value in [*strings(node, path), *_keys(node, path)] + for match in TOKEN_REF.finditer(value) + ] + found += [(key_path, ref) for key_path, value in strings(node, path) for ref in context_refs(value)] + return [f"{where}: token reference {ref!r} in {'/'.join(key_path)}" for key_path, ref in dict.fromkeys(found)] + + +def _keys(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[str, ...], str]]: + """Yields (path, key) for every mapping key in a YAML tree ('env: {GH_TOKEN: ...}').""" + if isinstance(node, dict): + for key, value in node.items(): + yield (*path, str(key)), str(key) + yield from _keys(value, (*path, str(key))) + elif isinstance(node, list): + for index, value in enumerate(node): + yield from _keys(value, (*path, str(index))) + + +def post_sandbox_problems(workflow: Mapping[str, Any]) -> list[str]: + """The steps after the agent's run ('id: agent') in both review jobs treat the host as tainted. + + No step of those jobs, nor their job or the workflow, sets a variable + that runs code before a step's script ('BASH_ENV', ...; in 'env:' or + through $GITHUB_ENV). No token or secret reference ('TOKEN_REF', + 'context_refs'), in those steps or in what they inherit: + the workflow's and the job's 'env:' and 'defaults:', and the + $GITHUB_ENV and $GITHUB_PATH files, which no step of the job that holds + a token may name; every 'run:' step uses the fixed shell and + 'PATH: /usr/bin:/bin'; only 'actions/upload-artifact' as an action; the + result upload's 'path' is exactly '${{ runner.temp }}/result'. + """ + problems = _startup_problems("workflow", workflow) + for key in ("env", "defaults"): + problems += _token_problems("workflow", workflow.get(key) or {}, (key,)) + for job_id in REVIEW_JOBS: + job = workflow["jobs"][job_id] + problems += _startup_problems(job_id, job) + for key in ("env", "defaults"): + problems += _token_problems(job_id, job.get(key) or {}, (key,)) + steps = job["steps"] + for step in steps: + where = f"{job_id}/{step.get('name', '?')}" + problems += _startup_problems(where, step) + text = "\n".join(value for _, value in strings(step)) + if any(name in text for name in STEP_STATE_FILES): + if _token_problems("", step): + problems.append(f"{where}: holds a token and writes $GITHUB_ENV or $GITHUB_PATH") + if STARTUP_VARIABLE.search(text): + problems.append(f"{where}: writes $GITHUB_ENV or $GITHUB_PATH and names a startup variable") + ids = [step.get("id") for step in steps] + if "agent" not in ids: + problems.append(f"{job_id}: no step with 'id: agent'") + continue + uploads = 0 + for step in steps[ids.index("agent") + 1 :]: + where = f"{job_id}/{step.get('name', '?')}" + problems += _token_problems(where, step) + if "run" in step: + if step.get("shell") != TAINTED_SHELL: + problems.append(f"{where}: shell is not '{TAINTED_SHELL}'") + if (step.get("env") or {}).get("PATH") != FIXED_PATH: + problems.append(f"{where}: env PATH is not '{FIXED_PATH}'") + uses = step.get("uses") + if uses is not None: + if not uses.startswith("actions/upload-artifact@"): + problems.append(f"{where}: action '{uses}' after the sandbox") + elif str((step.get("with") or {}).get("name", "")).startswith(RESULT_ARTIFACT): + uploads += 1 + if step["with"].get("path") != RESULT_PATH: + problems.append(f"{where}: the result upload's path is not '{RESULT_PATH}'") + if uploads != 1: + problems.append(f"{job_id}: {uploads} result upload(s) after the sandbox, not 1") + return problems + + +# --- Sandbox output ------------------------------------------------------------------ + +# Every line of AWF's output goes through exactly this filter: carriage +# returns and NUL bytes dropped, '##[' (the runner's legacy command syntax, matched +# anywhere in a line) broken up with a zero-width space, a prefix so no line +# starts with '::' (invariant 11). +AWF_OUTPUT_FILTER = "| /usr/bin/sed -u -e 's/\\r//g' -e 's/\\x00//g' -e 's/##\\[/#\\xe2\\x80\\x8b#[/g' -e 's/^/awf| /'" +DIAG_FILTER = "sed -e 's/\\x00//g' -e 's/##\\[/#\\xe2\\x80\\x8b#[/g' -e \"s/^/${ADAPTER_NAME:-harness}| /\" >&2" + + +AWF_CALL = '"${AWF_BIN}"' +AWF_COMMAND_END = " 2>&1 \\" +# 'AWF_BIN' in any spelling, or 'awf' as a word (not '/awf', 'awf-…', 'awf.json'). +AWF_WORD = re.compile(r"AWF_BIN|(?> "$GITHUB_ENV"' +# The only lines allowed after an awf call's filter: they report its status. +AFTER_AWF = frozenset( + {"rc=${PIPESTATUS[0]}", 'echo "exit_code=${rc}" >> "$GITHUB_OUTPUT"', 'exit "${rc}"', 'exit "${PIPESTATUS[0]}"'} +) +# The only lines allowed before an awf call in its step: the agent step's +# choice of key variable. Nothing before the call may print pull request text. +BEFORE_AWF = frozenset( + { + 'if [ "$(head -n 1 "/opt/agent-review/harnesses/${HARNESS}/wire")" = openai-chat ]; then', + 'export OPENAI_API_KEY="${KEY}"', + "fi", + "unset KEY", + "set +e", + } +) +# Shell syntax that would let a part of the call write around the filter. +AWF_CALL_SYNTAX = re.compile(r"[<>;&|`]|\$\(") +COMMON_SH = "harnesses/common.sh" +DIAG_DEFINITION = re.compile(r"^\s*(?:function\s+diag\b|diag\s*\(\s*\))", re.MULTILINE) + + +def _awf_call_problems(where: str, script: str) -> list[str]: + """awf is named only as '"${AWF_BIN}"' (or where it is found); each call is filtered and ends the step. + + Before the first call come only comments and the lines in BEFORE_AWF. + Each call continues to a '-- … 2>&1 \\' line followed by exactly the + filter line, with no redirection, pipe, list or command substitution + of its own; after it come only comments and the lines in AFTER_AWF. + """ + problems = [] + lines = script.split("\n") + calls = [] + for number, line in enumerate(lines): + code = line.strip() + if code.startswith("#") or code == AWF_SETTER: + continue + if AWF_WORD.search(line.replace(AWF_CALL, "")): + problems.append(f"{where}: line {number + 1} names awf other than as the call '{AWF_CALL}'") + if AWF_CALL in line: + calls.append(number) + for number in range(calls[0] if calls else 0): + code = lines[number].strip() + if code and not code.startswith("#") and code not in BEFORE_AWF: + problems.append(f"{where}: line {number + 1} before the awf call is not one of {sorted(BEFORE_AWF)}") + for index, number in enumerate(calls): + end = number + while end < len(lines) and not lines[end].strip().startswith("-- ") and lines[end].endswith(" \\"): + end += 1 + command = lines[end].strip() if end < len(lines) else "" + if not command.startswith("-- "): + problems.append(f"{where}: the awf call on line {number + 1} has no '-- ' command line") + continue + if not command.endswith(AWF_COMMAND_END): + problems.append(f"{where}: the awf command does not end with '{AWF_COMMAND_END}' (stderr unfiltered)") + continue + call = "\n".join([*lines[number:end], command.removesuffix(AWF_COMMAND_END)]) + syntax = sorted(set(AWF_CALL_SYNTAX.findall(call))) + if syntax: + problems.append(f"{where}: the awf call on line {number + 1} uses {syntax}, which can bypass the filter") + continue + if not (end + 1 < len(lines) and lines[end + 1].strip() == AWF_OUTPUT_FILTER): + problems.append(f"{where}: the awf command is not followed by '{AWF_OUTPUT_FILTER}'") + continue + stop = calls[index + 1] if index + 1 < len(calls) else len(lines) + for after in range(end + 2, stop): + code = lines[after].strip() + if code and not code.startswith("#") and code not in AFTER_AWF: + problems.append(f"{where}: line {after + 1} after the awf call is not one of {sorted(AFTER_AWF)}") + return problems + + +def _diag_problems(shell: Mapping[str, str]) -> list[str]: + """'diag' is defined once, in common.sh, as one pipeline that ends with exactly the filter.""" + defined = [path for path, text in shell.items() for _ in DIAG_DEFINITION.finditer(text)] + if defined != [COMMON_SH]: + return [f"'diag' is defined in {defined}, not once in {COMMON_SH}"] + body = re.search(r"^diag\(\) \{\n(.*?)\n\}$", shell[COMMON_SH], re.MULTILINE | re.DOTALL) + lines = [line.strip() for line in body.group(1).split("\n")] if body else [] + if not lines or lines[-1] != DIAG_FILTER or not all(line.endswith("|") for line in lines[:-1]): + return [f"{COMMON_SH}: 'diag' is not a pipeline that ends with '{DIAG_FILTER}'"] + return [] + + +def sandbox_output_problems(workflow: Mapping[str, Any], shell: Mapping[str, str]) -> list[str]: + """Every 'awf' call in agent-review.yml, and 'diag' in the harness shell files, filters all its output. + + ``shell`` maps each tracked shell file under agent-review/ to its text. + """ + problems = [] + awf_steps = 0 + for job_id, _, step_name, script in run_scripts(workflow): + awf_steps += AWF_CALL in script + problems += _awf_call_problems(f"{job_id}/{step_name}", script) + if awf_steps == 0: + problems.append("no awf call found") + return problems + _diag_problems(shell) + + +# --- The collect gate ------------------------------------------------------------- + +COLLECT_STEP = "Collect the result" +TEARDOWN_ID = "teardown" +TEARDOWN_SUCCESS = "steps.teardown.outcome == 'success'" + + +def collect_gate_problems(workflow: Mapping[str, Any]) -> list[str]: + """'Collect the result' runs only after a successful teardown, in every job that has it.""" + problems = [] + found = 0 + for job_id, job in workflow["jobs"].items(): + steps = job.get("steps", []) + for index, step in enumerate(steps): + if step.get("name") != COLLECT_STEP: + continue + found += 1 + where = f"{job_id}/{COLLECT_STEP}" + if not any(s.get("id") == TEARDOWN_ID for s in steps[:index]): + problems.append(f"{where}: no earlier step with id '{TEARDOWN_ID}'") + condition = str(step.get("if", "")).strip() + if condition.startswith("${{") and condition.endswith("}}"): + condition = condition[3:-2].strip() + terms = [term.strip() for term in condition.split("&&")] + # Only 'always()' may hold parentheses: no grouping, so no '!(...)'. + plain = "||" not in condition and all(t == "always()" or not set(t) & set("()") for t in terms) + if not plain: + problems.append(f"{where}: 'if:' is not a plain '&&' chain: {condition!r}") + elif TEARDOWN_SUCCESS not in terms: + problems.append(f"{where}: 'if:' does not require {TEARDOWN_SUCCESS!r}: {condition!r}") + if found == 0: + problems.append(f"no '{COLLECT_STEP}' step found") + return problems + + +# --- Tree ---------------------------------------------------------------------- + +FORBIDDEN_NAMES = ("sitecustomize.py", "usercustomize.py", "__pycache__") +FORBIDDEN_SUFFIXES = (".pth", ".pyc", ".pyo") + + +def tree_problems(index: list[tuple[str, str]]) -> list[str]: + """``index``: (git mode, path) of every tracked file under agent-review/.""" + problems = [] + for mode, path in index: + parts = path.split("/") + if mode == "120000": + problems.append(f"{path}: a symlink") + elif mode == "160000": + problems.append(f"{path}: a submodule") + if any(part in FORBIDDEN_NAMES for part in parts) or path.endswith(FORBIDDEN_SUFFIXES): + problems.append(f"{path}: forbidden name") + in_python_dirs = path.startswith(("agent-review/lib/agent_review/", "agent-review/tests/")) + if path.endswith(".py") and not in_python_dirs: + problems.append(f"{path}: Python files belong in lib/agent_review/ (or tests/)") + if path.startswith("agent-review/lib/"): + if not path.startswith("agent-review/lib/agent_review/"): + problems.append(f"{path}: lib/ may hold only agent_review/") + elif not path.endswith(".py"): + problems.append(f"{path}: agent_review/ may hold only .py files") + return problems + + +def shebang_problems(first_lines: Mapping[str, str]) -> list[str]: + """No Python shebang outside lib/agent_review/ and tests/: such a file would run without '-I -S'. + + ``first_lines``: path under agent-review/ -> its first line. + """ + return [ + f"{path}: a Python shebang ('{line}'); use an entry point in bin/" + for path, line in sorted(first_lines.items()) + if line.startswith("#!") + and PYTHON_WORD.search(line) + and not path.startswith(("agent-review/lib/agent_review/", "agent-review/tests/")) + ] + + +# --- Imports and calls (AST) ------------------------------------------------------- + +STDLIB_ALLOWED = frozenset( + { + "__future__", + "argparse", + "base64", + "collections", + "contextlib", + "dataclasses", + "datetime", + "enum", + "errno", + "functools", + "hashlib", + "io", + "itertools", + "json", + "math", + "os", + "pathlib", + "re", + "secrets", + "selectors", + "shutil", + "stat", + "string", + "subprocess", + "sys", + "tempfile", + "textwrap", + "time", + "tomllib", + "typing", + "unicodedata", + } +) +RUNNER_MODULE = "lib/agent_review/runner.py" +GH_MODULE = "lib/agent_review/gh.py" +BANNED_CALLS = frozenset( + {"eval", "exec", "compile", "__import__", "breakpoint", "globals", "locals", "vars", "__builtins__"} +) +# Banned as attributes of anything, not only of 'os', so that a re-exported +# or aliased module cannot reach them ('runner.os.system'). +BANNED_OS = re.compile(r"system|popen|exec[lv]p?e?|spawn[lv]p?e?|posix_spawnp?|fork|forkpty", re.ASCII) +# 'sys.modules' gives any loaded module, whatever the import rules say. +SYS_MODULES_ALLOWED = frozenset({"lib/agent_review/probe.py"}) +# Each trust zone only in the modules that run programs there: gh.py on the +# trusted host, where the token is; run-review in the sandbox. The tainted +# host (collect-result) starts no process, so no module but runner.py names it. +ZONE_ALLOWED = { + "TRUSTED_HOST": frozenset({RUNNER_MODULE, GH_MODULE}), + "SANDBOX": frozenset({RUNNER_MODULE, "lib/agent_review/run_review.py", "lib/agent_review/sandbox_git.py"}), + "TAINTED_HOST": frozenset({RUNNER_MODULE}), +} +ATTRIBUTE_BUILTINS = ("getattr", "setattr", "delattr") +# getattr() on these objects (not modules) is allowed: the probe reads sys.flags by name. +GETATTR_ALLOWED = frozenset({"sys.flags"}) +# The probe lists its imported modules in a tuple to show that they import; +# the rule is off for the whole file. +MODULE_VALUES_ALLOWED = frozenset({"lib/agent_review/probe.py"}) +GH_ENTRY_POINTS = frozenset({"authorize", "publish-comment"}) + + +def _module_name(rel: str) -> str | None: + """'lib/agent_review/x.py' -> 'agent_review.x'; entry points -> None.""" + if not rel.startswith("lib/") or not rel.endswith(".py"): + return None + name = rel[len("lib/") : -len(".py")].replace("/", ".") + return name.removesuffix(".__init__") + + +def _imported_names(tree: ast.AST) -> set[str]: + """The names that import statements bind in ``tree``.""" + bound = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + bound |= {a.asname or a.name.split(".")[0] for a in node.names} + elif isinstance(node, ast.ImportFrom): + bound |= {a.asname or a.name for a in node.names} + return bound + + +def _module_names(tree: ast.AST) -> set[str]: + """The names that import statements bind to modules in ``tree``. + + 'import x' and 'import x.y' bind modules; 'from p import n' does when p is + the agent_review package or n is an allowlisted standard-library module. + """ + bound = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + bound |= {a.asname or a.name.split(".")[0] for a in node.names} + elif isinstance(node, ast.ImportFrom): + bound |= { + a.asname or a.name for a in node.names if node.module == "agent_review" or a.name in STDLIB_ALLOWED + } + return bound + + +def _dotted(node: ast.AST) -> str | None: + """'os.path' for the expression os.path; None if it is not a plain name chain.""" + parts = [] + while isinstance(node, ast.Attribute): + parts.append(node.attr) + node = node.value + if not isinstance(node, ast.Name): + return None + return ".".join([node.id, *reversed(parts)]) + + +def ast_problems(sources: Mapping[str, str]) -> list[str]: + """``sources``: path relative to agent-review/ -> text, for lib/ and the Python bin/ files.""" + problems = [] + for rel, text in sorted(sources.items()): + try: + tree = ast.parse(text, filename=rel) + except SyntaxError as e: + problems.append(f"{rel}: does not parse ({e.msg})") + continue + imported = _imported_names(tree) + modules = _module_names(tree) + attribute_bases = {id(node.value) for node in ast.walk(tree) if isinstance(node, ast.Attribute)} + called = {id(node.func) for node in ast.walk(tree) if isinstance(node, ast.Call)} + for node in ast.walk(tree): + where = f"{rel}:{getattr(node, 'lineno', 0)}" + names: list[str] = [] + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + # 'import os as o' would hide 'o.system' from the attribute rule. + problems += [f"{where}: 'import os as {a.asname}'" for a in node.names if a.name == "os" and a.asname] + elif isinstance(node, ast.ImportFrom): + if node.level: + problems.append(f"{where}: relative import; use 'agent_review.'") + continue + if any(a.name == "*" for a in node.names): + problems.append(f"{where}: 'from {node.module} import *'") + names = [node.module or ""] + if node.module == "os": + problems += [f"{where}: os.{a.name}" for a in node.names if BANNED_OS.fullmatch(a.name)] + if (node.module or "").split(".")[0] == "agent_review": + # A standard-library module re-exported by a package module + # ('from agent_review.runner import subprocess'). + problems += [ + f"{where}: '{a.name}' imported through {node.module}" + for a in node.names + if a.name in STDLIB_ALLOWED or a.name in ("importlib", "pickle", "marshal", "ctypes") + ] + for name in names: + top = name.split(".")[0] + if top == "subprocess" and rel != RUNNER_MODULE: + problems.append(f"{where}: subprocess outside agent_review/runner.py") + elif top not in STDLIB_ALLOWED and top != "agent_review": + problems.append(f"{where}: import of '{name}' is not allowlisted") + if isinstance(node, ast.Name) and node.id in BANNED_CALLS: + problems.append(f"{where}: '{node.id}'") + if isinstance(node, ast.Attribute): + if BANNED_OS.fullmatch(node.attr): + problems.append(f"{where}: '.{node.attr}'") + if node.attr == "subprocess" and rel != RUNNER_MODULE: + problems.append(f"{where}: '.subprocess' outside agent_review/runner.py") + if node.attr in ZONE_ALLOWED and rel not in ZONE_ALLOWED[node.attr]: + problems.append(f"{where}: the zone '{node.attr}' outside its modules") + if ( + node.attr == "modules" + and isinstance(node.value, ast.Name) + and node.value.id == "sys" + and rel not in SYS_MODULES_ALLOWED + ): + problems.append(f"{where}: 'sys.modules'") + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id in ATTRIBUTE_BUILTINS + and node.args + ): + chain = _dotted(node.args[0]) + if chain is not None and chain.split(".")[0] in imported and chain not in GETATTR_ALLOWED: + problems.append(f"{where}: {node.func.id}() on the module '{chain}'") + if ( + isinstance(node, ast.Name) + and isinstance(node.ctx, ast.Load) + and node.id in modules + and id(node) not in attribute_bases + and rel not in MODULE_VALUES_ALLOWED + ): + # 'x = os' or 'f(os)' would hide a module from the rules above. + problems.append(f"{where}: the module '{node.id}' used as a value") + if isinstance(node, ast.Name) and node.id in ATTRIBUTE_BUILTINS and id(node) not in called: + # 's = setattr' would hide the call from the getattr rule. + problems.append(f"{where}: '{node.id}' used as a value") + if isinstance(node, ast.keyword) and node.arg == "shell": + problems.append(f"{where}: a 'shell=' argument") + if ( + isinstance(node, ast.Constant) + and isinstance(node.value, str) + and node.value.rsplit("/", 1)[-1] == "gh" + and rel != GH_MODULE + ): + problems.append(f"{where}: the 'gh' program outside agent_review/gh.py") + return problems + + +def _imports(text: str, known: set[str]) -> set[str]: + """The agent_review modules that ``text`` imports.""" + found = set() + for node in ast.walk(ast.parse(text)): + if isinstance(node, ast.Import): + found |= {a.name for a in node.names if a.name in known} + elif isinstance(node, ast.ImportFrom) and node.module and not node.level: + if node.module in known: + found.add(node.module) + found |= {f"{node.module}.{a.name}" for a in node.names if f"{node.module}.{a.name}" in known} + return found + + +def import_closure(text: str, modules: Mapping[str, str]) -> set[str]: + """Every agent_review module reachable from ``text``; ``modules``: name -> text.""" + known = set(modules) + seen: set[str] = set() + todo = _imports(text, known) + while todo: + name = todo.pop() + if name in seen: + continue + seen.add(name) + parent = name.rpartition(".")[0] + if parent in known: + todo.add(parent) + todo |= _imports(modules[name], known) - seen + return seen + + +def token_reach_problems(sources: Mapping[str, str]) -> list[str]: + """Only the 'authorize' and 'publish-comment' entry points reach agent_review.gh.""" + modules = {m: text for rel, text in sources.items() if (m := _module_name(rel))} + problems = [] + for rel, text in sorted(sources.items()): + if not rel.startswith("bin/"): + continue + name = rel[len("bin/") :] + if "agent_review.gh" in import_closure(text, modules) and name not in GH_ENTRY_POINTS: + problems.append(f"{rel}: reaches agent_review.gh (the token); only {sorted(GH_ENTRY_POINTS)} may") + return problems + + +# --- The repository --------------------------------------------------------------- + + +def git_index(prefix: str = "agent-review") -> list[tuple[str, str]]: + """(mode, path) of the tracked files under ``prefix``: what the trusted tarball ships.""" + out = subprocess.run( + ["git", "-C", str(ROOT), "ls-files", "-s", "-z", "--", prefix], + check=True, + capture_output=True, + ).stdout.decode("utf-8") + index = [] + for record in out.split("\0"): + if record: + meta, path = record.split("\t", 1) + index.append((meta.split(" ")[0], path)) + return index + + +def read(rel: str) -> str: + return (AR_DIR / rel).read_text(encoding="utf-8") + + +def repository() -> dict[str, Any]: + """The tracked files the checks need.""" + index = git_index() + modes = {path.removeprefix("agent-review/"): mode for mode, path in index} + entries = {rel[len("bin/") :]: (read(rel), mode) for rel, mode in modes.items() if rel.startswith("bin/")} + kinds = {name: entry_kind(name, text) for name, (text, _) in entries.items()} + lib = {rel: read(rel) for rel in modes if rel.startswith("lib/") and rel.endswith(".py")} + python = {**lib, **{f"bin/{n}": entries[n][0] for n, k in kinds.items() if k == "python"}} + shell = { + rel: read(rel) + for rel in modes + if rel.startswith("harnesses/") and (rel.endswith(".sh") or read(rel).startswith("#!")) + } + first_lines = {path: _first_line(path) for mode, path in index if mode != "120000"} + return { + "index": index, + "entries": entries, + "kinds": kinds, + "lib": lib, + "python": python, + "shell": shell, + "first_lines": first_lines, + } + + +def _first_line(path: str) -> str: + with (ROOT / path).open("rb") as f: + return f.readline(256).decode("utf-8", errors="replace").rstrip("\n") + + +def load(path: pathlib.Path) -> Any: + with path.open(encoding="utf-8") as f: + return yaml.safe_load(f) diff --git a/docs/adr/0004-python-runtime.md b/docs/adr/0004-python-runtime.md new file mode 100644 index 0000000..8af5c46 --- /dev/null +++ b/docs/adr/0004-python-runtime.md @@ -0,0 +1,65 @@ +# Python for the agent review's trusted code, and how it runs + +- **Status**: valid +- **Authors**: Enrique González Paredes (@egparedes) +- **Created**: 2026-11-14 +- **Updated**: 2026-11-16 + +Why-statement: In the context of the agent review's trusted scripts ([ADR 0001](0001-sandboxed-agent-pr-review.md), [ADR 0002](0002-reusable-workflow.md)), which run on the host next to tokens or inside the sandbox on hostile pull request content, facing bash's weak handling of untrusted text (byte-range `sed` sanitising, ad-hoc parsing, no unit tests), we decided to port them one by one to Python using only the standard library, run only as `/usr/bin/python3 -I -S -B /bin/` from thin entry points that refuse to run otherwise, with process execution, tool lookup and environment chosen per trust zone, to achieve code that can be unit-tested and type-checked without importing anything a pull request or the runner's environment can influence. We considered staying with bash and plain `python3 -I`, and accept a structure test that pins every call site and import, test-only tools installed from hash-pinned requirements, and a runtime tied to the runner image's Python (3.12 on `ubuntu-24.04`). + +## Context + +- The scripts in `agent-review/bin/` (`authorize`, `run-review`, `collect-result`, `publish-comment`) are about 1,000 lines of bash. `publish-comment` sanitises model output with `sed` in the only job with a write token; `run-review` parses untrusted JSON and paths in the sandbox. +- AWF chroots into the host filesystem, so the sandbox has the runner image's `/usr/bin/python3` (Ubuntu 24.04: 3.12) and standard library; no other Python is guaranteed, and nothing may be installed at run time. +- `python3 -I` alone is not enough on Ubuntu: it still imports `sitecustomize` (apport's hook, from `/etc/python3.12/`) and adds two `dist-packages` directories, whose `.pth` files it executes. `-I -S -B` leaves the standard library only (verified on 3.12.3). +- A shebang cannot carry two options (`#!/usr/bin/python3 -I -B` passes one argument, `-I -B`, which Python rejects), and a bare `python3` is looked up on the runner's `PATH`, which searches home directories such as `~/.local/bin` before `/usr/bin`, so whatever an earlier step put there would run instead. +- `-B` stops Python writing `.pyc` files, not reading an existing one next to the source. +- Python's defaults accept more than bash's checks: `re.match` with `$` accepts a trailing newline; `\d` and `\w` match non-ASCII; `int()` accepts full-width digits, `_` and whitespace. +- The bash test suites are the specification of each script's behaviour (about 100 cases), and they find tools on `PATH` (a fake `gh`) and pass environment variables (`GIT_ALLOW_PROTOCOL=none`). + +## Decision + +- **Interpreter and flags.** Python entry points run only as `/usr/bin/python3 -I -S -B /bin/`: absolute interpreter, isolated mode (no `PYTHON*` variables, no user site, neither the script's directory nor the working directory on `sys.path`), no `site` (no `sitecustomize`, no `dist-packages`, no `.pth`), no bytecode written. Never `-c`, `-m`, `pip` or `setup-python` in `agent-review.yml`. +- **Entry points** are files without a `.py` suffix, mode 100644 (not executable, so no shebang can run them with other flags), and exactly one fixed template apart from the module name ([`workflow_structure.py`](../../agent-review/tests/workflow_structure.py)). The template exits with status 2 unless `sys.flags.isolated`, `no_site`, `dont_write_bytecode` and `safe_path` are all set, then inserts the real path of `bin/../lib` at `sys.path[0]` and calls `agent_review..main()`. All logic is in the package `agent-review/lib/agent_review/`, the only content of `lib/`. +- **Roots.** `"${RUNNER_TEMP}/trusted/bin/"` in `authorize`, `prepare` and `publish`; `/opt/agent-review/bin/` (root-owned, read-only in the sandbox) in both review jobs from the "Prepare the sandbox inputs" step on, including the AWF command lines. The library is found from the entry point's real path, so the same files work from both roots. Python call sites name the file inline, never through a variable, and start a command, so a reviewer sees every call. Shell files under `bin/` and `harnesses/` call Python only in the same form, with the root set from the file's own path by one fixed line. No file outside `lib/agent_review/` and `tests/` is a `.py` file or has a Python shebang: such a file would run without `-I -S`. +- **Standard library only**, from an allowlist of modules, without dynamic code (`eval`, `exec` and the like), shell or process calls outside `runner.py`, and without the obvious indirect routes around these rules (aliased imports, `getattr` on a module, a module stored in a variable, `sys.modules`). The exact lists are in [`workflow_structure.py`](../../agent-review/tests/workflow_structure.py). +- **Processes and trust zones** ([`runner.py`](../../agent-review/lib/agent_review/runner.py), the only module that imports `subprocess`): argument lists only, the program resolved to an absolute path first, `PATH` entries that are not absolute skipped, stdin from `/dev/null` unless given. Each zone is named only by the modules that run programs there: the trusted host by `gh.py`, the sandbox by `run_review.py` and `sandbox_git.py`. + - *Trusted host* (`authorize`, `publish-comment post`: before any untrusted code, or on a fresh VM): `PATH` lookup and the inherited environment, so the test suites' fake `gh` is found; the workflow sets `PATH: /usr/bin:/bin` on those steps (`Authorize`, `Render the review`, `Publish the review`), so `gh` is `/usr/bin/gh`. + - *Sandbox* (`run-review`): `PATH` lookup and the inherited environment plus the caller's overrides (the forced `GIT_*` settings); an inherited `GIT_ALLOW_PROTOCOL` reaches git. + - *Tainted host* (after the sandbox ran): no process starts there today (`collect-result` starts none). The zone exists so that any future one gets an absolute program under `/usr/bin` or `/bin` and a fixed environment (`PATH=/usr/bin:/bin`, `LC_ALL=C.UTF-8`), since the runner's `PATH` searches home directories such as `~/.local/bin` first: AWF mounts them read-only, but after the sandbox has run the host is treated as tainted (invariant 3 in [agent-review.md](../agent-review.md)). +- **GitHub API** through `gh api` as a subprocess ([`gh.py`](../../agent-review/lib/agent_review/gh.py)), never `urllib`: the token stays in `gh`, proxy variables are not honoured by accident, and the suites' fake `gh` keeps working. Projections stay in `gh --jq`: a PR object or a comment body is handled only by `gh`'s JSON decoder, and our code receives only the projected fields (invariant 2). Only the `authorize` and `publish-comment` entry points may import it, and only `gh.py` names the program (by basename) and uses the trusted-host zone. Which steps hold the token is decided by the workflow (the step's `env:`); this rule keeps the code that can run `gh` narrow. +- **Untrusted data**: validation with `re.fullmatch` and ASCII-only classes, and before every `int()` ([`validate.py`](../../agent-review/lib/agent_review/validate.py)); files opened with `O_NOFOLLOW | O_NONBLOCK`, checked with `fstat` on the descriptor, read up to a cap ([`files.py`](../../agent-review/lib/agent_review/files.py)); bytes or strict UTF-8 (U+FFFD replacement only where untrusted text is just data, such as the PR title and body in the prompt), never the locale's encoding; workflow commands escape `%`, CR and LF, step outputs reject CR and LF; untrusted log text gets a prefix on every line that starts with neither whitespace nor `:` (the runner trims leading whitespace before matching `::`), and every `##[` in it is broken up with a zero-width space (the runner's legacy parser finds `##[command]` anywhere in a line) ([`workflow.py`](../../agent-review/lib/agent_review/workflow.py)). `runner.run` caps a command's captured stdout (16 MiB by default), or sends it uncapped to a descriptor the caller opened (a file, or the caller's own stdout), and keeps only the tail of its stderr. +- **The tree** under `agent-review/` has no symlink, submodule, `.pth`, `.pyc`, `__pycache__`, `sitecustomize.py` or `usercustomize.py`, and `lib/agent_review/` holds only `.py` files: the tarball the workflow fetches is the git tree. +- **Command-line contract.** Each entry point keeps a fixed contract (arguments, exit codes, outputs, notices), so the workflow depends only on its call line. The `.sh` suites are the black-box specification of that contract and run each entry point with the production command line (`tests/lib.sh`); new logic gets pytest unit tests. +- **Enforcement.** [`test-workflow-structure.py`](../../agent-review/tests/test-workflow-structure.py) checks all of the above on every pull request; [`workflow_structure.py`](../../agent-review/tests/workflow_structure.py) lists every check. Its rules are unit-tested on crafted inputs in [`tests/python/`](../../agent-review/tests/python/); the script's own job-level checks run only against the real workflow. These code rules are tripwires against mistakes and visible shortcuts, not a sandbox: Python offers more spellings (`Zone['SANDBOX']`, `os.__dict__`) than an AST check can list, and each of them still shows up in review of the diff. The self-test's stub run prints `bin/probe` on the host and inside AWF, and the `check` job asserts both lines. +- **Tooling**, test-only: the tools of [`requirements.in`](../../agent-review/tests/requirements.in) in the self-test's `python` job, from [`requirements.txt`](../../agent-review/tests/requirements.txt) with hashes (`pip install --require-hashes`) in a virtual environment; ruff and mypy in pre-commit, hooks pinned by commit SHA. Runtime code never imports them. + +## Consequences + +- The scripts can be unit-tested and type-checked, while the `.sh` suites keep checking their command-line behaviour. +- The runtime depends on the runner image's Python. A new `ubuntu-24.04` image with another 3.12 patch release is harmless; another minor version would fail the self-test's probe check (it expects 3.12) until reviewed. Inside AWF the interpreter is the same file; the probe's two lines show the same path, version and flags on every self-test run. +- A new standard-library import, entry point or call site needs a change to the structure test's tables, which a reviewer sees. +- The inline `run:` bash in the workflow stays (rendering the AWF configuration, the token report, the publish step's result logic): Python has no YAML parser in the standard library, and "Fetch trusted files" bootstraps the trusted files, so it cannot be Python itself. +- Developers run the tests with `python3 -B -m pytest` from the repository root, with the tools of `requirements.txt` installed; without `-B`, `__pycache__` directories appear in the working tree (ignored by git, so never shipped). + +## Alternatives considered + +### Stay with bash + +- Good, because nothing changes, and the scripts are reviewed. +- Bad, because sanitising and parsing hostile text with `sed`, `grep` and `jq` is hard to get right and to test, and bash has no types. + +### `python3 -I` (or `-I -B`) and a shebang + +- Good, because it is shorter and the scripts stay executable. +- Bad, because `-I` still runs `sitecustomize` and `.pth` files, a shebang cannot pass two options, and a bare `python3` comes from `PATH`. + +### Dependencies (a vendored or pip-installed package) + +- Good, because libraries such as a YAML parser or a Markdown sanitiser exist. +- Bad, because nothing may be installed at run time, vendored code needs its own review and updates, and the standard library covers what the scripts do. + +## References + +- [agent-review.md](../agent-review.md): security invariants, testing. +- Python docs: [Command line and environment](https://docs.python.org/3/using/cmdline.html) (`-I`, `-S`, `-B`, `-P`), [`sys.flags`](https://docs.python.org/3/library/sys.html#sys.flags). diff --git a/docs/agent-review.md b/docs/agent-review.md index 22abac3..3ecc1bf 100644 --- a/docs/agent-review.md +++ b/docs/agent-review.md @@ -93,7 +93,7 @@ Optionally, a **test job** for the caller's own pull requests (see [Caller test ### Inputs -`workflow_call` has no `choice` type, so every value is validated in the `authorize` job by [`bin/authorize`](../agent-review/bin/authorize), fail-closed, with offline unit tests ([`tests/test-authorize.sh`](../agent-review/tests/test-authorize.sh)). +`workflow_call` has no `choice` type, so every value is validated in the `authorize` job by [`bin/authorize`](../agent-review/bin/authorize) (Python, [`lib/agent_review/authorize.py`](../agent-review/lib/agent_review/authorize.py)), fail-closed, with offline unit tests ([`tests/test-authorize.sh`](../agent-review/tests/test-authorize.sh), [`tests/python/test_authorize.py`](../agent-review/tests/python/test_authorize.py)). A value must match its whole pattern, in ASCII only (a value that is not UTF-8 fails), and every value quoted in a notice or error is escaped, so it cannot start another workflow command. | Input | Default | Meaning and validation | | --- | --- | --- | @@ -117,7 +117,7 @@ Optionally, a **test job** for the caller's own pull requests (see [Caller test Callers can lower the caps, never raise them: `authorize` rejects larger values, zero and non-integers (unit-tested), and the review job clamps them to [`awf.yaml`](../agent-review/awf.yaml) again (checked in the self-test's log). -**Secret**: `inference_api_key`, optional; without it, a harness that calls a model is skipped with a notice. It must be an **environment** secret: `authorize`, which has no environment, fails if the mapped name resolves there (a repository or organization secret of that name). **Outputs**: `result` (`posted`, `dry-run`, `skipped`, `missing`, `invalid`; empty if not authorized), `comment_url`, `head_sha`. +**Secret**: `inference_api_key`, optional; without it, a harness that calls a model is skipped with a notice. It must be an **environment** secret: `authorize`, which has no environment, fails if the mapped name resolves there (a repository or organization secret of that name). **Outputs**: `result` (`posted`, `dry-run`, `skipped`, `missing`, `invalid`; `rendered` if posting the comment failed; empty if not authorized), `comment_url`, `head_sha`. ## Required settings in the calling repository @@ -157,9 +157,11 @@ Each harness keeps one comment per PR, updated in place by later runs. The comme | --- | --- | --- | | `authorize` | read token, **no secrets** | Records this workflow's own commit (`job.workflow_repository`@`job.workflow_sha`), fetches `agent-review/` from it, and runs [`bin/authorize`](../agent-review/bin/authorize): validates the inputs, picks the endpoint from the allowlist, decides from its harness allowlist whether the run is **keyed**, applies the event rules, checks permissions (fails closed on API errors) and pins the PR head and base sha. Every other job requires its `allowed` output. | | `prepare` | read token, **no secrets** | Fetches [`agent-review/`](../agent-review/) from this workflow's own commit (checking that its own `job.workflow_sha` is the one recorded), runs the harness's `install.sh`, which downloads the pinned harness without running any of its code, and uploads it as an artifact. | -| `review` (keyed) or `review-keyless` | read token; for `review` only: inference key in **one step's** env (caller's environment) | The two jobs run the same steps (YAML aliases); only `review` declares the environment and references the secret, and only keyed harnesses under `pull_request_target` or `workflow_dispatch` run it, one at a time per PR (its own concurrency group). Fetches `agent-review/` as above and the caller's addendum from the caller repository at the caller's `github.workflow_sha`, copies them to `/opt/agent-review` (root-owned, read-only in the sandbox), writes the PR metadata as raw bytes, and runs AWF twice. First without a key and with only `github.com` allowed: [`run-review`](../agent-review/bin/run-review) `--phase fetch` fetches the PR with git, resets agent instruction files and rule files to the base version and renders the prompt; no agent runs. Then with the key (keyed job only) and no allowed domain: `run-review --phase review` runs the harness. Afterwards leftover containers are removed and [`collect-result`](../agent-review/bin/collect-result) copies only `review.md` and `meta.json` out. | +| `review` (keyed) or `review-keyless` | read token; for `review` only: inference key in **one step's** env (caller's environment) | The two jobs run the same steps (YAML aliases); only `review` declares the environment and references the secret, and only keyed harnesses under `pull_request_target` or `workflow_dispatch` run it, one at a time per PR (its own concurrency group). Fetches `agent-review/` as above and the caller's addendum from the caller repository at the caller's `github.workflow_sha`, copies them to `/opt/agent-review` (root-owned, read-only in the sandbox), writes the PR metadata as raw bytes, and runs AWF twice. First without a key and with only `github.com` allowed: [`run-review`](../agent-review/bin/run-review) `--phase fetch` fetches the PR with git, resets agent instruction files and rule files to the base version and renders the prompt; no agent runs. Then with the key (keyed job only) and no allowed domain: `run-review --phase review` runs the harness. Afterwards leftover containers are removed and [`collect-result`](../agent-review/bin/collect-result) copies only `review.md` and `meta.json` out; it starts no process and opens the output directory one component at a time from `/`, none a symlink, then reads both files through that descriptor. | | `publish` | write token (`pull-requests`), no model | On a fresh VM, [`publish-comment`](../agent-review/bin/publish-comment) validates and renders the review in a step without a token, then upserts the comment. | +The trusted code is in [`agent-review/`](../agent-review/): `bin/` holds the entry points the workflow calls, `lib/agent_review/` the Python package they use (standard library only), `harnesses/` the adapters, `tests/` the tests. The scripts in `bin/` are Python. Each is a fixed template that refuses to run unless started as `/usr/bin/python3 -I -S -B /bin/` ([ADR 0004](adr/0004-python-runtime.md)). [`bin/probe`](../agent-review/bin/probe) prints the interpreter's version and flags; the `stub` harness runs it on the host (in `prepare`) and in the sandbox. + The generic review rules are in [`prompt.md.tmpl`](../agent-review/prompt.md.tmpl); the project-specific part is the caller's `rule_files` (listed in order) and its addendum. Extend the caller's rule files rather than the prompt. The PR title and body are included as delimited untrusted data. The prompt also asks the agent to finish within about 12 minutes, to read narrowly, to confirm each finding against the code and say how, and to keep maintainability remarks to an optional `### Nits` section of at most three lines; the comment has `### Summary`, `### Findings` (at most five), and optionally `### Nits` and `### Questions`. ## Security invariants @@ -167,21 +169,37 @@ The generic review rules are in [`prompt.md.tmpl`](../agent-review/prompt.md.tmp Callers use `pull_request_target` because fork PRs get no secrets under `pull_request`. That trigger runs with secrets next to untrusted code, so all PR content is handled inside AWF only. Keep these when changing anything here: 01. **The real key is only in AWF's API-proxy sidecar** and the environment of the `awf` step that runs the agent in the keyed `review` job; the agent sees placeholders. Never inline it into a `run:` script or pass it to another step. It comes from the caller's environment (`agent-review`), only through the caller's explicit mapping and only in the job that declares that environment, never from a repository secret (`authorize` fails if it resolves without the environment). It goes only to an endpoint of [`api-bases.txt`](../agent-review/api-bases.txt) in the pinned commit. [`tests/test-workflow-structure.py`](../agent-review/tests/test-workflow-structure.py) checks that no job without an environment references a secret, apart from that boolean check. -02. **No PR-derived byte is executed or parsed on the host.** No `actions/checkout`, no git on the PR tree outside the sandbox. `pr.json` is written as bytes and parsed inside the sandbox. The one exception is AWF's token-usage log, which the API-proxy sidecar writes out of the sandbox's reach; its request paths and model names come from the agent's requests, so the `Report token usage` step reads only its numeric fields. `prepare` never executes harness code either: it runs on the host with sudo, and its token can read and write the caller's Actions cache. -03. **The sandbox writes only to the review workspace** (`filesystem.allowWrite`); the rest of what AWF mounts from the host (the runner workspace, `/tmp`, `~/.config`, `~/.local/bin`, ...) is read-only to it. Exception: `~/.copilot/{logs,session-state}` stay writable, and AWF moves them into host `/tmp` after the run. So **the host is treated as tainted once `awf` returns**: steps after the agent's run use no token, run no git, use no cache action, and run only `/usr/bin` tools with a fixed `PATH`. The only data leaving `review` is at most 64 KiB per file of regular, single-link files named `review.md` and `meta.json`, copied without following symlinks, after every sandbox container has been removed, plus the token counts in the run summary and, with `upload_audit`, AWF's own audit and proxy logs from `$RUNNER_TEMP`. +02. **No PR-derived byte is executed on the host, nor parsed by our code there.** No `actions/checkout`, no git on the PR tree outside the sandbox. `pr.json` is written as bytes and parsed inside the sandbox. Where the host must ask the API about the PR or its comments (`authorize`, `publish-comment post`), the JSON is handled only by `gh`'s own decoder (`gh api --jq`), and our code receives only the projected fields (shas, a permission, comment ids, logins and the first 256 characters of each first line). The one exception is AWF's token-usage log, which the API-proxy sidecar writes out of the sandbox's reach; its request paths and model names come from the agent's requests, so the `Report token usage` step reads only its numeric fields. `prepare` never executes harness code either: it runs on the host with sudo, and its token can read and write the caller's Actions cache. +03. **The sandbox writes only to the review workspace** (`filesystem.allowWrite`); the rest of what AWF mounts from the host (the runner workspace, `/tmp`, `~/.config`, `~/.local/bin`, ...) is read-only to it. Exception: `~/.copilot/{logs,session-state}` stay writable, and AWF moves them into host `/tmp` after the run. So **the host is treated as tainted once `awf` returns**: steps after the agent's run use no token, run no git, use no cache action, and run only `/usr/bin` tools with a fixed shell and `PATH`; nothing they inherit (the workflow's and the job's `env:` and `defaults:`, `$GITHUB_ENV`) carries a token, and no step of the review jobs sets a variable that runs code before a step's script, such as `BASH_ENV`. Only this leaves `review`: + - `review.md` and `meta.json`, at most 64 KiB each: regular, single-link files, copied without following symlinks or blocking on FIFOs, and only after every sandbox container has been removed (the single-link check relies on that); + - the token counts in the run summary; + - with `upload_audit`, AWF's own audit and proxy logs from `$RUNNER_TEMP`. + + The structure test checks those steps, what they inherit and the teardown gate ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py) lists the checks). 04. **The agent has no network access** except AWF's API-proxy listener: its sandbox run allows no domain. Only the first, keyless run, which runs no agent, reaches `github.com`. AWF still allows the inference host for its sidecar in the shared egress proxy, so the agent can probably reach it directly too (not tried), without a key. -05. **Write tokens exist only in `publish`**, which runs no model and no PR code, and treats the review as hostile: it must be valid UTF-8; invisible format characters (zero-width, bidirectional controls, variation selectors, tag characters) are dropped; markup that GitHub renders as nothing (HTML comments, processing instructions, declarations, CDATA, link reference definitions) is broken up, so the review cannot hide text that way nor imitate the comment marker; character references are escaped (`@` and `@` would become mentions, `‏` an invisible character); `@mentions` are neutralised with a zero-width joiner; the length is capped. Rendering needs no token. The marker is matched only on the first line of the bot's own comments, never with `--edit-last`, because other tools (such as PR Agent) may post as the same bot. -06. **Harness, prompt and AWF configuration come from this workflow's own commit** (`job.workflow_repository` at `job.workflow_sha`, the commit the caller pinned, fetched as a tarball and checked to be the same in every job), never from the PR or the caller. **The caller's configuration** (inputs and the addendum) comes from the caller's workflow commit: the default branch under `pull_request_target`, the dispatched ref under `workflow_dispatch` (which the environment rule gates). **Instruction files** matching [`instruction-files.txt`](../agent-review/instruction-files.txt) or the caller's `instruction_files`, and every `rule_files` entry, at any depth, are reset to the version in the PR's **base commit** (or removed): that is the branch the PR targets, not necessarily the default one. The PR's versions are kept as data for the review. After the reset, `run-review` checks the result: every rule file and every file the addendum names (in backticks, with one of the listed extensions) must be byte-identical to its base version or absent in both, with no symlinked parent directory; otherwise the fetch phase stops before the prompt exists, which ends as a green run with a "no review" warning (fail closed, advisory check). This post-condition, not the earlier pattern check (bash matching, where `*` crosses `/`), is what enforces the invariant; `tests/test-run-review.sh` and `tests/test-instruction-coverage.sh` check both. Under `pull_request` (caller test mode) the caller's configuration is PR content, so this invariant does not hold there. +05. **Write tokens exist only in `publish`**, which runs no model and no PR code, and treats the review as hostile ([`sanitize.py`](../agent-review/lib/agent_review/sanitize.py)): it must be valid UTF-8 (strict: no surrogates, nothing above U+10FFFF); control characters other than tab and newline are dropped, and so are invisible characters: a fixed list of ranges (zero-width, bidirectional controls, variation selectors, tag characters) plus every character of Unicode category `Cf` (the list stays, because variation selectors are `Mn` and a character newer than Python's Unicode version is `Cn`); no raw HTML can form: a zero-width space follows every `<` that is followed by an ASCII letter, `/`, `!` or `?`, so there is no tag, end tag, HTML block, comment, processing instruction, declaration or CDATA section (GitHub strips attributes and hides some HTML content, and the review cannot imitate the comment marker); comment ends (`-->`) and link reference definitions (`[label]: url`) are broken up too; character references are escaped (`@` and `@` would become mentions, `‏` an invisible character; without HTML, a named reference needs its `;`); `@mentions` are neutralised with a zero-width joiner; the length is capped, never inside a character or a neutralisation, and the comment says so if and only if content was cut. Rendering needs no token. The marker is matched only on the first line of the bot's own comments, never with `--edit-last`, because other tools (such as PR Agent) may post as the same bot; the comment listing is a `gh --jq` projection (id, login, and at most the first 256 characters of the first line, so that a long comment adds at most about 1 KB to it; a pull request with many thousands of comments can still exceed the output cap or the time limit, and then `post` fails without posting), so the comment bodies are handled only by `gh`'s JSON decoder and our code receives only the projected fields. In `publish`, the review never reaches a log: the rendered body goes to a file, then to the comment or, in a dry run, to the run summary; `post` prints only the comment URL, and `gh`'s errors prefixed and with `##[` broken up. +06. **Harness, prompt and AWF configuration come from this workflow's own commit** (`job.workflow_repository` at `job.workflow_sha`, the commit the caller pinned, fetched as a tarball and checked to be the same in every job), never from the PR or the caller. **The caller's configuration** (inputs and the addendum) comes from the caller's workflow commit: the default branch under `pull_request_target`, the dispatched ref under `workflow_dispatch` (which the environment rule gates). **Instruction files** matching [`instruction-files.txt`](../agent-review/instruction-files.txt) (the central list; the fetch phase fails if it is missing or holds no pattern) or the caller's `instruction_files`, and every `rule_files` entry, at any depth, are reset to the version in the PR's **base commit** (or removed): that is the branch the PR targets, not necessarily the default one. The PR's versions are kept as data for the review. A pattern's directories are reset too, so a PR cannot keep its files reachable through a link such as `.opencode -> evil/`. Whether a pattern matches a path is always git's decision (`:(glob,icase)**/`), both in the reset and in the earlier check that some pattern covers each file the addendum names, so the two cannot disagree. Two post-conditions on the result then enforce the invariant, whatever the matching does. If either fails, the fetch phase stops before the prompt exists, with a message naming the path and the reason, and the run ends green with a "no review" warning (fail closed, advisory check): + - every rule file and every file the addendum names (in backticks, with one of the listed extensions) is byte-identical to its base version or absent in both, with no symlinked parent directory; + - no symlink or gitlink remains where a pattern matches, at a directory pattern's directory, or at a directory leading to a pattern with `/`, except: + - a gitlink that is the base commit's own, with an empty directory (submodules are never fetched); + - a base symlink linking one instruction file or directory to another (`AGENTS.md -> CLAUDE.md`, `.claude/skills -> ../.agents/skills`), if its target is relative, inside the repository and covered by the reset; otherwise the agent would read the PR's version of the target (see [What remains risky](#what-remains-risky)); + - a base symlink standing only where a wildcard pattern expects a directory on the way (`docs/*/RULES.md`), if it leads to a regular file or to nothing, since no instruction file can lie below it. + + The exact conditions are in `verify_no_linked_directories` ([`reset.py`](../agent-review/lib/agent_review/reset.py)). `tests/test-run-review.sh` and `tests/test-instruction-coverage.sh` check both post-conditions, and [`test_run_review.py`](../agent-review/tests/python/test_run_review.py) runs the fetch phase with the reset subverted (a PR-version, added or deleted rule file, a symlinked parent) to show that they stop it. Under `pull_request` (caller test mode) the caller's configuration is PR content, so this invariant does not hold there. 07. **The `review` job starts no service on the host.** The sandbox can connect to any host port bound to `0.0.0.0` through AWF's network gateway (`172.30.0.1`); on a stock runner that is only `sshd`. No `services:` containers, no daemons started in a step. 08. **AWF's logs are read only from `$RUNNER_TEMP`** (`--proxy-logs-dir`, `--audit-dir`). Without `--proxy-logs-dir`, AWF moves them to `/tmp` after the run, where the sandbox can plant fake ones. 09. **Only AWF's OpenAI listener is configured**: never an `anthropic` target or `ANTHROPIC_API_KEY`. In AWF v0.29.12 the Anthropic listener's `POST /messages` is not counted by `maxTurns`, and the key breaks the entrypoint under `filesystem.allowWrite`. The run log shows `API proxy enabled: OpenAI=true, Anthropic=false`. 10. **Pinned**: actions by commit SHA, the runner image (`ubuntu-24.04`, which is the sandbox's userland since AWF chroots into the host filesystem), the AWF version, AWF images by digest (the setup action's `image-tag` output, taken from the attested release at run time), and each harness by exact version with an integrity check. Not pinned: the runner image's own updates, and the model behind its id. -11. **The sandbox's output cannot issue workflow commands**: every line of `awf` output is prefixed. Harness diagnostics go through `diag` in `common.sh`, which does the same. +11. **The sandbox's output cannot issue workflow commands**: every line of `awf` output is prefixed, so none starts with `::`; NUL bytes are dropped, and every `##[` in it is then broken up with a zero-width space, because the runner also accepts the legacy `##[command]` syntax anywhere in a line (verified: before this, a sandbox line `##[warning]…` became an annotation). Harness diagnostics go through `diag` in `common.sh`, which does the same. The stub prints such a line on stdout and through `diag` in every self-test run, also with a NUL between the two `#`, and the `check` job asserts that no annotation results; the structure test checks that every `awf` call sends stdout and stderr through the filter, that nothing else in its step can print, and that `diag` is the one filtered definition ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py)). 12. **Per-job least privilege under the caller's ceiling**: top-level `permissions: {}`; `authorize`, `review` and `review-keyless` read contents and pull requests, `prepare` reads contents, `publish` adds `pull-requests: write` (the structure test checks that no other job can write). The caller grants exactly `contents: read` and `pull-requests: write`; a job asking for more fails every caller at startup, so a new permission is a breaking change. +13. **Python runs only as `/usr/bin/python3 -I -S -B /bin/`**: the standard library only, nothing from `PYTHON*` variables, the working directory, `site`, `sitecustomize` or `.pth` files, and no bytecode written. The root is `${RUNNER_TEMP}/trusted` in `authorize`, `prepare` and `publish`, and the root-owned `/opt/agent-review` in the review jobs. Entry points exit unless started with those flags; processes start from argument lists, with tool lookup and environment per trust zone (no process starts on the tainted host today; one that did would get an absolute program and a fixed environment); only `authorize` and `publish-comment` can reach the `gh` wrapper (which steps hold the token is decided by their `env:`); no Python file or Python shebang exists outside `lib/agent_review/` and `tests/` ([ADR 0004](adr/0004-python-runtime.md)). The structure test checks the call sites, the entry points, the imports and the tree ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py)). ## What remains risky -- **Prompt injection can steer the review's content**: a false approval, misleading findings, links. Mitigations: the comment is labelled advisory, never a status, names the reviewed commit and says the PR can steer it; mentions are neutralised and the size is capped. Cross-references such as `owner/repo#123` are not neutralised and can create backlinks in other repositories. The caller's rule files are reset to base (invariant 6), but files they in turn point at (`CONTRIBUTING.md`, the ADRs) are not, so injected text there is still read as context; it can only steer review content. Visible content (links, images, collapsed `
`) is not filtered. +- **A base that links an instruction file or directory to a path no reset pattern covers gets no review** (fail closed, invariant 6), because the agent would read the PR's version of the target: for example `AGENTS.md -> CONTRIBUTING.md`, `.github/copilot-instructions.md -> ../docs/copilot.md`, a rule file `docs/RULES.md -> guide.md`, or `.claude/skills -> ../tools/skills`. The run ends green with a "no review" warning, and the fetch log names the link, its target and the fix: add the target to the caller's `instruction_files` input (a file as `CONTRIBUTING.md`, a directory as `tools/skills/`), which resets it to the base version as well. Patterns apply at any depth and case-insensitively, so `CONTRIBUTING.md` resets every file of that name. Following links in the reset itself is a candidate for v0.2.0. +- **The PR's `.gitattributes` applies to the checkout.** A PR adding `* -diff` makes git write `Binary files differ` instead of the changes into the context's `diff.patch`, which steers what the agent sees of the diff (it can still read the files); this breaks no invariant. Attributes such as `eol=crlf` or `working-tree-encoding` also transform the base files the reset restores: a rule file then is not its base version, so the run stops (fail closed); another instruction file keeps the base text, transformed, never the PR's (tests in `test_run_review.py`). +- **Prompt injection can steer the review's content**: a false approval, misleading findings, links. Mitigations: the comment is labelled advisory, never a status, names the reviewed commit and says the PR can steer it; mentions are neutralised and the size is capped. Cross-references such as `owner/repo#123` are not neutralised and can create backlinks in other repositories. The caller's rule files are reset to base (invariant 6), but files they in turn point at (`CONTRIBUTING.md`, the ADRs) are not, so injected text there is still read as context; it can only steer review content. Visible content (links, images) is not filtered; raw HTML such as `
` cannot form. **Markdown-level hiding remains** (accepted for v0.1.0, candidates for v0.2.0): math such as `$\phantom{text}$` or `$\color{white}{text}$`, image alt text, link titles (`[a](u "text")`), link destinations in angle brackets (`[]()`), and code-fence info strings (the words after an opening ```` ``` ````) carry text that the comment does not show. +- **A steered review can carry command lines for other bots.** The workflow itself uses no comment commands, but the review text may contain lines such as `/approve`, `/lgtm` or `bors r+`, which the sanitiser passes unchanged. Whether a bot installed in the caller acts on them depends on that bot's own checks of the comment's author (here the workflow's bot account); check those before adopting. Breaking up a line-initial `/` is a candidate for v0.2.0. - **Budget burn, driven by the content of any reviewed PR.** The agent has a shell and can call AWF's listener directly, so the per-run bound is AWF's rate limiter, not the turn cap: at most **100 upstream requests per run** (`rateLimiting.requestsPerHour`; the run is shorter than an hour), paced at 30 per minute, each up to the model's context and output limits. AWF's `maxTurns` (80) stops a well-behaved harness but is not a hard cap: it counts only `POST`s to chat-completions, responses and messages paths, when the response ends. Other paths are forwarded with the real key and not counted (the key works for `/v1/completions`), and concurrent calls are all admitted before any is counted. AWF forwards every method and path under `/v1` (dot segments cannot leave `/v1`; encoded separators such as `%2f` are passed through), has no `max_tokens` clamp, and skips the model allowlist when the body has no string `model` or is not JSON. All of this was checked in a test fork against a fake upstream: 100 concurrent chat calls all reached it under a turn cap of 20, and 100 calls to uncounted paths reached it under the production limits before the hourly limit answered 429. Hence the dedicated key's budget (Required settings, item 2) is the real cap. - **A sandbox escape** would expose the key on the host. Beyond kernel and Docker bugs, this includes AWF itself: it runs as root on the host, and its API-proxy sidecar, which holds the key, parses requests from the sandbox; both are young code (the AWF probe worked around three of its bugs). Mitigations: the dedicated, low-budget key, quick to rotate; gVisor (`--container-runtime gvisor`) is planned once the harnesses are known to work with it. - **Egress**: the keyless fetch run reaches `github.com` and its subdomains, with git only. The agent's run reaches the API proxy, the inference host (without a key) and the runner's `sshd` through AWF's gateway, and runs for up to 25 minutes. @@ -194,7 +212,7 @@ Callers use `pull_request_target` because fork PRs get no secrets under `pull_re - **The self-test's "nothing can be spent or posted"** holds inside the reviewed file: stub, keyless job, forced dry run. For a fork or branch PR of this repository the file itself is the PR's, so the guarantee there is GitHub's fork rules plus the absence of secrets in this repository, not these checks. **Never store a key or any secret in this repository**: keyed tests run from a separate test caller. - **One keyed review per PR at a time**: the keyed job's concurrency group queues a second run; a newer queued run replaces an older queued one, which GitHub cancels. - **AWF updates are manual**: Dependabot ignores `github/gh-aw-firewall` ([`dependabot.yml`](../.github/dependabot.yml)), so its security fixes reach this workflow only when a maintainer bumps it; watch its releases and advisories. -- `@`, `&` and `]:` are neutralised everywhere, including code blocks, so a Python decorator copied from a review contains an invisible character, and character references show literally. +- `@`, `&`, `]:` and `<` before a letter, `/`, `!` or `?` are neutralised everywhere, including code blocks, so a Python decorator or `std::vector` copied from a review contains an invisible character, and character references show literally. ## Configuration notes @@ -204,11 +222,11 @@ Ceilings, changed by a reviewed PR here; callers can only lower the first four ( AWF's runtime model catalogue is disabled (`apiProxy.modelCatalogue.enabled: false`): otherwise its API-proxy sidecar makes ~7 GETs per run to `api.github.com` (`github/gh-aw-firewall`'s pricing snapshot). Those carry no data about the run and no token, but the AI-credit accounting they feed is unused here. Note that the inference host (added via `baseUrlEnv`) is marked _sensitive_ by AWF and is therefore excluded from Squid's `access.log` and `audit.jsonl`, so model traffic does not appear in the egress logs by design; it is visible only in the API-proxy's own `token-usage.jsonl`. -The `stub` harness makes no model call and posts a fixed review containing hostile content; it is for testing the pipeline only. +The `stub` harness makes no model call and posts a fixed review containing hostile content; it is for testing the pipeline only. It also prints the probe line of `bin/probe` (the Python runtime) on the host in `prepare` and inside the sandbox. ## Harness adapters -A harness is a directory `agent-review/harnesses//`; the name must also be added to the harness allowlist in [`bin/authorize`](../agent-review/bin/authorize), as keyed (it calls a model; `wire` `openai-chat`) or keyless (`wire` `none`; both review jobs check that the two agree), and callers may add it to their `workflow_dispatch` choice. The contract is in [`harnesses/README.md`](../agent-review/harnesses/README.md): +A harness is a directory `agent-review/harnesses//`; the name must also be added to the harness allowlist in [`lib/agent_review/authorize.py`](../agent-review/lib/agent_review/authorize.py) (`KEYED_HARNESSES` or `KEYLESS_HARNESSES`), as keyed (it calls a model; `wire` `openai-chat`) or keyless (`wire` `none`; both review jobs check that the two agree), and callers may add it to their `workflow_dispatch` choice. The contract is in [`harnesses/README.md`](../agent-review/harnesses/README.md): - `install.sh ` runs in `prepare` and installs an exact version, integrity-checked, into ``, writing the version to `/VERSION`, without executing any harness code. The prefix is unpacked to `/opt/agent-review/harness/` and must run from there without network access. - `run.sh` runs inside the sandbox, from the PR checkout, with `PROMPT_FILE`, `REPO_DIR`, `OUT_DIR`, `CONTEXT_DIR`, `MODEL`, `HARNESS_PREFIX` and `PR_NUMBER` set, plus AWF's `AWF_API_PROXY_OPENAI_URL`. It checks the harness version, keeps its configuration in a scratch home under `$TMPDIR` (in the workspace), disables updates, telemetry and sharing, and writes `$OUT_DIR/review.md`. Exit codes: 0 review written, 2 no review, anything else a failure; it must return 2, not 0, when the harness exits 0 without a real answer. @@ -221,11 +239,12 @@ The [adapters README](../agent-review/harnesses/README.md) compares the harnesse This repository's [`self-test.yml`](../.github/workflows/self-test.yml) runs on every pull request, on `main`, weekly and on demand: -- pre-commit (actionlint, shellcheck, file checks) and [zizmor](https://docs.zizmor.sh/) on the workflows; +- pre-commit (actionlint, shellcheck, ruff, mypy on `agent-review/lib/`, file checks) and [zizmor](https://docs.zizmor.sh/) on the workflows; - the script tests: `agent-review/tests/test-collect-result.sh`, `test-publish-comment.sh`, `test-instruction-coverage.sh` (offline) and `test-run-review.sh` (fetches real commits from github.com, no AWF; includes the reset post-condition); -- the unit tests of `authorize` ([`test-authorize.sh`](../agent-review/tests/test-authorize.sh), offline: every input, the event and harness matrix, the writer check) and the [workflow structure test](../agent-review/tests/test-workflow-structure.py); +- the unit tests of `authorize` ([`test-authorize.sh`](../agent-review/tests/test-authorize.sh), offline: every input, the event and harness matrix, the writer check) and the [workflow structure test](../agent-review/tests/test-workflow-structure.py), which also enforces the Python runtime rules of invariant 13 ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py) lists every check). The script suites are the black-box specification of each entry point's command-line contract (arguments, exit codes, outputs, notices); they run each `bin/` entry point through `run_entry` in [`tests/lib.sh`](../agent-review/tests/lib.sh), with the production Python command line; +- the `python` job: the pytest suites in [`tests/python/`](../agent-review/tests/python/) (the package's helpers; the entry points' own cases, such as `collect-result`'s simulated swaps between check and open; the review sanitiser against an independent oracle on every code point, and property tests over random and adversarial reviews: no marker, no live mention or reference, no `Cf` or listed invisible character except those the sanitiser inserts, where it inserts them; `run-review`'s reset, prompt rendering and review collection, also through its entry point on crafted pull requests served from a local repository; each Python entry point run with the production command line from a directory holding a planted `json.py`, `agent_review/` and `sitecustomize.py`, with hostile `PYTHONPATH`, `PYTHONSTARTUP` and `PYTHONHOME`; the flag guard; the structure checks on crafted inputs) and mypy, with the test tools of the hash-pinned [`requirements.txt`](../agent-review/tests/requirements.txt). Locally: `python3 -B -m pytest` and `python3 -m mypy` from the repository root; - the whole pipeline through a **local** call (`uses: ./.github/workflows/agent-review.yml`), so the files fetched at `job.workflow_sha` are the commit under test, with the `stub` harness (keyless job), no key and a forced dry run, against a fixed public PR of another repository (`test_repository`); the dry-run comment is in the run summary; -- the `check` job: the keyed job skipped and the keyless one run, nothing posted, the sandbox's allowed domains, the clamped caps, no key in AWF, the reset post-condition, and no deployment for the commit. +- the `check` job: the keyed job skipped and the keyless one run, nothing posted, the sandbox's allowed domains, the clamped caps, no key in AWF, the reset post-condition, no deployment for the commit, `gh` found as `/usr/bin/gh` under the publish steps' fixed `PATH: /usr/bin:/bin` (the self-test never posts), and the probe's line from the host (`prepare`) and from inside the sandbox: Python 3.12, `/usr/bin/python3`, the isolation flags, no `site`, only the standard library and the trusted `lib/` on `sys.path`. The self-test path (`test_repository`, and the `push` and `schedule` events) is accepted only with the `stub` harness when `job.workflow_repository` equals the calling repository: this repository, or a fork or copy calling its own file, which is harmless (stub, no key, dry run). It skips the writer check, since nothing can be spent or posted; the intent is that Dependabot's and outside contributors' PRs can run it too (not yet observed: their read-only token might still fail the permission ceiling at startup). @@ -245,15 +264,16 @@ Before tagging (`v0.1.0` and every later release): 1. The self-test is green on the commit to be tagged, which is on `main` (merged through a reviewed PR). 2. Repository settings are in place: tag ruleset for `v*` (restricted creation, no update, no deletion), immutable releases, the self-test jobs as required status checks on `main`, no repository or organization secret available to this repository. -3. Cross-repository tests from a **separate test caller repository** pinned to the release candidate's SHA on `main` (its own `agent-review` environment, default branch only, with a dedicated low-budget key; never a key here): +3. Cross-repository tests from a **separate test caller repository** pinned to the release candidate's SHA on `main` (its own `agent-review` environment, default branch only, admins not exempt, with a dedicated low-budget key; never a key here; an Actions event policy for its workflow file allowing `pull_request_target`, `workflow_dispatch` and `pull_request`, without which `pull_request_target` is blocked from 2 December 2026; no forced dry run left in its workflow file): 1. `workflow_dispatch` dry run with `stub` from the default branch: the notice shows `workflow GridTools/ci-workflows@; caller @` with distinct values, the keyless job runs, no deployment is recorded. 2. `pull_request` caller test mode with `stub`: dry run forced, the PR-content notice; with `opencode`: rejected in `authorize`. - 3. The label path on a fixture PR (`pull_request_target`, `labeled`), with a writer: a real post, updated in place on a second run. + 3. The label path on a fixture PR (`pull_request_target`, `labeled`), with a writer: a real post through `/usr/bin/gh` under the publish steps' fixed `PATH: /usr/bin:/bin`, updated in place on a second run. 4. A non-writer adding the label (or the PR's author without write) is denied with a notice. 5. A keyed dispatch from a branch other than the default: denied by the environment rule before getting a runner. 6. One keyed dry run per harness (`opencode`, `pi`) with the dedicated key: a rendered review, the token-usage table, `OpenAI=true` only in the review run. 7. A shared repository secret named like the mapped one makes `authorize` fail (then delete it). 8. A pin to a commit that exists only in a fork of this repository: record what the notice prints, and that the caller-side check in [Pinning and updating](#pinning-and-updating) rejects it. 9. A tag-pinned call, re-run after the tag moved (in a scratch repository, never with release tags here): record which commit the re-run uses. + 10. A PR from a fork, by an account without write access, labelled by a writer (`pull_request_target`): the keyed review runs on the fork's head inside the sandbox, the instruction-file reset and its post-conditions hold, and the comment is posted; nothing from the fork runs on the host. 4. Release notes list breaking changes and the evidence (run URLs) of step 3. 5. Callers update their pin to the tag's SHA and check it ([Pinning and updating](#pinning-and-updating)). diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..d357259 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,39 @@ +# Development tooling only (ruff, mypy, pytest). This repository ships no +# Python package: the agent review's code in agent-review/lib/ runs with the +# runner's /usr/bin/python3 and the standard library only +# (docs/adr/0004-python-runtime.md). + +[tool.ruff] +target-version = "py312" +line-length = 120 + +[tool.ruff.lint] +select = ["E", "W", "F", "I", "B", "UP", "S", "RUF", "SIM", "PL"] +ignore = [ + "PLR0911", # too many return statements + "PLR0912", # too many branches + "PLR0913", # too many arguments + "PLR0915", # too many statements + "PLR2004", # magic values in comparisons +] + +[tool.ruff.lint.per-file-ignores] +# Tests run tools as subprocesses and use assert; the structure checks run git. +"agent-review/tests/**" = ["S101", "S603", "S607", "S108", "PLC0415"] + +[tool.ruff.lint.isort] +known-first-party = ["agent_review", "workflow_structure"] + +[tool.mypy] +python_version = "3.12" +strict = true +warn_unreachable = true +mypy_path = ["agent-review/lib", "agent-review/tests"] +files = ["agent-review/lib", "agent-review/tests/python", "agent-review/tests/workflow_structure.py"] + +[tool.pytest.ini_options] +testpaths = ["agent-review/tests/python"] +pythonpath = ["agent-review/lib", "agent-review/tests"] +# No .pytest_cache in the tree; run with 'python -B' so that no __pycache__ +# is written either (the structure test forbids both in agent-review/). +addopts = ["--import-mode=importlib", "-p", "no:cacheprovider", "--strict-markers", "-ra"]