Compare commits

...
2 Commits
Author SHA1 Message Date
eb56b6666f Log text as plain text, and post buffered comments in the run step (#2122)
Text that the action logs, such as a prompt, a comment or a file name, could
contain workflow commands. Console output now shows them as plain text, and
git's output goes through console. The prompt input is no longer logged.

Buffered inline comments are posted at the end of the run step instead of in
a step of their own, so they aren't posted when a run is cancelled or times
out. The issue triage recipe passes only the issue's number.

Co-authored-by: Claude <[email protected]>
2026-11-23 15:51:21 -08:00
Mohamed HegazyandGitHub 4a461cbbb7 Skip pull requests from forks by default (#2114)
Breaking change: allow_fork_prs now defaults to false, so runs for pull requests and workflow runs from forks are skipped unless the workflow sets allow_fork_prs: "true".

Fork runs that hold credentials still go through the actor checks first, so a run those checks refuse fails instead of being skipped.
2026-11-23 15:03:36 -08:00
26 changed files with 564 additions and 101 deletions
+2 -20
View File
@@ -45,9 +45,9 @@ inputs:
required: false
default: ""
allow_fork_prs:
description: "Whether to run on pull requests from forks, and on workflow_run events for a fork's run. With any value other than 'true', the action skips them, whoever opened them, before it checks anything out. See docs/security.md."
description: "Set to 'true' to run on pull requests from forks, and on workflow_run events for a fork's run. By default, and with any other value, the action skips them, whoever opened them, before it checks anything out. Where the event has credentials, a run that the actor checks refuse fails instead. See docs/security.md."
required: false
default: "true"
default: "false"
restrict_untrusted_prs:
description: "On pull requests whose author does not have write access, deny commands that commonly run code from the checkout (package managers, test runners, interpreters, shells), even if claude_args allows them. Set to 'false' to turn this off. See docs/security.md."
required: false
@@ -447,24 +447,6 @@ runs:
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/cleanup-ssh-signing.ts
- name: Post buffered inline comments
if: always() && inputs.classify_inline_comments != 'false'
shell: bash
env:
BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0"
GITHUB_TOKEN: ${{ steps.run.outputs.github_token || inputs.github_token || github.token }}
REPO_OWNER: ${{ github.event.repository.owner.login }}
REPO_NAME: ${{ github.event.repository.name }}
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
run: |
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
"$BUN_BIN" --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/post-buffered-inline-comments.ts
- name: Revoke app token
if: always() && inputs.github_token == '' && steps.run.outputs.github_token != '' && steps.run.outputs.skipped_due_to_workflow_validation_mismatch != 'true'
shell: bash
+3 -2
View File
@@ -1,3 +1,4 @@
import * as core from "@actions/core";
import { spawnSync } from "child_process";
import { readdirSync, readFileSync } from "fs";
@@ -109,8 +110,8 @@ export function stopDescendants(): void {
signal(known, "SIGKILL");
const left = [...known].filter((pid) => cannotSignal.has(pid));
if (left.length > 0) {
console.log(
`::warning::Processes of another user could not be stopped: ${left.join(", ")}`,
core.warning(
`Processes of another user could not be stopped: ${left.join(", ")}`,
);
}
}
+2
View File
@@ -7,6 +7,7 @@ import { setupClaudeCodeSettings } from "./setup-claude-code-settings";
import { validateEnvironmentVariables } from "./validate-env";
import { installPlugins } from "./install-plugins";
import { onCancel } from "./cancel";
import { escapeConsoleOutput } from "./log";
import { setExecutionFileOutputIfPresent } from "./execution-file";
import { setupWorkloadIdentity } from "./workload-identity";
import type { WorkloadIdentityHandle } from "./workload-identity";
@@ -95,5 +96,6 @@ async function run() {
}
if (import.meta.main) {
escapeConsoleOutput();
run();
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Changes what the runner would take for a workflow command, so that it's only shown.
* The runner reads `::name::` at the start of a line and `##[name]` anywhere in it.
*/
export function escapeWorkflowCommands(text: string): string {
return (
text
.replaceAll("##[", "##[\\")
// The runner skips spaces first. This skips all that isn't visible ASCII.
.replace(/^([^\x21-\x7e\r\n]*)::/gm, "$1\\::")
);
}
/**
* Keeps text that is logged, such as a comment or a file name, from running workflow
* commands. To run one, use @actions/core, which doesn't go through console.
*/
export function escapeConsoleOutput(): void {
for (const method of ["log", "info", "warn", "error", "debug"] as const) {
const write = console[method].bind(console);
console[method] = (...args: unknown[]) => {
const text = args.map((arg) =>
typeof arg === "string" ? arg : Bun.inspect(arg, { depth: 2 }),
);
write(escapeWorkflowCommands(text.join(" ")));
};
}
}
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bun
import { spawnSync } from "node:child_process";
import { describe, expect, test } from "bun:test";
import { escapeWorkflowCommands } from "../src/log";
describe("escapeWorkflowCommands", () => {
test.each([
["::warning::x", "\\::warning::x"],
["a\n::warning::x", "a\n\\::warning::x"],
["a\r::warning::x", "a\r\\::warning::x"],
["a\r\n \t::warning::x", "a\r\n \t\\::warning::x"],
[" \u0085 ::warning::x", " \u0085 \\::warning::x"],
["::warning file=a::x", "\\::warning file=a::x"],
["a ##[warning]x", "a ##[\\warning]x"],
["##[##[warning]x", "##[\\##[\\warning]x"],
["####[warning]x", "####[\\warning]x"],
])("escapes %j", (text, escaped) => {
expect(escapeWorkflowCommands(text)).toBe(escaped);
});
test.each(["std::string::npos", "## [x]", "a: b", "- see ::x", ""])(
"keeps %j",
(text) => {
expect(escapeWorkflowCommands(text)).toBe(text);
},
);
});
test("escapeConsoleOutput escapes what console writes, and not @actions/core", () => {
const { stdout, stderr } = spawnSync(
"bun",
[
"-e",
`import { escapeConsoleOutput } from "./src/log";
import * as core from "@actions/core";
escapeConsoleOutput();
console.log("a\\n::warning::b", { c: "##[warning]d" }, "100%s");
console.error("failed:", new Error("\\n::warning::e"));
try { await Bun.$\`git no-such-command\`.quiet(); } catch (e) { console.error(e); }
core.warning("f\\n::warning::g");`,
],
{ cwd: new URL("..", import.meta.url).pathname, encoding: "utf8" },
);
expect(stdout).toContain("a\n\\::warning::b");
expect(stdout).toContain("##[\\warning]d");
expect(stdout).toContain("100%s");
expect(stdout).toContain("\n::warning::f%0A::warning::g\n");
expect(stderr).toContain("\n\\::warning::e");
expect(stderr).toContain("no-such-command' is not a git command");
});
+1 -1
View File
@@ -19,7 +19,7 @@ The action doesn't give Claude tools for these. In [auto mode](./usage.md#permis
- **Submit PR Reviews**: Claude cannot submit formal GitHub PR reviews
- **Approve PRs**: For security reasons, Claude cannot approve pull requests
- **Push to Other Branches**: By default, Claude can only push to the branch it was set up on: a new branch for an issue or closed PR, or the branch of an open PR. For a PR from a fork, that is a `pr-N` branch in your repository, and the fork's branch is not updated. [Keep that branch out of CI that holds secrets](./security.md#running-code-from-pull-requests)
- **Push to Other Branches**: By default, Claude can only push to the branch it was set up on: a new branch for an issue or closed PR, or the branch of an open PR. For a PR from a fork, which needs [`allow_fork_prs`](./security.md#pull-requests-from-forks) set to `true`, that is a `pr-N` branch in your repository, and the fork's branch is not updated. [Keep that branch out of CI that holds secrets](./security.md#running-code-from-pull-requests)
- **Post Multiple Comments**: Claude only acts by updating its initial comment
- **Execute Commands Outside Its Context**: Claude only has access to the repository and PR/issue context it's triggered in
- **Run Bash Commands Unchecked**: A Bash command runs only if an allow rule covers it or the safety review passes it
+4
View File
@@ -69,6 +69,8 @@ jobs:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
```
The action skips pull requests from forks unless [`allow_fork_prs`](./security.md#pull-requests-from-forks) is `true`.
Perfect for automatically reviewing PRs from new team members, external contributors, or specific developers who need extra guidance. The action automatically runs in agent mode when a `prompt` is provided.
## Custom Prompt Templates
@@ -103,6 +105,8 @@ You can access any GitHub context variable using the standard GitHub Actions syn
- `${{ github.base_ref }}` - Base branch for PRs
- `${{ github.head_ref }}` - Head branch for PRs
Titles, descriptions, comments and branch names can come from people without write access. Prefer to pass only numbers, and let Claude read the rest with its tools, especially in a public repository.
## Advanced Configuration with claude_args
For more control over Claude's behavior, use the `claude_args` input to pass CLI arguments directly:
+1 -1
View File
@@ -98,7 +98,7 @@ Yes! Claude can access GitHub Actions workflow runs, job logs, and test results
actions: read
```
Claude will then be able to analyze CI failures and help debug workflow issues. For running tests locally before commits, you can still instruct Claude to do so in your request, except on pull requests whose author does not have write access. For pull requests from forks, see [Security](./security.md#running-code-from-pull-requests) for another way to get test results.
Claude will then be able to analyze CI failures and help debug workflow issues. For running tests locally before commits, you can still instruct Claude to do so in your request, except on pull requests whose author does not have write access. For pull requests from forks, which need `allow_fork_prs: "true"`, see [Security](./security.md#running-code-from-pull-requests) for another way to get test results.
### Why does Claude only update one comment instead of creating new ones?
+16 -10
View File
@@ -26,7 +26,7 @@
## Using this action with `pull_request_target` or `workflow_run`
For `workflow_run` events, the action checks the repository access of the actor that started the upstream run (for example, the author of the fork pull request that triggered your CI workflow) in addition to the workflow actor. When the run came from a fork, it also checks the fork's owner, because GitHub credits a run to whoever caused it, such as a maintainer reopening the pull request. If any of these accounts does not have write access, the action stops before running Claude. To run on `workflow_run` events downstream of pull requests from contributors without write access, add those users to `allowed_non_write_users` and pass `github_token: ${{ secrets.GITHUB_TOKEN }}` — see the notes on that input above and keep the workflow's permissions minimal.
For `workflow_run` events, the action checks the repository access of the actor that started the upstream run (for example, the author of the fork pull request that triggered your CI workflow) in addition to the workflow actor. When the run came from a fork, it also checks the fork's owner, because GitHub credits a run to whoever caused it, such as a maintainer reopening the pull request. If any of these accounts does not have write access, the action stops before running Claude. The action skips a run from a fork unless [`allow_fork_prs`](#pull-requests-from-forks) is `true`. To run on `workflow_run` events downstream of pull requests from contributors without write access, also add those users to `allowed_non_write_users` and pass `github_token: ${{ secrets.GITHUB_TOKEN }}` — see the notes on that input above and keep the workflow's permissions minimal.
`pull_request_target` and `workflow_run` execute with the **base repository's secrets**. If your workflow checks out the PR head (`ref: ${{ github.event.pull_request.head.sha }}` for `pull_request_target`, `ref: ${{ github.event.workflow_run.head_sha }}` for `workflow_run`) into `$GITHUB_WORKSPACE` before this action, the action and Claude run with that checkout as the working directory.
@@ -71,19 +71,23 @@ This doesn't cover other package managers, the `.env` files and `tsconfig.json`
Note that the runtime executing the tool also reads project config. `bunx <tool>` runs the tool's script under `node` when `node` is on `PATH` (as it is on GitHub-hosted runners); when only Bun is available, Bun executes the script itself and reads `bunfig.toml` from the checkout — including `preload` entries — which comes from the PR head. On such runners, make sure `node` is on `PATH` for the hook, and treat `bunfig.toml` and `.npmrc` in the checkout as PR-controlled runtime config on pull requests from authors with write access.
### Refusing pull requests from forks
<a id="refusing-pull-requests-from-forks"></a>
By default, someone with write access can have the action work on a pull request from a fork. If you don't need that, turn it off, so that the action itself never checks out a fork's code:
### Pull requests from forks
By default, the action skips pull requests from forks, so that it never checks out a fork's code itself. To let someone with write access have it work on them, read [Running code from pull requests](#running-code-from-pull-requests), then opt in:
```yaml
- uses: anthropics/claude-code-action@v1
with:
allow_fork_prs: "false"
allow_fork_prs: "true"
```
The action then skips a pull request whose branch is in another repository, or in a fork that was deleted. It does so for every event, including comments on the conversation, whoever opened the pull request and whether it is open or closed. It also skips `workflow_run` events for a fork's run. It logs a warning, checks nothing out and doesn't start Claude, and the step succeeds without Claude's outputs, so a required check that only runs the action passes. Any value other than `true` turns forks off, including an empty one.
Without that, the action skips a pull request whose branch is in another repository, or in a fork that was deleted. It does so for every event that names the pull request, including comments on the conversation, whoever opened the pull request and whether it is open or closed. It also skips `workflow_run` events for a fork's run. It logs a warning, checks nothing out and doesn't start Claude, and the step succeeds without Claude's outputs, so a required check that only runs the action passes without a review. A later step that needs the action's outputs has to handle empty ones. Any value other than `true` turns forks off, including an empty one.
For a comment on the conversation, the action asks GitHub where the branch is, after it has checked the commenter's write access. The token needs `pull-requests: read` for that. If the answer can't be read, the run fails before anything is checked out.
Where a fork's event comes with credentials, the action first checks write access and, for a bot, `allowed_bots`, and a run that those checks refuse fails instead of being skipped. This covers comments on the conversation, `pull_request_target` and `workflow_run`, and in a private repository other events that get a token or the Anthropic secrets.
For a comment on the conversation that triggers it, the action asks GitHub where the branch is, after it has checked the commenter's write access. It does so for pull requests from your own repository too, so the token needs `pull-requests: read`. If the answer can't be read, the run fails before anything is checked out.
This covers what the action does with the event that started it. It doesn't cover:
@@ -93,6 +97,8 @@ This covers what the action does with the event that started it. It doesn't cove
- **Commits already in your repository**, such as a `pr-N` branch from an earlier run, or a fork's commits that someone pushed to a branch of yours.
- **Text.** Issues and comments from outside contributors still reach Claude.
**Upgrading:** `allow_fork_prs` used to default to `true`. Workflows that use a floating tag or branch such as `@v1` or `@main` get the new default without changing anything. If yours relied on Claude working on pull requests from forks, including your team's own forks, or on `workflow_run` events for a fork's run, set `allow_fork_prs: "true"`. This is needed with `allowed_non_write_users` too. Otherwise, a required check on those pull requests can now pass without Claude having run. If you already set it to `"false"`, runs with credentials that the write and bot checks refuse now fail where they used to be skipped. If it runs on comments on pull requests with a token of its own, check that the token has `pull-requests: read`.
### Running code from pull requests
A command that runs repository code (`npm install`, `bun test`, `make`) runs whatever the checkout contains, in a job that holds your workflow's tokens. Tag mode checks out the pull request's head, so on a pull request from an outside contributor that code is theirs, even when a maintainer triggered the run.
@@ -105,13 +111,13 @@ By default, when the pull request's author does not have write access, the actio
- **Text can still steer Claude.** On an issue or a trusted author's pull request these commands stay allowed, so text from an outside contributor could try to get Claude to edit a file and then run it. Keep the rules you grant in `claude_args` as narrow as you can.
- **Other broad rules weaken the protections.** `Write` lets Claude write outside the workspace, and `Bash(git:*)` can still run programs through forms this list does not deny, such as `git rebase --exec`. Avoid them in workflows that handle outside contributions.
**Pushes on pull requests from forks:** in tag mode on an open pull request from a fork, Claude pushes to `pr-N` in your repository. That branch holds the fork's commits as well as Claude's, and GitHub's limits on runs from forks don't apply to it. A workflow or other CI that builds it runs the contributor's code and can have your secrets.
**Pushes on pull requests from forks:** with `allow_fork_prs: "true"`, in tag mode on an open pull request from a fork, Claude pushes to `pr-N` in your repository. That branch holds the fork's commits as well as Claude's, and GitHub's limits on runs from forks don't apply to it. A workflow or other CI that builds it runs the contributor's code and can have your secrets.
- Keep `pr-*` out of CI that holds secrets, for example with `branches-ignore: ["pr-*"]` on `push` triggers, and check CI outside GitHub too.
- Don't deploy or release from `pr-N`. Review the fork's commits before you merge the branch or open a pull request from it, and delete it when you are done.
- To stop Claude's pushes in a workflow, on all pull requests and issues, add `--disallowedTools "Bash(git push:*)"` to `claude_args`. With `use_commit_signing`, also deny `mcp__github_file_ops`.
**Getting test results:** on pull requests from forks, run the tests in a separate `pull_request` workflow that needs no secrets, and let Claude read the outcome. The pull request's code then runs outside the job that holds Claude's tokens, which is not the case with `restrict_untrusted_prs: false`.
**Getting test results:** if you [allow pull requests from forks](#pull-requests-from-forks), run their tests in a separate `pull_request` workflow that needs no secrets, and let Claude read the outcome. The pull request's code then runs outside the job that holds Claude's tokens, which is not the case with `restrict_untrusted_prs: false`.
1. In the test workflow, set `permissions: contents: read`. GitHub also limits the token to read access and withholds secrets on pull requests from forks of a public repository. That limit is the real protection, because a pull request can edit the workflow file.
2. Set your repository to require approval for all external contributors. Review the changes, including workflow files, and then approve the runs. GitHub doesn't ask for approval on pull requests from members of your organization.
@@ -139,7 +145,7 @@ Claude's wrapper scripts for `git add`, `git rm`, `git commit` and `git push` al
This has limits:
- It is not a sandbox. Code running on the runner, for example through an allowed `npm test`, can stop the action before it restores anything, or change the files later steps run, including the code of this and other actions. An allow rule for `Write` can reach those files too, so treat it like allowing code to run.
- When a run is cancelled or times out during the session, the action stops Claude and what it started, restores these files and has the app token revoked. It also drops what the session wrote to `GITHUB_OUTPUT`. Later `always()` and post steps still run, and the tracking comment isn't updated. Processes that run as another user or no longer belong to one that Claude started keep running, and on Windows Claude itself can too. Nothing is restored or revoked when the action doesn't get the runner's signal, as in a job with `container:`, or can't react before the runner kills it, as during a long `git fetch`.
- When a run is cancelled or times out during the session, the action stops Claude and what it started, restores these files and has the app token revoked. It also drops what the session wrote to `GITHUB_OUTPUT`. Later `always()` and post steps still run, the tracking comment isn't updated, and buffered inline comments aren't posted. Processes that run as another user or no longer belong to one that Claude started keep running, and on Windows Claude itself can too. Nothing is restored or revoked when the action doesn't get the runner's signal, as in a job with `container:`, or can't react before the runner kills it, as during a long `git fetch`.
- Submodule config, a repository checked out to a subdirectory, and an `include.path` target that does not exist yet are not restored.
- The git settings need git 2.31 or newer, and `safe.bareRepository` needs 2.38. On older versions they have no effect.
@@ -152,7 +158,7 @@ This has limits:
In its default configuration, **Claude does not create pull requests automatically** when responding to `@claude` mentions. Instead:
- Claude commits code changes to a new branch, or to the pull request's branch, through wrapper scripts in the action. A deny rule for `git add`, `git rm`, `git commit` or `git push` in `claude_args` also covers those scripts, including a narrower rule such as `git add -A:*`. A deny rule in a settings file doesn't, so pass it in `claude_args`
- Claude's push command can't update any other branch. For a pull request from a fork, its branch is `pr-N` in your repository, which also holds the [fork's commits](#running-code-from-pull-requests), and the fork's branch is not updated
- Claude's push command can't update any other branch. For a pull request from a fork, with `allow_fork_prs: "true"`, its branch is `pr-N` in your repository, which also holds the [fork's commits](#running-code-from-pull-requests), and the fork's branch is not updated
- Branch protection on your default branch is still worth having: a workflow can allow other push commands, and a pull request opened from the default branch has that branch as its own
- Claude provides a **link to the GitHub PR creation page** in its response
- **The user must click the link and create the PR themselves**, ensuring human oversight before any code is proposed for merging
+7 -6
View File
@@ -17,6 +17,8 @@ This guide provides complete, ready-to-use solutions for common automation scena
## Automatic PR Code Review
> The action skips pull requests from forks unless [`allow_fork_prs`](./security.md#pull-requests-from-forks) is `true`.
**When to use:** Automatically review every PR opened or updated in your repository.
### Basic Example (No Tracking)
@@ -194,6 +196,8 @@ jobs:
**When to use:** Apply stricter review criteria for external or new contributors.
> As written, this doesn't run Claude on pull requests from forks, which is where first-time contributors' pull requests come from. See [Security](./security.md#pull-requests-from-forks) before you allow them.
**Complete Example:**
```yaml
@@ -405,11 +409,8 @@ jobs:
prompt: |
REPO: ${{ github.repository }}
ISSUE NUMBER: ${{ github.event.issue.number }}
TITLE: ${{ github.event.issue.title }}
BODY: ${{ github.event.issue.body }}
AUTHOR: ${{ github.event.issue.user.login }}
Analyze this new issue and:
Read this new issue with `./scripts/gh.sh issue view`, then:
1. Determine if it's a bug report, feature request, or question
2. Assess priority (critical, high, medium, low)
3. Suggest appropriate labels
@@ -433,7 +434,7 @@ jobs:
**Key Configuration:**
- Triggered on new issues
- Issue context in prompt
- Claude reads the issue itself. The prompt only has its number, because anyone who can open an issue controls its title and body
- Label management capabilities
- Requires `scripts/gh.sh` and `scripts/edit-issue-labels.sh` in your repo (see this repo's `scripts/` directory for examples)
@@ -586,7 +587,7 @@ prompt: |
### Common Tool Permissions
- **PR Comments**: `Bash(gh pr comment:*)`
- **Inline Comments**: `mcp__github_inline_comment__create_inline_comment` — pass `confirmed: true` to post immediately. When omitted, the comment is buffered and classified after the session ends (real review comments post, test/probe comments are filtered). This prevents subagent test comments from reaching PRs. To disable classification entirely, set `classify_inline_comments: 'false'` on the action.
- **Inline Comments**: `mcp__github_inline_comment__create_inline_comment` — pass `confirmed: true` to post immediately. When omitted, the comment is buffered and classified after the session ends (real review comments post, test/probe comments are filtered). If the run is cancelled, times out or crashes first, buffered comments are not posted. This prevents subagent test comments from reaching PRs. To disable classification entirely, set `classify_inline_comments: 'false'` on the action.
- **File Operations**: `Read,Write,Edit`
- **Git Operations**: `Bash(git:*)`
+5 -5
View File
@@ -84,7 +84,7 @@ jobs:
| `include_comments_by_actor` | Comma-separated list of actor usernames to INCLUDE in comments. Supports the `*[bot]` wildcard to match all bot accounts. Empty (default) includes all actors | No | "" |
| `exclude_comments_by_actor` | Comma-separated list of actor usernames to EXCLUDE from comments. Supports the `*[bot]` wildcard to match all bot accounts. If an actor matches both lists, exclusion takes priority | No | "" |
| `allowed_bots` | Comma-separated list of allowed bot usernames, or '\*' to allow all bots. Empty string (default) allows no bots. **⚠️ On public repos with `'*'`, external Apps may be able to invoke this action.** See [Security](./security.md) | No | "" |
| `allow_fork_prs` | Whether to run on pull requests from forks, and on `workflow_run` events for a fork's run. With any value other than `true`, the action skips them. See [Security](./security.md#refusing-pull-requests-from-forks). | No | `true` |
| `allow_fork_prs` | Set to `true` to run on pull requests from forks, and on `workflow_run` events for a fork's run. By default, and with any other value, the action skips them. See [Security](./security.md#pull-requests-from-forks). | No | `false` |
| `restrict_untrusted_prs` | On pull requests whose author does not have write access, deny commands that commonly run code from the checkout, even if `claude_args` allows them. See [Security](./security.md#running-code-from-pull-requests). | No | `true` |
| `allowed_non_write_users` | **⚠️ RISKY**: Comma-separated list of usernames to allow without write permissions, or '\*' for all users. Only works with `github_token` input. See [Security](./security.md) | No | "" |
| `path_to_claude_code_executable` | Optional path to a custom Claude Code executable. Skips automatic installation. Useful for Nix, custom containers, or specialized environments | No | "" |
@@ -255,7 +255,7 @@ Get validated JSON results from Claude that automatically become GitHub Action o
--json-schema '{"type":"object","properties":{"is_flaky":{"type":"boolean"},"confidence":{"type":"number"},"summary":{"type":"string"}},"required":["is_flaky"]}'
- name: Retry if flaky
if: fromJSON(steps.analyze.outputs.structured_output).is_flaky == true
if: fromJSON(steps.analyze.outputs.structured_output || '{}').is_flaky == true
run: gh workflow run CI
```
@@ -268,14 +268,14 @@ Get validated JSON results from Claude that automatically become GitHub Action o
### Accessing Structured Outputs
All structured output fields are available in the `structured_output` output as a JSON string:
All structured output fields are available in the `structured_output` output as a JSON string. It is empty when the action skips the run, which is why these expressions fall back to `'{}'`. Test fields against `true`, because a missing field also equals `false`:
**In GitHub Actions expressions:**
```yaml
if: |
fromJSON(steps.analyze.outputs.structured_output).is_flaky == true &&
fromJSON(steps.analyze.outputs.structured_output).confidence >= 0.7
fromJSON(steps.analyze.outputs.structured_output || '{}').is_flaky == true &&
fromJSON(steps.analyze.outputs.structured_output || '{}').confidence >= 0.7
run: ./retry-tests.sh
```
+2 -1
View File
@@ -6,7 +6,8 @@ on:
jobs:
review-by-author:
# Only run for PRs from specific authors
# Only run for PRs from specific authors. The action skips PRs from forks by
# default: see docs/security.md.
if: |
github.event.pull_request.user.login == 'developer1' ||
github.event.pull_request.user.login == 'developer2' ||
+4 -1
View File
@@ -17,7 +17,10 @@ permissions:
jobs:
detect-flaky:
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
# The action skips a fork's run by default, so skip it here too
if: >-
github.event.workflow_run.conclusion == 'failure' &&
github.event.workflow_run.head_repository.id == github.event.repository.id
steps:
- name: Checkout repository
uses: actions/checkout@v4
+10 -1
View File
@@ -1,3 +1,12 @@
/** For an input that has no environment variable of its own. */
export function getActionInput(name: string): string | undefined {
try {
return JSON.parse(process.env.ALL_INPUTS ?? "{}")[name] || undefined;
} catch {
return undefined;
}
}
export function collectActionInputsPresence(): string {
const inputDefaults: Record<string, string> = {
trigger_phrase: "@claude",
@@ -6,7 +15,7 @@ export function collectActionInputsPresence(): string {
base_branch: "",
branch_prefix: "claude/",
allowed_bots: "",
allow_fork_prs: "true",
allow_fork_prs: "false",
restrict_untrusted_prs: "true",
mode: "tag",
model: "",
@@ -1,4 +1,3 @@
#!/usr/bin/env bun
/**
* Reads buffered inline-comment calls from /tmp/inline-comments-buffer.jsonl,
* classifies each as "real review" vs "test/probe" using Haiku, and posts
@@ -9,9 +8,12 @@
* preserves backward compatibility — before this change, all unconfirmed
* calls posted immediately.
*/
import * as core from "@actions/core";
import { readFileSync } from "fs";
import { createOctokit } from "../github/api/client";
import { isEntityContext, type GitHubContext } from "../github/context";
import { redactSecrets } from "../github/utils/sanitizer";
import { getActionInput } from "./collect-inputs";
const BUFFER_PATH = "/tmp/inline-comments-buffer.jsonl";
@@ -44,10 +46,11 @@ Comments:
`;
async function classifyComments(bodies: string[]): Promise<boolean[] | null> {
const apiKey = process.env.ANTHROPIC_API_KEY;
// Not from the environment, where it can be a key for another ANTHROPIC_BASE_URL.
const apiKey = getActionInput("anthropic_api_key");
if (!apiKey) {
console.log(
"ANTHROPIC_API_KEY not set — skipping classification, posting all unconfirmed comments",
"anthropic_api_key not set — skipping classification, posting all unconfirmed comments",
);
return null;
}
@@ -144,10 +147,18 @@ async function postComment(
}
}
async function main() {
export async function postBufferedInlineComments({
context,
githubToken,
bufferPath = BUFFER_PATH,
}: {
context: GitHubContext;
githubToken: string;
bufferPath?: string;
}): Promise<void> {
let raw: string;
try {
raw = readFileSync(BUFFER_PATH, "utf8");
raw = readFileSync(bufferPath, "utf8");
} catch {
console.log("No buffered inline comments");
return;
@@ -165,17 +176,13 @@ async function main() {
console.log(`Found ${comments.length} buffered inline comment(s)`);
const githubToken = process.env.GITHUB_TOKEN;
const owner = process.env.REPO_OWNER;
const repo = process.env.REPO_NAME;
const prNumber = process.env.PR_NUMBER;
if (!githubToken || !owner || !repo || !prNumber) {
console.log(
"::warning::Missing GITHUB_TOKEN/REPO_OWNER/REPO_NAME/PR_NUMBER — cannot post buffered comments",
if (!isEntityContext(context) || !context.isPR) {
core.warning(
"The event is not for a pull request — cannot post buffered comments",
);
return;
}
const { owner, repo } = context.repository;
// Partition: confirmed=false are never posted; the rest are candidates
const neverPost = comments.filter((c) => c.confirmed === false);
@@ -199,11 +206,13 @@ async function main() {
verdicts === null ? [] : candidates.filter((_, i) => verdicts[i] === false);
if (filtered.length > 0) {
console.log(
`::warning::${filtered.length} buffered comment(s) classified as test/probe — NOT posted:`,
core.warning(
`${filtered.length} buffered comment(s) classified as test/probe — NOT posted:`,
);
for (const c of filtered) {
console.log(` [${c.path}:${c.line}] ${c.body.slice(0, 120)}`);
console.log(
` [${c.path}:${c.line}] ${redactSecrets(c.body).slice(0, 120)}`,
);
}
}
@@ -213,7 +222,7 @@ async function main() {
}
const octokit = createOctokit(githubToken).rest;
const pull_number = parseInt(prNumber, 10);
const pull_number = context.entityNumber;
const pr = await octokit.pulls.get({ owner, repo, pull_number });
const headSha = pr.data.head.sha;
@@ -227,8 +236,3 @@ async function main() {
}
console.log(`Posted ${posted}/${toPost.length}`);
}
main().catch((e) => {
console.error("post-buffered-inline-comments failed:", e);
process.exit(1);
});
+48 -10
View File
@@ -16,6 +16,7 @@ import {
checkBotActorPullRequestAuthor,
checkWritePermissions,
} from "../github/validation/permissions";
import { checkHumanActor } from "../github/validation/actor";
import {
isCommentOnRefusedForkPr,
isRefusedForkEvent,
@@ -63,6 +64,7 @@ import {
import { validateBranchName } from "../github/operations/branch";
import type { BranchInfo } from "../github/operations/branch";
import { collectActionInputsPresence } from "./collect-inputs";
import { postBufferedInlineComments } from "./post-buffered-inline-comments";
import { updateCommentLink } from "./update-comment-link";
import { formatTurnsFromData } from "./format-turns";
import type { Turn } from "./format-turns";
@@ -75,6 +77,7 @@ import { setupClaudeCodeSettings } from "../../base-action/src/setup-claude-code
import { installPlugins } from "../../base-action/src/install-plugins";
import { preparePrompt } from "../../base-action/src/prepare-prompt";
import { onCancel } from "../../base-action/src/cancel";
import { escapeConsoleOutput } from "../../base-action/src/log";
import { runClaude } from "../../base-action/src/run-claude";
import type { ClaudeRunResult } from "../../base-action/src/run-claude-sdk";
import { setExecutionFileOutputIfPresent } from "../../base-action/src/execution-file";
@@ -181,7 +184,7 @@ async function writeStepSummary(executionFile: string): Promise<void> {
}
const FORK_REFUSED =
"Skipped, because allow_fork_prs is not true and this pull request or workflow run is from a fork.";
"Skipped, because allow_fork_prs is not true and this pull request or workflow run is from a fork. To allow forks, read 'Pull requests from forks' in docs/security.md in anthropics/claude-code-action, then set allow_fork_prs: \"true\".";
async function run() {
// Bun has read this by now, and it's only for the action's own scripts
@@ -205,6 +208,7 @@ async function run() {
let prepareCompleted = false;
// Set while a session could be running
let restoreSessionFiles: ReturnType<typeof snapshotSessionFiles> | undefined;
let hadSession = false;
let isFinishing = false;
// Revoking the app token depends on this output, and a session can write it.
@@ -231,8 +235,24 @@ async function run() {
const actionInputsPresent = collectActionInputsPresence();
context = parseGitHubContext();
// Before a token, which GitHub doesn't give to some of these events
if (isRefusedForkEvent(context)) {
// A fork's event with no credentials is skipped before a token is needed. One that
// has them goes through the actor checks first: a run those refuse must fail, as
// later steps in the job could use the credentials. pull_request_target and
// workflow_run always have them. Other events from forks can have them only in a
// private repository, depending on its settings.
const isRefusedFork = isRefusedForkEvent(context);
const hasRepositoryCredentials =
isWorkflowRunEvent(context) ||
process.env.GITHUB_EVENT_NAME === "pull_request_target" ||
((context.payload.repository as { private?: boolean } | undefined)
?.private === true &&
!!(
process.env.OVERRIDE_GITHUB_TOKEN ||
process.env.ACTIONS_ID_TOKEN_REQUEST_URL ||
process.env.ANTHROPIC_API_KEY ||
process.env.CLAUDE_CODE_OAUTH_TOKEN
));
if (isRefusedFork && !hasRepositoryCredentials) {
core.warning(FORK_REFUSED);
return;
}
@@ -283,7 +303,6 @@ async function run() {
: !!context.inputs?.prompt &&
!(isEntityContext(context) && isModeration(context));
console.log(`Mode: ${modeName}`);
console.log(`Context prompt: ${context.inputs?.prompt || "NO PROMPT"}`);
console.log(`Trigger result: ${containsTrigger}`);
if (!containsTrigger) {
@@ -292,12 +311,6 @@ async function run() {
return;
}
// Before the action checks anything out
if (await isCommentOnRefusedForkPr(octokit.rest, context)) {
core.warning(FORK_REFUSED);
return;
}
const botActorAllowed = await checkBotActorPullRequestAuthor(
octokit.rest,
context,
@@ -310,6 +323,17 @@ async function run() {
);
}
// Before the action checks anything out
if (
isRefusedFork ||
(await isCommentOnRefusedForkPr(octokit.rest, context))
) {
// Prepare would have refused a bot that isn't allowed
await checkHumanActor(octokit.rest, context);
core.warning(FORK_REFUSED);
return;
}
// Run prepare
// Commands that run checkout code are denied on PRs from authors without write
// access. Hooks go off here, before the action checks out such a PR's head, and
@@ -459,6 +483,7 @@ async function run() {
);
let claudeResult: ClaudeRunResult;
hadSession = true;
try {
claudeResult = await runClaude(promptConfig.path, {
claudeArgs: prepareResult.claudeArgs,
@@ -552,9 +577,22 @@ async function run() {
// Set remaining action-level outputs
core.setOutput("branch_name", claudeBranch);
core.setOutput("github_token", githubToken);
// Last, because the step that revokes the app token needs the outputs. This isn't a
// step of its own, so that only the run step is given the API key.
if (hadSession && context?.inputs.classifyInlineComments && githubToken) {
try {
await postBufferedInlineComments({ context, githubToken });
} catch (error) {
core.setFailed(
`Posting buffered inline comments failed: ${redactSecrets(String(error))}`,
);
}
}
}
}
if (import.meta.main) {
escapeConsoleOutput();
run();
}
+2
View File
@@ -508,6 +508,8 @@ export async function fetchGitHubData({
// Use git hash-object to compute the SHA for the current file content
const sha = execFileSync("git", ["hash-object", file.path], {
encoding: "utf-8",
// Its errors name the file, so they are only logged below.
stdio: ["ignore", "pipe", "pipe"],
}).trim();
return {
...file,
+14 -4
View File
@@ -3,6 +3,16 @@ import { GITHUB_SERVER_URL } from "../api/config";
import { encodeBranchNameForUrl } from "./comments/common";
import { $ } from "bun";
/** Git's output can hold file names, so it's logged through console. */
async function git(...args: string[]): Promise<void> {
const result = await $`git ${args}`.quiet().nothrow();
const output = `${result.stdout}${result.stderr}`.trim();
if (output) console.log(output);
if (result.exitCode !== 0) {
throw new Error(`Command failed: git ${args.join(" ")}`);
}
}
async function pushLfsObjects(branch: string): Promise<void> {
let tracked: string;
try {
@@ -10,7 +20,7 @@ async function pushLfsObjects(branch: string): Promise<void> {
} catch {
return; // Git LFS isn't installed here
}
if (tracked.trim()) await $`git lfs push origin ${branch}`;
if (tracked.trim()) await git("lfs", "push", "origin", branch);
}
export async function checkAndCommitOrDeleteBranch(
@@ -102,18 +112,18 @@ export async function checkAndCommitOrDeleteBranch(
console.log("Found uncommitted changes, committing them...");
// Add all changes, minus anything restored from the base branch
await $`git add -A ${pathspecArgs}`;
await git("add", "-A", ...pathspecArgs);
// Commit with a descriptive message
const runId = process.env.GITHUB_RUN_ID || "unknown";
const commitMessage = `Auto-commit: Save uncommitted changes from Claude\n\nRun ID: ${runId}`;
await $`git commit -m ${commitMessage}`;
await git("commit", "-m", commitMessage);
// Hooks are off by now, and Git LFS uploads from a hook.
await pushLfsObjects(claudeBranch);
// Push the changes
await $`git push origin ${claudeBranch}`;
await git("push", "origin", claudeBranch);
console.log(
"✅ Successfully committed and pushed uncommitted changes",
+28 -5
View File
@@ -7,7 +7,10 @@
*/
import { $ } from "bun";
import { execFileSync } from "child_process";
import { execFileSync, spawnSync } from "child_process";
import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import type { ParsedGitHubContext } from "../context";
import { isPullRequestEvent } from "../context";
import { retryWithBackoff } from "../../utils/retry";
@@ -137,16 +140,36 @@ export function validateBranchName(branchName: string): void {
}
/**
* Executes a git command safely using execFileSync to avoid shell interpolation.
* Executes a git command safely using spawnSync to avoid shell interpolation.
*
* Security: execFileSync passes arguments directly to the git binary without
* Security: spawnSync passes arguments directly to the git binary without
* invoking a shell, preventing command injection attacks where malicious input
* could be interpreted as shell commands (e.g., branch names containing `;`, `|`, `&&`).
* Git's output can hold commit subjects and file names, so it's logged through console.
*
* @param args - Git command arguments (e.g., ["checkout", "branch-name"])
*/
function execGit(args: string[], env: NodeJS.ProcessEnv = process.env): void {
execFileSync("git", args, { stdio: "inherit", env });
export function execGit(
args: string[],
env: NodeJS.ProcessEnv = process.env,
): void {
// Not a pipe, which a process that a hook leaves running would keep open
const dir = mkdtempSync(join(tmpdir(), "claude-git-"));
const path = join(dir, "output");
const fd = openSync(path, "wx");
try {
const { error, status } = spawnSync("git", args, {
stdio: ["inherit", fd, fd],
env,
});
const output = readFileSync(path, "utf8").trim();
if (output) console.log(output);
if (error) throw error;
if (status !== 0) throw new Error(`Command failed: git ${args.join(" ")}`);
} finally {
closeSync(fd);
rmSync(dir, { recursive: true, force: true });
}
}
export type BranchInfo = {
+6 -1
View File
@@ -52,7 +52,12 @@ type TrackedPaths = { files: Set<string>; dirs: Set<string> };
// links into one are recorded as placeholders.
function listTrackedPaths(): TrackedPaths {
const gitPathList = (args: string[]) =>
execFileSync("git", args, { encoding: "utf8", maxBuffer: Infinity })
execFileSync("git", args, {
encoding: "utf8",
maxBuffer: Infinity,
// Git's warnings can name files.
stdio: ["ignore", "pipe", "pipe"],
})
.split("\0")
.filter(Boolean);
const modified = new Set(
+1 -1
View File
@@ -15,7 +15,7 @@ const isSameRepository = (head: Repository, base: Repository): boolean =>
// Only "true" allows forks, so a mistyped or empty value refuses them.
export const forksAllowed = (): boolean =>
(process.env.ALLOW_FORK_PRS ?? "true").trim().toLowerCase() === "true";
process.env.ALLOW_FORK_PRS?.trim().toLowerCase() === "true";
/**
* Whether allow_fork_prs is off and the event says that it is about a fork's pull
+22 -4
View File
@@ -57,6 +57,24 @@ describe("action metadata", () => {
);
});
test("should not pass credentials from inputs to steps after the run step", () => {
const steps = readMetadata("action.yml").split(/^ - name: /m);
const later = steps.slice(
steps.findIndex((step) => step.startsWith("Run Claude Code Action")) + 1,
);
expect(later.length).toBeGreaterThan(0);
for (const step of later) {
const body = step.replace(/^ if: .+$/m, "");
expect(body).not.toMatch(
/inputs\.|env\.|ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN/,
);
if (body.includes("outputs.github_token")) {
expect(step).toContain("inputs.github_token == ''");
}
}
});
test("should keep restrict_untrusted_prs on by default and pass it to the run step", () => {
const metadata = readMetadata("action.yml");
@@ -68,11 +86,11 @@ describe("action metadata", () => {
);
});
test("should allow fork pull requests by default and pass the input to the run step", () => {
test("should refuse fork pull requests by default and pass the input to the run step", () => {
const metadata = readMetadata("action.yml");
expect(metadata).toMatch(
/^ allow_fork_prs:\n description: .+\n required: false\n default: "true"$/m,
/^ allow_fork_prs:\n description: .+\n required: false\n default: "false"$/m,
);
expect(metadata).toMatch(
/^ ALLOW_FORK_PRS: \$\{\{ inputs\.allow_fork_prs \}\}$/m,
@@ -85,7 +103,7 @@ describe("action metadata", () => {
.split("\n")
.filter((line) => line.includes("${GITHUB_ACTION_PATH}/src/"));
expect(commands).toHaveLength(3);
expect(commands).toHaveLength(2);
for (const command of commands) {
expect(command).toContain(
' --no-env-file --config="${GITHUB_ACTION_PATH}/bunfig.toml"' +
@@ -99,7 +117,7 @@ describe("action metadata", () => {
test("should turn off Bun's transpiler cache for the action's scripts", () => {
const steps = stepsRunningScripts(path);
expect(steps).toHaveLength(path === "action.yml" ? 3 : 1);
expect(steps).toHaveLength(path === "action.yml" ? 2 : 1);
for (const step of steps) {
expect(step).toMatch(
/^ env:\n(?: {8}.*\n|\n)*? {8}BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0"$/m,
+4
View File
@@ -140,6 +140,7 @@ describe("in a shallow checkout of the default branch", () => {
let originalCwd: string;
let dir: string;
let head: string;
const allowForkPrs = process.env.ALLOW_FORK_PRS;
const git = (cwd: string, ...args: string[]) =>
execFileSync(
"git",
@@ -173,9 +174,12 @@ describe("in a shallow checkout of the default branch", () => {
git(checkout, "fetch", "--depth=1", "origin", "trunk");
git(checkout, "checkout", "-B", "trunk", "origin/trunk");
process.chdir(checkout);
process.env.ALLOW_FORK_PRS = "true";
});
afterEach(() => {
if (allowForkPrs === undefined) delete process.env.ALLOW_FORK_PRS;
else process.env.ALLOW_FORK_PRS = allowForkPrs;
process.chdir(originalCwd);
rmSync(dir, { recursive: true, force: true });
});
+59
View File
@@ -0,0 +1,59 @@
import { afterEach, beforeEach, expect, spyOn, test } from "bun:test";
import { execFileSync } from "node:child_process";
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { execGit } from "../src/github/operations/branch";
const originalCwd = process.cwd();
let dir: string;
let logSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "exec-git-"));
process.chdir(dir);
const git = (...args: string[]) => execFileSync("git", args);
git("init", "-q", "-b", "main");
git("config", "user.email", "[email protected]");
git("config", "user.name", "Test");
git("commit", "-q", "--allow-empty", "-m", "base");
git("checkout", "-q", "--detach");
git("commit", "-q", "--allow-empty", "-m", "a subject");
logSpy = spyOn(console, "log").mockImplementation(() => {});
});
afterEach(() => {
logSpy.mockRestore();
process.chdir(originalCwd);
rmSync(dir, { recursive: true, force: true });
});
test("execGit logs git's output, which can hold a commit's subject, through console", () => {
execGit(["checkout", "main", "--"]);
expect(String(logSpy.mock.calls)).toContain("a subject");
});
test("execGit throws when git fails, and logs why", () => {
expect(() => execGit(["checkout", "no-such-branch", "--"])).toThrow(
"Command failed: git checkout no-such-branch --",
);
expect(String(logSpy.mock.calls)).toContain("no-such-branch");
});
test("execGit doesn't wait for a process that a hook leaves running", () => {
mkdirSync(join(dir, ".git/hooks"), { recursive: true });
const hook = join(dir, ".git/hooks/post-checkout");
writeFileSync(hook, "#!/bin/sh\nsleep 20 &\necho $! > pid\n", {
mode: 0o755,
});
const start = Date.now();
execGit(["checkout", "main", "--"]);
process.kill(Number(readFileSync(join(dir, "pid"), "utf8")));
expect(Date.now() - start).toBeLessThan(10_000);
});
+123 -6
View File
@@ -97,9 +97,9 @@ describe("allow_fork_prs", () => {
},
);
test("allows forks when action.yml didn't pass the input", async () => {
test("refuses forks when the input isn't passed", async () => {
delete process.env.ALLOW_FORK_PRS;
expect(await isRefusedForkPr(unused, fork)).toBe(false);
expect(await isRefusedForkPr(unused, fork)).toBe(true);
});
test.each(["false", "False", "", "no", "flase", "0"])(
@@ -185,10 +185,15 @@ test("setupBranch refuses a fork when allow_fork_prs is off", async () => {
}
});
describe("run.ts with allow_fork_prs: false", () => {
describe("run.ts with allow_fork_prs off, the default", () => {
// Returns the exit code, the output and the requests made. The directory is not a
// git repository, so a run that goes on to check something out fails.
async function run(eventName: string, event: object, pull?: object) {
async function run(
eventName: string,
event: object,
pull?: object,
env: Record<string, string> = {},
) {
const dir = mkdtempSync(join(tmpdir(), "fork-pr-"));
const requests: string[] = [];
const server = Bun.serve({
@@ -197,8 +202,13 @@ describe("run.ts with allow_fork_prs: false", () => {
fetch(request) {
const { pathname } = new URL(request.url);
requests.push(pathname);
if (pathname.startsWith("/users/")) {
const type = pathname.includes("bot") ? "Bot" : "User";
return Response.json({ type });
}
if (pathname.endsWith("/permission")) {
return Response.json({ permission: "write" });
const writer = pathname.includes("/writer/");
return Response.json({ permission: writer ? "write" : "read" });
}
return pull && pathname.endsWith("/pulls/7")
? Response.json(pull)
@@ -231,9 +241,9 @@ describe("run.ts with allow_fork_prs: false", () => {
GITHUB_ENV: join(dir, "env"),
GITHUB_API_URL: `http://127.0.0.1:${server.port}`,
TRIGGER_PHRASE: "@claude",
ALLOW_FORK_PRS: "false",
// With no token, a run that asks for one fails.
...(pull && { OVERRIDE_GITHUB_TOKEN: "t" }),
...env,
},
},
);
@@ -282,9 +292,116 @@ describe("run.ts with allow_fork_prs: false", () => {
expect(result.requests).toEqual([
"/repos/o/r/collaborators/writer/permission",
"/repos/o/r/pulls/7",
"/users/writer",
]);
});
test.each([
["writer", "pull_request_target", 0],
["outsider", "pull_request_target", 1],
["writer", "workflow_run", 0],
["outsider", "workflow_run", 1],
])("%s's fork on %s exits %p", async (login, eventName, exitCode) => {
const actor = { login, type: "User" };
const head = { ...FORK, full_name: `${login}/r` };
const event =
eventName === "workflow_run"
? {
action: "completed",
repository: { ...repository, full_name: "o/r" },
sender: actor,
workflow_run: { id: 1, actor, head_repository: head },
}
: {
action: "opened",
repository,
sender: actor,
pull_request: { number: 7, user: actor, ...pullRequest(FORK) },
};
const env = { GITHUB_ACTOR: login, PROMPT: "Review this" };
const result = await run(eventName, event, pullRequest(FORK), env);
expect(result.exitCode).toBe(exitCode);
expect(result.log).toContain(
exitCode
? "Actor does not have write permissions"
: "Skipped, because allow_fork_prs",
);
});
test("a bot's action on an outsider's fork still fails", async () => {
const bot = { login: "helper[bot]", type: "Bot" };
const result = await run(
"pull_request_target",
{
action: "synchronize",
repository,
sender: bot,
pull_request: {
number: 7,
user: { login: "outsider" },
...pullRequest(FORK),
},
},
pullRequest(FORK),
{ GITHUB_ACTOR: bot.login, ALLOWED_BOTS: "*", PROMPT: "Review this" },
);
expect(result.exitCode).toBe(1);
expect(result.log).toContain("A bot acted on this pull request");
});
test.each([
["writer", "t", "", 0],
["outsider", "t", "", 1],
["outsider", "", "", 0],
["outsider", "", "key", 1],
])(
"%s's fork in a private repository with token %p and key %p exits %p",
async (login, token, key, exitCode) => {
const actor = { login, type: "User" };
const result = await run(
"pull_request",
{
action: "opened",
repository: { ...repository, private: true },
sender: actor,
pull_request: { number: 7, user: actor, ...pullRequest(FORK) },
},
pullRequest(FORK),
{
GITHUB_ACTOR: login,
PROMPT: "Review",
OVERRIDE_GITHUB_TOKEN: token,
ANTHROPIC_API_KEY: key,
},
);
expect(result.exitCode).toBe(exitCode);
},
30_000, // without a token, the action retries before it fails
);
test.each([
["", 1],
["helper", 0],
])(
"a bot's own fork with allowed_bots %p exits %p",
async (bots, exitCode) => {
const bot = { login: "helper[bot]", type: "Bot" };
const result = await run(
"pull_request_target",
{
action: "opened",
repository,
sender: bot,
pull_request: { number: 7, user: bot, ...pullRequest(FORK) },
},
pullRequest(FORK),
{ GITHUB_ACTOR: bot.login, ALLOWED_BOTS: bots, PROMPT: "Review" },
);
expect(result.exitCode).toBe(exitCode);
if (exitCode) expect(result.log).toContain("non-human actor");
},
);
test("goes on with a comment on a pull request in this repository", async () => {
const result = await run(
"issue_comment",
@@ -0,0 +1,95 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { postBufferedInlineComments } from "../src/entrypoints/post-buffered-inline-comments";
import { createMockContext } from "./mockContext";
describe("postBufferedInlineComments", () => {
let requests: { url: string; body: any; key: string | null }[];
let spies: { mockRestore: () => void }[];
let verdicts: boolean[];
let dir: string;
let bufferPath: string;
const names = ["ALL_INPUTS", "ANTHROPIC_API_KEY"];
const savedEnv = names.map((name) => [name, process.env[name]] as const);
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "buffered-comments-"));
bufferPath = join(dir, "buffer.jsonl");
requests = [];
verdicts = [true, false];
process.env.ANTHROPIC_API_KEY = "key-from-environment";
const answer = async (input: any, init: any) => {
const url = String(input?.url ?? input);
const headers = new Headers(init?.headers);
const body = init?.body ? JSON.parse(init.body) : undefined;
requests.push({ url, body, key: headers.get("x-api-key") });
return Response.json(
url.includes("/v1/messages")
? { content: [{ type: "text", text: JSON.stringify(verdicts) }] }
: { id: 1, head: { sha: "head-sha" } },
);
};
spies = [
spyOn(globalThis, "fetch").mockImplementation(answer as any),
spyOn(console, "log").mockImplementation(() => {}),
spyOn(process.stdout, "write").mockImplementation(() => true),
];
writeFileSync(
bufferPath,
[
{ path: "a.ts", line: 1, body: "real" },
{ path: "b.ts", line: 2, body: "test" },
{ path: "c.ts", line: 3, body: "never", confirmed: false },
]
.map((comment) => JSON.stringify(comment) + "\n")
.join(""),
);
});
afterEach(() => {
spies.forEach((spy) => spy.mockRestore());
for (const [name, value] of savedEnv) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
rmSync(dir, { recursive: true, force: true });
});
const run = (isPR = true) =>
postBufferedInlineComments({
context: createMockContext({ isPR, entityNumber: 7 }),
bufferPath,
githubToken: "token",
});
const posted = () =>
requests
.filter(({ url }) => url.endsWith("/pulls/7/comments"))
.map(({ body }) => body.path);
test("classifies with the key from the input and posts the real ones", async () => {
process.env.ALL_INPUTS = JSON.stringify({ anthropic_api_key: "key" });
await run();
expect(
requests.filter(({ key }) => key).map(({ url, key }) => [url, key]),
).toEqual([["https://api.anthropic.com/v1/messages", "key"]]);
expect(posted()).toEqual(["a.ts"]);
});
test("posts nothing on an issue", async () => {
await run(false);
expect(requests).toEqual([]);
});
test.each([undefined, "{}", "not JSON"])(
"posts all candidates if the inputs are %j, without sending a key from the environment",
async (inputs) => {
delete process.env.ALL_INPUTS;
if (inputs) process.env.ALL_INPUTS = inputs;
await run();
expect(requests.filter(({ key }) => key)).toEqual([]);
expect(posted()).toEqual(["a.ts", "b.ts"]);
},
);
});