Compare commits

...
Author SHA1 Message Date
Claudeandmhegazy fee4b164c1 Skip pull requests from forks by default
allow_fork_prs now defaults to false. Workflows that need forks set it to
"true".

On pull_request_target and workflow_run, the write checks run before the
skip, so a run they refuse still fails.

Co-authored-by: mhegazy <[email protected]>
2026-11-21 01:35:06 +00:00
15 changed files with 124 additions and 35 deletions
+2 -2
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. 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
+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
+2
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
+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?
+15 -9
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.
`pull_request_target` and `workflow_run` events have your repository's credentials, so the action checks write access first on those. If that check refuses the run, the step fails instead of being skipped.
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. 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.
@@ -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
+4
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 covers branches in your repository only. The action skips pull requests from forks, as described in [Security](./security.md#pull-requests-from-forks).
**Complete Example:**
```yaml
+1 -1
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 | "" |
+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
+1 -1
View File
@@ -6,7 +6,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: "",
+19 -9
View File
@@ -180,7 +180,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
@@ -207,8 +207,15 @@ async function run() {
const actionInputsPresent = collectActionInputsPresence();
context = parseGitHubContext();
// Before a token, which GitHub doesn't give to some of these events
if (isRefusedForkEvent(context)) {
// GitHub gives a fork's pull_request and review events no credentials, so those
// are skipped before a token is needed. pull_request_target and workflow_run have
// the repository's, so they go through the write checks first: a run those refuse
// must fail, as later steps in the job could use the repository's secrets.
const isRefusedFork = isRefusedForkEvent(context);
const hasRepositoryCredentials =
isWorkflowRunEvent(context) ||
process.env.GITHUB_EVENT_NAME === "pull_request_target";
if (isRefusedFork && !hasRepositoryCredentials) {
core.warning(FORK_REFUSED);
return;
}
@@ -268,12 +275,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,
@@ -286,6 +287,15 @@ async function run() {
);
}
// Before the action checks anything out
if (
isRefusedFork ||
(await isCommentOnRefusedForkPr(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
+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
+2 -2
View File
@@ -68,11 +68,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,
+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 });
});
+65 -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({
@@ -198,7 +203,8 @@ describe("run.ts with allow_fork_prs: false", () => {
const { pathname } = new URL(request.url);
requests.push(pathname);
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 +237,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,
},
},
);
@@ -285,6 +291,59 @@ describe("run.ts with allow_fork_prs: false", () => {
]);
});
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("goes on with a comment on a pull request in this repository", async () => {
const result = await run(
"issue_comment",