Repository navigation
feat(github): add a plain GitHub script split around the session - #269
eric-factory wants to merge 14 commits into
Conversation
🟡 Changes recommendedThe split-user runner has verified privileged-input, authorization, state-isolation and validation failure paths, alongside redundant persisted state. All 36 existing focused tests passed after installing the locked dependencies; the initial run failed with dependencies missing. Validation used targeted code traces and read-only probes, with no new tests added. 🔒 Security review: 3 findings (High). 15 open findings ·
What changedAdds a three-phase GitHub review runner for execution outside Actions, a synthetic PR-event entrypoint, and an automatic-review defaults layer below repository configuration and explicit inputs.
flowchart LR
B[Privileged preparation] --> S[Session-user candidate review]
S --> V[Session-user validation]
V --> A[Privileged posting]
B --> T[Trusted lifecycle state]
T --> A
A --> G[GitHub review and check]
Fix with an agentReply to a finding with a question, or comment |
eric-factory
left a comment
There was a problem hiding this comment.
Deep review: the write-token containment here is careful and well tested, with an env -i validator, root-owned state, a GIT_DIR-guarded after, 15 mutation-checked safeguards and a live run as root. All nine comments are non-blocking or nits: a check that stays open if before is killed, a prior-findings path the prompts never resolve, two places where the write token is more exposed than it needs to be, vague failure messages after the check opens, three test improvements, and one PR-description correction.
There was a problem hiding this comment.
Droid found 15 issues (2 P1, 13 P2) in 9e8c0ce. Summary
github/run-review.sh runs action.yml's automatic code review outside GitHub Actions, in two parts around a caller's review session: `before` opens the Droid Review check, marks the PR as being reviewed, and writes the PR context and candidates prompt; `after` runs the validator pass without GitHub credentials, posts the review, and closes the check. github-pr-event.ts builds the pull_request event the entrypoints read, from the GitHub API. Closes AUT-3072 Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Refs AUT-3072 Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
A `git clone --depth 1` fetches only the default branch, so gh pr checkout fetched the PR branch but could not track it. Also state the token permissions the review needs: pull requests and checks write, contents read. Refs AUT-3072 Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
… nothing to review The validator ran as a child of the part that held the write token, so it could read the token from its parent's environment. It now runs in its own part, `validate`, which takes the read-only token and gives the validator an allowlisted environment like action.yml's validator step. `after` takes the write token, posts the review and closes the check, or closes it with the error `validate` left. `before` exits 78 when the PR moved past PR_HEAD_SHA or the review settings skip the event, so the caller can skip the session. Refs AUT-3072 Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
github-post-review runs `git diff` for incremental reviews. In after, that ran in the checkout the session could change, where planted git config can run commands while the write token is in the environment. after now runs with GIT_DIR=/dev/null, so git opens no repository and posting reads the diff through GitHub's API, as it already does when git fails. Also test that droid-action's authenticated fetches leave no token in ~/.git-credentials on a computer with credential.helper=store. Refs AUT-3072 Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
When SESSION_USER names the user the session and validate run as, before and after run as root and keep the session out of them: - before checks that droid-action and RUNNER_TEMP can be changed by root alone, recreates the prompts directory instead of writing into one a previous session left, copies the droids into the session user's HOME as that user, and hands the clone and prompts over with chown once its git work is done. - before and after keep their state, the review lifecycle, their own copy of the diff and the post results in $RUNNER_TEMP/github-review, which only they write. - after runs from its private directory with no git, reads what the session and validate wrote as the session user, with a cleared environment, and closes the check when the prepared head differs from PR_HEAD_SHA instead of leaving it open. - validate refuses to run as another user than SESSION_USER. - Entrypoints keep their temporary files in the part's private directory, so prepare's frozen publisher bundles no longer pile up in /tmp. Removed, as nothing needs them: the droid CLI install fallback in validate (droid must be on its PATH), bun install in validate and after, the unused DETAILED_PERMISSION_MESSAGES variable, and validate's reset of an earlier error file. after no longer requires validate's error file to be a regular file: reading it as the session user covers that when the users differ, and a session running as the same user could write the same text directly. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
run-review.sh ran prepare with AUTOMATIC_REVIEW=true. Action inputs win over .factory/review.yaml, so an automation's automaticReview: false and a review.yaml auto_review.enabled: false were both ignored, and a security-only review could not happen. prepare now takes the caller's AUTOMATIC_REVIEW when it is set, then the base branch's review.yaml, then true. The script sets DEFAULT_AUTOMATIC_REVIEW=true, which loadReviewUxConfigFromBase applies below the file, as the GitLab loader already does for its default. Actions never sets it, so automatic review stays opt-in there. No other review setting is forced: AUTOMATIC_SECURITY_REVIEW and the rest pass through from the caller. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
- after closes the check of a before that was stopped, for example at the caller's time limit, before it closed the check or handed it over. before now keeps its outputs in $RUNNER_TEMP/github-review/before, which its exit deletes; after closes the check they name and deletes them. - Both prompts get an absolute prior-findings path, and the validator gets RUNNER_TEMP, as in action.yml. - bun is installed from its GitHub release after checking a pinned SHA-256, instead of running bun.sh's installer as root with the write token in its environment. - prepare gets the write token through its environment instead of env(1)'s arguments, which any user can read in /proc. - before's failures after the check opens name the failed step on the check instead of the CI default message. - Tests cover a review.yaml without automatic-review keys and git config planted above after's private directory. The fake server and git test helpers move to test/helpers, and the Bitbucket and Azure DevOps helper files re-export them. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
… succeeded - review-artifacts.ts and pr-checkout.ts run git and gh with argument lists instead of shell strings, so shell syntax in a base branch name runs nothing. - after posts only with VALIDATE_RESULT=succeeded. Unset or any other value closes the check as failed without posting. - before takes no @droid commands from the PR description (AUTOMATIC_REVIEW_ONLY), and requires GITHUB_ACTOR, the login that sent the event, instead of falling back to the PR author. - RUNNER_TEMP is required and must be absolute: every part of one run shares it, and no other run may. - after reads at most 16 MiB of each file the session or validate wrote, for at most 30 seconds, and drops a larger file. - validate deletes an earlier attempt's error and results before it runs, and reports a missing FACTORY_API_KEY on the check. - The validator runs without a tracking comment when review_summary is off, as preparation then makes none for a new PR. This also fixes the Actions validator step. - loadReviewUxConfigFromBase takes only the automatic_review default. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
… no git after runs no git, and GitHub's compare API is three-dot, so once a PR was rebased posting could not get the previous reviewed head's diff. It then dropped the fixed decisions preparation had made eligible, and fixed findings stayed open. prepare now keeps that diff in REVIEW_PRIOR_DIFF_PATH, which run-review.sh points into before's own directory, and posting uses it for exactly that base and head. Actions sets no REVIEW_PRIOR_DIFF_PATH, so nothing changes there. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
- prepare creates no check for a run it already knows it will skip, such as an automatic trigger that review_auto_triggers leaves out. Completed as neutral, that check became the head's latest Droid Review and hid an earlier failing review from branch protection. Actions did the same when a workflow's types listed labeled. - A run that skips after creating its check (no new changes since the last review, or superseded) completes it as failure while the findings it skipped to still block, instead of always as neutral. - run-review.sh's before re-reads the PR for up to a minute while GitHub's API still reports a head that has not reached PR_HEAD_SHA, and skips at once only when the head moved past it. A synchronize delivery read during that lag used to leave its head unreviewed. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
…none A skipped automatic run again creates the neutral check on a head that has no Droid Review check, as before 197d3ee, so repos that require the check are not blocked while reviews are paused or at the auto-run limit. It still creates none where the head already has a Droid Review check, completed or in progress, or when the head's checks cannot be listed. A check made before its run skipped completes as failure only over another Droid Review check on the head while the findings it skipped to block, and as neutral otherwise. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
github/run-review.sh now takes GITHUB_EVENT_NAME and GITHUB_EVENT_PATH as GitHub Actions sets them, and prepare.ts decides what to do with the event, as in action.yml. before keeps a copy of the payload and its name in $RUNNER_TEMP/github-review, which validate and after read. The made-up pull_request event (github-pr-event.ts), PR_NUMBER, PR_HEAD_SHA, PR_ACTION, the 60-second wait for a pushed head and the head checks are gone; the PR number comes from prepare. Commands run as in action.yml. help, pause, resume and resolve finish in before, which exits 78. @droid fix and questions in a Droid finding's thread get a session and no validator pass; after publishes the result with github-post-command.ts, from a copy read as the session user. With SESSION_USER set, before hands the command's droid-command-* directory over with the clone and prompts. FACTORY_AUTOMATION, which the script sets, makes @droid fill and @droid security --full reply that they are not supported on Factory-run automations yet, before anything else is written: their model runs write to GitHub, and the session never holds a write token. It replaces AUTOMATIC_REVIEW_ONLY. DEFAULT_AUTOMATIC_REVIEW is removed: automatic review follows the caller's AUTOMATIC_REVIEW and the base branch's .factory/review.yaml, as in action.yml. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
The publisher commits fixes through GitHub's git data API, so after's token needs contents write for @droid fix, as droid-action mints for fix runs in Actions. Comment only. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
964369c to
b8eb9c5
Compare
Factory Code Review: Web · Desktop
Summary
Factory is moving GitHub automations from CI workflow files to first-party GitHub webhook triggers that run on Factory computers. This adds the script those runs use:
github/run-review.shruns droid-action on one GitHub event outside GitHub Actions, the wayaction.ymldoes, split around an agent session that Factory runs in between. On a Factory computer,beforeandafterrun as root, while the session andvalidaterun as the session user (factory-user), so the agent never reaches the GitHub write token.Changed in 413d0ff: the script takes GitHub's real event (
GITHUB_EVENT_NAME,GITHUB_EVENT_PATH) instead of a pull request event it built fromPR_NUMBER,PR_HEAD_SHAandPR_ACTION, and droid-action decides what to do with each event exactly as in Actions.@droidcommands now work:fixand questions in a Droid finding's thread get a session andafterpublishes them;help,pause,resumeandresolvefinish inbefore;fillandsecurity --fullreply that they are not supported on Factory-run automations yet.The script reuses the entrypoints
action.ymlruns (prepare.ts,github-review-lifecycle.ts,prepare-validator.ts,base-action/src/index.ts,github-post-review.ts,github-post-command.ts), with the same environmentaction.ymlgives each step.action.ymlis unchanged. Four fixes in shared code also change GitHub Actions runs; they are listed under "Shared code".Closes AUT-3072
Changes
The script
github/run-review.sh(new): the three parts. Its header is the caller's contract.GITHUB_REPOSITORY,GITHUB_TOKEN(write token forbeforeandafter, with contents write inafterfor@droid fix; read-only forvalidate),GITHUB_RUN_ID, andRUNNER_TEMP, an absolute path to a directory only this run uses, the same in every part.beforealso needsGITHUB_EVENT_NAMEandGITHUB_EVENT_PATH, as GitHub Actions sets them, andGITHUB_ACTOR, the login that sent the event, whose permissions prepare checks.validateneedsFACTORY_API_KEYfor a review.afterposts a review only withVALIDATE_RESULT=succeeded: unset or any other value closes the check as failed without posting. Optional:SESSION_USER,GITHUB_RUN_ATTEMPT, and action.yml's inputs as the environment variables its prepare step sets (AUTOMATIC_REVIEW,REVIEW_DEPTH,ALLOWED_BOTS...).beforecopies the payload and saves the event name in$RUNNER_TEMP/github-review, which only root writes.validateandafterread that copy, so a changed event file or a different caller variable cannot change what they parse. The PR number comes from prepare's outputs.beforeexits 78 when prepare skipped the event or finished it itself: no@droidtrigger, a draft or disabled automatic trigger, no new changes,help,pause,resume,resolve, and thefillandsecurity --fullreplies. The caller then skips the session, andvalidateandafterdo nothing. Any other failure closes the check as failed oncebeforehas opened it.@droid fixand thread questions,validatedoes nothing (Actions has no validator pass for commands) andafterignoresVALIDATE_RESULT.afterreads the session's result as the session user, at most 16 MiB and 30 seconds (the publisher refuses anything over 4 MiB), and passes that copy togithub-post-command.ts. Without a result, the publisher replies "Droid could not finish this request. Please retry the command."aftereven whenbeforefailed or was stopped.beforekeeps its outputs in$RUNNER_TEMP/github-review/beforeuntil it finishes, soaftercan close the check a stoppedbeforeopened ("Droid was stopped while preparing the review of ; nothing was posted.").workflow_runwithCI_STEWARD=true) reaches it.src/github/context.ts,src/tag/index.ts,src/tag/commands/conversation.ts:FACTORY_AUTOMATION=true, which only the script sets, makes@droid filland@droid security --fullreply "<command>is not supported on Factory-run automations yet." right after the actor checks, before any tracking comment or other write. Their model runs write to GitHub with tools that need the write token, which the session never gets. Actions never sets the variable.src/github/operations/review-lifecycle.ts,src/github/data/review-artifacts.ts,src/entrypoints/github-post-review.ts: prepare keeps the previous reviewed head's diff, which it computes with git, inREVIEW_PRIOR_DIFF_PATH, and posting uses it for exactly that base and head.afterruns no git, and GitHub's compare API is three-dot, so without it a rebased PR's confirmed fixes stayed open. Actions sets noREVIEW_PRIOR_DIFF_PATH.Removed since the last review
src/entrypoints/github-pr-event.tsand its test: the made-uppull_requestevent, its 60-second wait for GitHub's API to report a pushed head, and the head checks inbeforeandafter. As in Actions, prepare reads the PR's current head itself.AUTOMATIC_REVIEW_ONLY(ignored@droidcommands) andDEFAULT_AUTOMATIC_REVIEW(automatic review on unless turned off), with their tests. Automatic review follows the caller'sAUTOMATIC_REVIEWand the base branch's.factory/review.yaml, as in Actions. The shared fake GitHub server moved back intotest/bitbucket/, its only remaining user.Shared code (also changes GitHub Actions runs)
src/github/data/review-artifacts.ts,src/github/data/pr-checkout.ts: git and gh run with argument lists (execFileSync), never a shell string. A base branch name can hold shell syntax, which ran commands in prepare.src/entrypoints/prepare-validator.ts: the validator runs without a tracking comment whenreview_summaryis off. Preparation makes no summary comment for a new PR then, and the validator step failed.src/github/operations/review-lifecycle.ts,src/github/operations/review-checks.ts: a run that prepare skips (draft, disabled trigger, paused, auto-run limit, no new changes) creates no check when the head already has a Droid Review check, completed or in progress. Its neutral check used to become the head's latest and hide an earlier failing review from branch protection, for example after alabeledevent in a workflow whosetypeslist it. On a head with no Droid Review check it still creates the neutral check, as before, and when the head's checks cannot be listed it creates none. A check made before its run skipped (no new changes found in the diff, or superseded) completes as failure over another Droid Review check while the findings it skipped to still block, and as neutral otherwise.test/modes/tag/security-review-command.test.tsmockedchild_processwithmock.module, which leaked into other test files; it now spies onexecFileSync.Tests
test/github/run-review.test.tsdrives every part with stub entrypoints, plusrunuserandchownstubs for the split-user path. It covers the four PR events (pull_request,issue_comment,pull_request_review_comment,pull_request_review) through all three parts frombefore's copy, the skip outcomes, and command runs: no validator, a copied result, no result, a failed publish, and the hand-over of the command's directory.test/review/conversation.test.ts: with the flag,@droid filland@droid security --fullget only the reply and no tracking comment.test/github/context.test.ts:FACTORY_AUTOMATIONsets the flag.test/integration/fill-flow.test.ts, unchanged, still runs fill without it.test/github/git-credentials.test.tsruns droid-action's real authenticated fetch against a local git server, including a base branch namedbase;touch${IFS}p1;$(touch${IFS}p2)`touch${IFS}p3`|touch${IFS}p4&, which now diffs normally and creates none of those files.test/github/review-lifecycle.test.ts: a failing check stays the head's latest after a skippedlabeledtrigger; a skip on a head with no check gets the neutral check; a rebased fix is resolved from the kept prior diff only for its exact range.Keeping the write token away from the agent
Only
beforeandafterhold the write token. The session andvalidateget a read-only token.beforeleaves no copy of the token. Entrypoint outputs (some hold the token) live in a private directory that is deleted on exit, and@actions/core's::add-mask::lines are dropped from the log. prepare gets the token through its environment, never through a command line, which any user can read in/proc. droid-action's git commands reset credential helpers before adding gh's, so nothing lands in.git/configor in~/.git-credentials(Factory computers set a globalcredential.helper=store).droid execruns in its own part, with an allowlisted environment likeaction.yml's validator step. A child process can read its parent's environment through/proc, so no parent of the validator may hold the write token.SESSION_USERset (the Factory computer setup), root runs only code the session cannot change:RUNNER_TEMPcan be changed by root alone, and so can every directory above them (sticky ones such as/tmpaside).--config=/dev/null --env-file=/dev/null, so abunfig.tomlor.envplanted in the clone is ignored.SESSION_USERset, root never writes through or reads from anything the session controls:beforerecreates the prompts directory instead of reusing one an earlier session left, and copies the security-reviewer droid into the session user's HOME as that user.droid-command-*directory over withchown. The event copy and state stay in root'sgithub-reviewdirectory.afterreadsreview_candidates.json,review_validated.json, validate's error and a command's result as the session user, throughrunuserwith a cleared environment, at most 16 MiB and 30 seconds each, and works on copies. A FIFO or a link to a device can neither stall it nor fill the disk, and a link to a root-only file is read with the session user's rights.afternever runs git: it usesGIT_DIR=/dev/nulland a private working directory, so git config planted in the clone or above it cannot run commands.validaterefuses to run as anyone other thanSESSION_USER, and clears an earlier attempt's error and results before it starts.SESSION_USERevery part runs as one user, and this is not a sandbox: the session could change the codeafterruns.Decisions made without a reviewer
afteras running the validator and then posting. A single process cannot do that without the validator being able to read the write token, so the validator moved intovalidate.aftertakes validate's outcome from the caller (VALIDATE_RESULT) and fails closed when it is missing: a stale or session-writtenreview_validated.jsonmust never be posted.validateandafterreadbefore's copy of the event and its name, not the caller's variables, so all three parts work on the same event.RUNNER_TEMPandGITHUB_ACTORare required. A shared default directory let two runs overwrite each other, and the PR author is not the sender whose permissions the event should be checked against.SESSION_USERis opt-in and defaults to the user running the part, so a single-user run behaves as before.checks: write,pull_requests: write,contents: readandmetadata: read, pluscontents: writeinafter:@droid fixcommits through GitHub's git data API, and droid-action mints the same for fix runs in Actions.validateruns thedroidon its PATH and does not install one. Factory computers ship droid.BUN_VERSION.Known gaps
pushandcheck_runevents: droid-action throws "Unsupported event type", as in Actions, sobeforefails with that message without writing to GitHub.github.com/<repo>/actions/runs/<GITHUB_RUN_ID>, which does not exist outside Actions. Pointing them at the Factory run needs a URL override in the shared lifecycle code, which is left to the code-review port.beforerungit fetch --unshallowfor the merge base, as in CI. On very large repositories that is slow.validateruns as the session user, so the session can reach whatvalidateholds (FACTORY_API_KEYand the read-only token).validateholds nothing the session may not.Validation
Local, at 413d0ff
contents: writerequirement to the script header's token description. CI on 964369c: test, typecheck, format and code-walkthrough pass.bun test: 2655 pass, 0 fail (166 files).bun run typecheckandbun run format:checkpass, andshellcheck github/run-review.shis clean. CI on 413d0ff: test, typecheck, format and code-walkthrough pass.FACTORY_AUTOMATIONnot passed or read from another variable; skip outcomes ignored; unknown run kinds proceeding;PR_NUMBERnot saved; the command directory not handed over; the result read from the session's own path or as root; a missing result reported as success; commands falling through to review posting or opening a check;validaterunning for commands; the refusal removed, applied without the flag, applied tofillonly, or with the wrong text. The earlier rounds' checks (session-file limits, theVALIDATE_RESULTgate, the kept prior diff, the skipped-run checks, the 15 split-user safeguards) still pass; the head-wait checks went with the wait.Live, as the computer runs it, at 413d0ff
droid-action was copied as root into
/opt. Each run got a root-ownedRUNNER_TEMPunder/var/tmp, a fresh--depth 1clone made as root, and its event payload, built from GitHub's API in webhook shape, as a root-owned 0644 file.beforeandafterran underenv -i HOME=/root PATH=/usr/sbin:/usr/bin:/sbin:/binwithSESSION_USER=factory-userandAUTOMATIC_REVIEW=true, the token passed through the environment. The session (a realdroid execfollowing the prompt, with no GitHub token) andvalidateran as factory-user. The scratch PR, Factory-AI/eric-test-1#62, added a script with an unquotedrm -rf, and is closed.pull_requestopenedbeforeinstalled bun 1.2.11 through the SHA-256 check and prepared the review in 18 s. The session wrote 5 candidates,validateexited 0, andafterposted the review "Droid found 4 issues (1 P0, 1 P1, 2 P2)" and closed the check.issue_comment@droid fillbeforeexited 78 after replying "@droid fillis not supported on Factory-run automations yet." No tracking comment and no reaction.validateandafterhad nothing to do.issue_comment@droid security --fullpull_request_review_comment, a question in the P0 finding's threadbeforeprepared adroid-questionrun and handed itsdroid-command-*directory to factory-user. The session wrote its answer in 16 s,validatereported no validator pass, andafterposted the answer in that thread.pull_request_review_comment,@droid fixin the P1 finding's threadaftercommitted 1ffffd3 to the head branch, replied in the thread and resolved it. Its token had contents write, whichafterneeds for fix runs.issue_comment@droid reviewon the new headafterupdated the summary and closed the check "Found 3 issues (1 P0, 2 P2)".pull_request_review@droid helpbeforeexited 78 after posting the commands table.pull_requestsynchronize, repeated on the reviewed headbeforeexited 78 (no new changes), and the head kept exactly one Droid Review check.FACTORY_API_KEYappear in no part's log and in no file under the run directories, and the clones' git config holds no credential.beforeandafterused the computer's own GitHub token, andvalidategot the same token instead of a read-only one, because no narrowed token can be minted on this machine.