Compare commits

..
11 Commits
Author SHA1 Message Date
GitHub Actions acfe799285 chore: bump Claude Code to 2.1.330 and Agent SDK to 0.3.330 2026-11-20 22:34:58 +00:00
3c38c04401 Use the base branch's version of files that the workflow's inputs name (#2099)
On pull requests from authors without write access, the action already
takes .claude, .mcp.json and similar files from the base branch. Do the
same for files and directories that the settings, plugin_marketplaces and
claude_args inputs name, where the pull request changes them, and keep
the session from editing them.

Co-authored-by: Claude <[email protected]>
2026-11-20 14:16:54 -08:00
GitHub Actions c84e279f85 chore: bump Claude Code to 2.1.329 and Agent SDK to 0.3.329 2026-11-19 22:15:27 +00:00
GitHub Actions f431adaf77 chore: bump Claude Code to 2.1.328 and Agent SDK to 0.3.328 2026-11-19 01:15:13 +00:00
5a85689334 Keep prompt runs to the actor's own comments and the step's output files in place (#2098)
* Don't run a prompt when someone else's comment or review is edited or deleted

docs/security.md says that editing or deleting another person's comment or review
doesn't start a run, even with a prompt. That held with track_progress only. It now
holds for every prompt. New comments and reviews run as before, and label_trigger
still doesn't apply to prompts without track_progress.

Co-authored-by: mhegazy <[email protected]>

* Keep a session from linking the step's output files elsewhere

GITHUB_OUTPUT and GITHUB_STEP_SUMMARY keep what a session writes to them, but a link
put in their place is replaced by the file from before the session, because the action
adds to them afterwards.

Co-authored-by: mhegazy <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
2026-11-18 08:47:34 -08:00
23cd101ac6 Remove the unused prepare entrypoint (#2097)
action.yml has run src/entrypoints/run.ts since #898, and nothing imports prepare.ts.

Co-authored-by: Claude <[email protected]>
2026-11-18 08:47:21 -08:00
6c3921da9b Send Bun commands in claude.yml to the safety review (#2096)
The workflow no longer lists Bun commands as allowed tools, so the review decides on
them. The system prompt says what to do when one is denied.

Co-authored-by: Claude <[email protected]>
2026-11-18 08:47:11 -08:00
e5812cd756 Add an allow_fork_prs input (#2094)
Set to "false", the action skips pull requests from forks, and workflow_run
events for a fork's run, before it checks anything out. The default keeps
today's behavior.

Co-authored-by: Claude <[email protected]>
2026-11-17 16:09:22 -08:00
47bf91ccca Skip fork pull requests in claude.yml (#2092)
In this repository, a mention on a pull request from a fork no longer starts
Claude. A first job looks up where the pull request's branch is, because the
event for a comment doesn't say.

Co-authored-by: Claude <[email protected]>
2026-11-17 16:09:18 -08:00
87ff2368a1 Apply the session's git settings to the action's own commands (#2093)
The action's own git commands now use safe.bareRepository=explicit, as the
session does. On pull requests that restrict_untrusted_prs applies to, the
checkout leaves Git LFS files that aren't downloaded yet as pointer files.

Co-authored-by: Claude <[email protected]>
2026-11-17 16:08:55 -08:00
GitHub Actions 469588f42e chore: bump Claude Code to 2.1.327 and Agent SDK to 0.3.327 2026-11-17 23:18:14 +00:00
33 changed files with 1980 additions and 198 deletions
+38 -4
View File
@@ -11,12 +11,46 @@ on:
types: [submitted]
jobs:
claude:
# In this repository Claude doesn't run on fork PRs, whatever triggers it. The event for a comment
# on a PR's conversation doesn't say where the PR's branch is, so this job asks GitHub. If it can't
# tell, Claude doesn't run.
fork-check:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
pull-requests: read
outputs:
run-claude: ${{ steps.check.outputs.run-claude }}
steps:
- name: Check that a pull request is not from a fork
id: check
shell: bash
env:
GH_TOKEN: ${{ github.token }}
# Empty on an issue
PR_NUMBER: ${{ github.event.pull_request.number || (github.event.issue.pull_request && github.event.issue.number) }}
run: |
same_repo=true
if [ -n "$PR_NUMBER" ]; then
for attempt in 1 2 3; do
same_repo=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq '.head.repo.id == .base.repo.id') && break
[ "$attempt" -lt 3 ] || exit 1
sleep 5
done
fi
if [ "$same_repo" = true ]; then
echo "run-claude=true" >> "$GITHUB_OUTPUT"
else
echo "::notice::Claude does not run on pull requests from forks in this repository."
fi
claude:
needs: fork-check
if: needs.fork-check.outputs.run-claude == 'true'
# This job calls Claude, so it runs on GitHub's egress-firewall runner, which
# filters the job's outbound network traffic (allow list: .github/egress-firewall.yaml).
runs-on: ubuntu-24.04-firewall
@@ -45,12 +79,12 @@ jobs:
# --permission-mode auto: a tool call that needs permission and that the allowed tools
# do not cover runs only if Claude Code's safety review passes it. This is also the
# action's default, and it is set here so that the workflow hardening check can see it.
# No --allowedTools, because a rule there skips the review: bun test runs whatever the workspace holds.
# --disallowedTools: of the CI tools that actions: read enables, Claude needs only the run results. A pull
# request controls the text of logs and of job and step names.
# --append-system-prompt: how to use those results where the action denies commands.
# --append-system-prompt: how to use those results where commands are denied.
claude_args: |
--allowedTools "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(bun typecheck)"
--disallowedTools "mcp__github_ci__download_job_log,mcp__github_ci__get_workflow_run_details"
--append-system-prompt "The action denies commands such as bun on pull requests whose author is not confirmed to have write access. When that happens, do not ask for changes to allowedTools. Instead call mcp__github_ci__get_ci_status and report the newest run named CI, which is ci.yml. Only a success conclusion means it passed. action_required means a maintainer has not approved it yet, and a run without a conclusion has not finished. Say that the result is for the latest commit of the pull request and not for edits you made, and that the pull request can change its own workflows, so a maintainer should check the run."
--append-system-prompt "A safety review decides whether a command such as bun test may run, and the action denies such commands on pull requests whose author is not confirmed to have write access. If one is denied, do not try the others or ask for changes to allowedTools. On an issue, say what you could not run. On a pull request, call mcp__github_ci__get_ci_status and report the newest run named CI, which is ci.yml. Only a success conclusion means it passed. action_required means a maintainer has not approved it yet, and a run without a conclusion has not finished. Say that the result is for the latest commit of the pull request and not for edits you made, and that the pull request can change its own workflows, so a maintainer should check the run."
--model "claude-opus-4-7"
--permission-mode auto
+3 -2
View File
@@ -79,7 +79,7 @@ Thank you for your interest in contributing to Claude Code Action! This document
git push origin feature/your-feature-name
```
5. Ensure all CI checks pass. On a pull request from a fork, checks usually start only after a maintainer approves them, and jobs that call Claude are skipped because forks don't get the credentials they need.
5. Ensure all CI checks pass. On a pull request from a fork, checks usually start only after a maintainer approves them, and jobs that call Claude are skipped.
6. Request review from maintainers
@@ -96,7 +96,8 @@ These steps are for pull requests from forks whose author does not have write ac
1. Review the changes, including any to workflow files and test scripts.
2. Select **Approve and run**, which starts every waiting workflow. `ci.yml` runs the tests, type check and format check. GitHub gives these runs a read-only token and no secrets. New commits can need a new approval.
3. Check the result. Jobs that call Claude, such as `claude-review.yml` and the ones in `test-*.yml`, show as skipped, which doesn't mean they passed. The `test-*.yml` jobs run on `main` after the merge.
4. If you want help, mention `@claude` in a comment on the conversation, not in a review. Claude can see whether `ci.yml` passed, but commands such as `bun` are denied. See [Running code from pull requests](./docs/security.md#running-code-from-pull-requests).
Mentioning `@claude` on a pull request from a fork does nothing in this repository: `claude.yml` skips its Claude job. Don't work around that by pushing the fork's commits to a branch here, because Claude then trusts them as yours. See [Running code from pull requests](./docs/security.md#running-code-from-pull-requests).
## Action Development
+5
View File
@@ -44,6 +44,10 @@ inputs:
only use for workflows with very limited permissions and validate all outputs.
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."
required: false
default: "true"
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
@@ -312,6 +316,7 @@ runs:
OVERRIDE_GITHUB_TOKEN: ${{ inputs.github_token }}
ALLOWED_BOTS: ${{ inputs.allowed_bots }}
ALLOWED_NON_WRITE_USERS: ${{ inputs.allowed_non_write_users }}
ALLOW_FORK_PRS: ${{ inputs.allow_fork_prs }}
RESTRICT_UNTRUSTED_PRS: ${{ inputs.restrict_untrusted_prs }}
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: ${{ env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB || (inputs.allowed_non_write_users != '' && '1') || '' }}
CLAUDE_CODE_SCRIPT_CAPS: ${{ env.CLAUDE_CODE_SCRIPT_CAPS || '' }}
+1 -1
View File
@@ -147,7 +147,7 @@ runs:
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
run: |
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
CLAUDE_CODE_VERSION="2.1.326"
CLAUDE_CODE_VERSION="2.1.330"
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
for attempt in 1 2 3; do
echo "Installation attempt $attempt..."
+10 -10
View File
@@ -6,7 +6,7 @@
"name": "@anthropic-ai/claude-code-base-action",
"dependencies": {
"@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.326",
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
"shell-quote": "^1.8.4",
},
"devDependencies": {
@@ -27,23 +27,23 @@
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]26", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.326", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.326", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.326", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.326", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.326", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.326", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.326", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.326" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-BUTSky/4YWfL/MxC+4kV0NDbJFjbJPoQMFEk/s9G6hV9LUfYPMbsWz94bFQ7ZIo2ubj2xwJ2c2NVxkNlQhVw+Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]30", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.330" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-7om9Xus6tfkeCUCfzg6ilJuN6Z7okkEvJ0mx+ukXa/Id5U/6BGtPkOYni+3ebedwa3b9SVF7A05+ln+/9EoU/w=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]26", "", { "os": "darwin", "cpu": "arm64" }, "sha512-D3ZbowCMdKNet0YPZlsJxdJUW1t1Q8KLy1BwNd+5eilf18TlCRtWZlm8DrewFLmu/gxBK7gcsq6uysrIVbPyQg=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]30", "", { "os": "darwin", "cpu": "arm64" }, "sha512-J9nqvcfD2V90O5uoR8At66R51VYtSMKnxSmPc0S4A4F5oX1VbokcpJLXU1yVCOuTtzr/OIHjRr9nn2vKi/S6rQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]26", "", { "os": "darwin", "cpu": "x64" }, "sha512-m8K3Im2S8STdAVBrriuDZyJcnjsu/Vc3476wIOqTAefnCCdtdZ4AHcOcWxt+4KIHE5Vx1qT2qacTRrQBaVVweA=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]30", "", { "os": "darwin", "cpu": "x64" }, "sha512-woe+f9qeZYWML5fACibNyth0xMDf22riNRNDryIYuhdteh7IoWrK6zC31cC2MrZRoqDZcPVtfOLND79+iZbrLA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]26", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-nYVN8jCcH490DCXIvby7rllzQFxLzKeKClfo2u/yv7mx3ipZQv344caULL/amwZ8w8GUzYyZ8hnS6pI9goSq+A=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]30", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-2Q+kfzaoTvJv1rsyu+iR4UHDZ3nxiOfdXISk+2ydQShU9DqXNlgQAt3BdJMh0Yx4MrxB66TMphVvVQeRslwwhA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]26", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-baSsuP2/wuWujRpHjKT4WkJB5lhttqKq9jcTfY2KRtQpylbk8E5PWcct/pmwJfNCKIUoE8CD+JpmoWzsdd5Ajw=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]30", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-fXmuAEegw31v+kiBd51yn7RVhjs7Rz2lnhfx/+XJXqt5lyqR2v7Ul/U/9r1CQZKuIw8M3ms9jQqGpmKbgKndqQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]26", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-WMhDY07gk2O0E8FXTbrVYmPjSLFaYPDCPwsNueVxm6vZ7ek+lPaKuOMAxTb1K07TzSmTOexoWeX2Y9VrbVDMpw=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]30", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9w4uMdA3vNZXocwOUhivOGotXoRDxN/C/xPMkZMY9WPpKLAlj8upMZskNgPjQKlVRXhxPfNagcBijGPUH4WepA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]26", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-kK9VO3uFqNd4wgeU0Cefluam5AdPu6mvF1nn6aboGy8TA5NoxlWTmA4/AwMhK39zK1S9Q2OjeX0JtAahYlIchw=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]30", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-kooZMdp6tFwNFkDXbGoNTZMgFcPQfJVfG+gZ2qAdkk11S6MFts9ybHRLQmzUK3VrqlahH7T9fmI2mNfzYgOXkw=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]26", "", { "os": "win32", "cpu": "arm64" }, "sha512-S+Ai+HhGRVFfTDmYWRfTrdWF3b4KMsfLSThZCqRJ0WCOKOXrRShMKV1hqqHBljx/wkMDPCpY0V/9S/e6w57eGQ=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]30", "", { "os": "win32", "cpu": "arm64" }, "sha512-6jscch7vk/XBSn7mm1i6zwTeiz05q98nKrQ3HdTavQEDGvXycMcB/QxIdMrs3vrdNEjWuoxwrL1qlT1lOyAWLg=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]26", "", { "os": "win32", "cpu": "x64" }, "sha512-Yn1gZXYFuHmjHz7SpHx4TqDcRDsC8TfwWcntJdYjFzMWm+caPAp6QRqr/aTvirjqVA1D+D8Rd29xhuytpE3xTQ=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]30", "", { "os": "win32", "cpu": "x64" }, "sha512-ooThWbUXlXKTDgj2VgWBXQ/6vSOTaAbBDWPvvCGNHi20haoSkw4uPX9gczkX+HJuVTslvvLiYIfe8zleVPzi7A=="],
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
+1 -1
View File
@@ -11,7 +11,7 @@
},
"dependencies": {
"@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.326",
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
"shell-quote": "^1.8.4"
},
"devDependencies": {
+10 -10
View File
@@ -7,7 +7,7 @@
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.326",
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
@@ -37,23 +37,23 @@
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]26", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.326", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.326", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.326", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.326", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.326", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.326", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.326", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.326" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-BUTSky/4YWfL/MxC+4kV0NDbJFjbJPoQMFEk/s9G6hV9LUfYPMbsWz94bFQ7ZIo2ubj2xwJ2c2NVxkNlQhVw+Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]30", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.330" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-7om9Xus6tfkeCUCfzg6ilJuN6Z7okkEvJ0mx+ukXa/Id5U/6BGtPkOYni+3ebedwa3b9SVF7A05+ln+/9EoU/w=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]26", "", { "os": "darwin", "cpu": "arm64" }, "sha512-D3ZbowCMdKNet0YPZlsJxdJUW1t1Q8KLy1BwNd+5eilf18TlCRtWZlm8DrewFLmu/gxBK7gcsq6uysrIVbPyQg=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]30", "", { "os": "darwin", "cpu": "arm64" }, "sha512-J9nqvcfD2V90O5uoR8At66R51VYtSMKnxSmPc0S4A4F5oX1VbokcpJLXU1yVCOuTtzr/OIHjRr9nn2vKi/S6rQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]26", "", { "os": "darwin", "cpu": "x64" }, "sha512-m8K3Im2S8STdAVBrriuDZyJcnjsu/Vc3476wIOqTAefnCCdtdZ4AHcOcWxt+4KIHE5Vx1qT2qacTRrQBaVVweA=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]30", "", { "os": "darwin", "cpu": "x64" }, "sha512-woe+f9qeZYWML5fACibNyth0xMDf22riNRNDryIYuhdteh7IoWrK6zC31cC2MrZRoqDZcPVtfOLND79+iZbrLA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]26", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-nYVN8jCcH490DCXIvby7rllzQFxLzKeKClfo2u/yv7mx3ipZQv344caULL/amwZ8w8GUzYyZ8hnS6pI9goSq+A=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]30", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-2Q+kfzaoTvJv1rsyu+iR4UHDZ3nxiOfdXISk+2ydQShU9DqXNlgQAt3BdJMh0Yx4MrxB66TMphVvVQeRslwwhA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]26", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-baSsuP2/wuWujRpHjKT4WkJB5lhttqKq9jcTfY2KRtQpylbk8E5PWcct/pmwJfNCKIUoE8CD+JpmoWzsdd5Ajw=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]30", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-fXmuAEegw31v+kiBd51yn7RVhjs7Rz2lnhfx/+XJXqt5lyqR2v7Ul/U/9r1CQZKuIw8M3ms9jQqGpmKbgKndqQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]26", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-WMhDY07gk2O0E8FXTbrVYmPjSLFaYPDCPwsNueVxm6vZ7ek+lPaKuOMAxTb1K07TzSmTOexoWeX2Y9VrbVDMpw=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]30", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9w4uMdA3vNZXocwOUhivOGotXoRDxN/C/xPMkZMY9WPpKLAlj8upMZskNgPjQKlVRXhxPfNagcBijGPUH4WepA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]26", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-kK9VO3uFqNd4wgeU0Cefluam5AdPu6mvF1nn6aboGy8TA5NoxlWTmA4/AwMhK39zK1S9Q2OjeX0JtAahYlIchw=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]30", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-kooZMdp6tFwNFkDXbGoNTZMgFcPQfJVfG+gZ2qAdkk11S6MFts9ybHRLQmzUK3VrqlahH7T9fmI2mNfzYgOXkw=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]26", "", { "os": "win32", "cpu": "arm64" }, "sha512-S+Ai+HhGRVFfTDmYWRfTrdWF3b4KMsfLSThZCqRJ0WCOKOXrRShMKV1hqqHBljx/wkMDPCpY0V/9S/e6w57eGQ=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]30", "", { "os": "win32", "cpu": "arm64" }, "sha512-6jscch7vk/XBSn7mm1i6zwTeiz05q98nKrQ3HdTavQEDGvXycMcB/QxIdMrs3vrdNEjWuoxwrL1qlT1lOyAWLg=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]26", "", { "os": "win32", "cpu": "x64" }, "sha512-Yn1gZXYFuHmjHz7SpHx4TqDcRDsC8TfwWcntJdYjFzMWm+caPAp6QRqr/aTvirjqVA1D+D8Rd29xhuytpE3xTQ=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]30", "", { "os": "win32", "cpu": "x64" }, "sha512-ooThWbUXlXKTDgj2VgWBXQ/6vSOTaAbBDWPvvCGNHi20haoSkw4uPX9gczkX+HJuVTslvvLiYIfe8zleVPzi7A=="],
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
+30 -4
View File
@@ -2,7 +2,7 @@
## Access Control
- **Text From Other People**: Triggering a run does not make someone else's text a request. When a maintainer labels or assigns another person's issue, slash commands in its body do not run, but Claude still reads the body to understand the task, so review it first. A pull request's body can also start a run when a maintainer pushes to, reopens or labels it, where `track_progress` is set. Editing or deleting another person's comment or review does not start a run, even with a `prompt`.
- **Text From Other People**: Triggering a run does not make someone else's text a request. When a maintainer labels or assigns another person's issue, slash commands in its body do not run, but Claude still reads the body to understand the task, so review it first. A pull request's body can also start a run when a maintainer pushes to, reopens or labels it, where `track_progress` is set. Editing or dismissing another person's comment or review, or deleting any comment, does not start a run, even with a `prompt`.
- **Repository Access**: The action can only be triggered by users with write access to the repository. This is checked for issue, pull request, comment, and review events, and for `workflow_run` events, where both the workflow actor and the actor that started the upstream run are checked. `workflow_dispatch`, `repository_dispatch`, and `schedule` events are not checked separately — GitHub itself requires write access to dispatch a workflow, and scheduled runs have no external actor.
- **Bot User Control**: By default, GitHub Apps and bots cannot trigger this action for security reasons. Use the `allowed_bots` parameter to enable specific bots or all bots
- **⚠️ Allowed bots are not checked for repository permissions.** A bot that matches an entry does **not** need to be installed on your repository or have write access. On a **public repository**, external parties — including GitHub Apps created by anyone — may be able to trigger workflow events such as opening issues, commenting, or reviewing pull requests. If your workflow listens on those events and `allowed_bots` is set to `'*'`, any such App can invoke this action with a prompt it controls.
@@ -65,10 +65,34 @@ Everything else in the working tree — including `package.json`, lockfiles, `Ma
On pull requests from authors without write access, the action also replaces what npm and Bun read from the repository root with the base branch's version, wherever the two differ: `.npmrc`, `bunfig.toml` and tracked files in `node_modules/`. In a `package.json` whose `name`, `bin`, `directories.bin` or `workspaces` change the commands it provides, only `name`, `bin`, `directories` and `workspaces` are replaced, or the whole file if it can't be understood, including in other directories if the base branch uses workspaces. The pull request's versions are kept under `.claude-pr/` for reading, except for `node_modules/`. Claude can't edit `.npmrc`, `bunfig.toml`, `node_modules/` or, where one was replaced, `package.json` on these pull requests, in any directory. Its Bash commands start in the repository root there, because a hook runs in the session's current directory and only the root's files are replaced. The replaced files stay in the working tree for later steps in the job, and if Claude stages everything, its commit can include them, as with the paths above. `restrict_untrusted_prs: false` turns this off.
On these pull requests, files and directories in the checkout that your workflow's inputs name also come from the base branch where the pull request changes them or a `.gitattributes` that applies to them: `settings`, `plugin_marketplaces`, and in `claude_args` `--settings`, `--mcp-config`, `--plugin-dir`, `--plugin-dir-no-mcp`, `--agents`, `--project-config-root`, `--system-prompt-file`, `--append-system-prompt-file` and `--append-subagent-system-prompt-file`. The pull request's versions are kept under `.claude-pr/` for reading, and Claude can't edit what these inputs name, apart from the paths listed above. The replaced files stay in the working tree here too. A file that only the pull request has is removed. The run stops if an input names the whole repository as a plugin or marketplace, except that a marketplace at the root works if all its plugins are in subdirectories, if it names a path with `..` after another directory, or if it names files in a submodule that the pull request has at another commit. What symbolic links lead to, files that other config names, for example in a `settings.json`, and executables are not covered. Git LFS files are written as pointers.
This doesn't cover other package managers, the `.env` files and `tsconfig.json` that Bun loads, other files that a hook's own command reads, or a git command that resets the working tree during the session, so keep hooks self-contained as described above. Files that git doesn't track, such as packages an earlier step installed, stay as they are. A file that is the same link on both branches is left as a link.
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
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:
```yaml
- uses: anthropics/claude-code-action@v1
with:
allow_fork_prs: "false"
```
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.
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.
This covers what the action does with the event that started it. It doesn't cover:
- **Other steps.** A step that checks out a fork's code, such as `actions/checkout` with the head of a `pull_request_target` event, does so before the action can refuse. A step after the action still runs.
- **Events that don't name a pull request**, such as `issues`, `workflow_dispatch`, `repository_dispatch` and `schedule`. A `workflow_run` event is judged by the run right before it, so one that follows a comment's run, or another `workflow_run`, counts as yours.
- **Commands in a session.** On an issue, for example, Claude could fetch a fork's commits with commands that you allow or that auto mode's review passes, such as `git` or `gh`.
- **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.
### 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.
@@ -100,14 +124,16 @@ Job logs, and job and step names, are text the pull request controls. To turn of
Bots often open pull requests from branches in your own repository. Runs there usually need no approval and can get secrets, so these steps don't protect you in that case.
**Upgrading:** workflows that use a floating tag or branch such as `@v1` or `@main` get this behavior without changing anything. If a workflow relied on commands like `npm test` running on pull requests from outside contributors or bots, those commands are now denied, Claude's config and tool config come from your default branch or `base_branch` even if the pull request targets another branch, as described [above](#which-files-come-from-the-base-branch-on-pull-requests), and a `cd` no longer carries over to the next Bash command. The run still succeeds, so check the log for the warning. Set `restrict_untrusted_prs: false` to turn this off.
**Upgrading:** workflows that use a floating tag or branch such as `@v1` or `@main` get this behavior without changing anything. If a workflow relied on commands like `npm test` running on pull requests from outside contributors or bots, those commands are now denied, Claude's config and tool config come from your default branch or `base_branch` even if the pull request targets another branch, as described [above](#which-files-come-from-the-base-branch-on-pull-requests), Git LFS files from the pull request stay pointer files if they aren't downloaded yet, and a `cd` no longer carries over to the next Bash command. The run still succeeds, so check the log for the warning. Set `restrict_untrusted_prs: false` to turn this off.
### What a session can leave behind
Steps that run after Claude, including post steps such as `actions/checkout`'s cleanup, trust `GITHUB_ENV`, `GITHUB_PATH` and git's config files. When the session ends, the action restores those files, including config pulled in through `include.path`, to how they were before it started, and logs a warning naming any it changed. A session therefore can't pass environment variables to later steps through `GITHUB_ENV`, and `git config` changes it made, such as the upstream that `git push -u` records, don't last. Use `GITHUB_OUTPUT` or `--json-schema` to pass results on.
Steps that run after Claude, including post steps such as `actions/checkout`'s cleanup, trust `GITHUB_ENV`, `GITHUB_PATH` and git's config files. When the session ends, the action restores those files, including config pulled in through `include.path`, to how they were before it started, and logs a warning naming any it changed. A session therefore can't pass environment variables to later steps through `GITHUB_ENV`, and `git config` changes it made, such as the upstream that `git push -u` records, don't last. Use `GITHUB_OUTPUT` or `--json-schema` to pass results on. What a session writes to `GITHUB_OUTPUT` and `GITHUB_STEP_SUMMARY` is kept, unless it replaced the file with a link or something else that isn't a file.
While Claude runs, and for the action's own git commands afterwards, git ignores `core.fsmonitor`. Git hooks are off for the action's own commits after the session, and from before the checkout on pull requests that `restrict_untrusted_prs` applies to. During the session these are set in the repository's git config and by the wrapper scripts. Global git config also sets `safe.bareRepository=explicit` for the session, so git won't use a repository it finds in a folder that has no `.git`. A workflow that has Claude work in a bare repository needs to pass `--git-dir`. If a run is cancelled before it restores this, the setting stays in the global config of a self-hosted runner that keeps its home directory. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
The action's own git commands use `safe.bareRepository=explicit` too. If the action starts in a bare repository, it doesn't set this before the session, unless `restrict_untrusted_prs` applies. On pull requests that `restrict_untrusted_prs` applies to, the action also checks out the pull request with `GIT_LFS_SKIP_SMUDGE=1`, so files that Git LFS hasn't downloaded yet stay as pointer files. The variable is set for that checkout only.
Claude's wrapper scripts for `git add`, `git rm`, `git commit` and `git push` always work on the repository the action checked out, and take only a short list of flags, so `git add -f` is refused. They ignore settings from the environment: `GIT_SSH_COMMAND`, `GIT_ASKPASS`, `GIT_CONFIG_*`, any other `GIT_*` variable except the author and committer ones, `XDG_CONFIG_HOME`, and a `HOME` changed during the session. A workflow that relies on one of those, such as pushing over SSH with `GIT_SSH_COMMAND`, can allow its own command in `claude_args`, such as `Bash(git push:*)`, which gives up these protections for that workflow.
This has limits:
@@ -119,7 +145,7 @@ This has limits:
### `claude-code-action` vs `claude-code-base-action`
`claude-code-base-action` is a lower-level building block that installs and runs Claude Code with the inputs you provide. It does not perform actor permission checks, restrict commands on pull requests from outside contributors, or restore project configuration from the base ref. If you need those behaviors, use this action (`claude-code-action`). See the [base-action README](../base-action/README.md#trust-model) for details.
`claude-code-base-action` is a lower-level building block that installs and runs Claude Code with the inputs you provide. It does not perform actor permission checks, refuse pull requests from forks, restrict commands on pull requests from outside contributors, or restore project configuration from the base ref. If you need those behaviors, use this action (`claude-code-action`). See the [base-action README](../base-action/README.md#trust-model) for details.
## Pull Request Creation
+1
View File
@@ -84,6 +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` |
| `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 | "" |
+1 -1
View File
@@ -12,7 +12,7 @@
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.326",
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
+1
View File
@@ -6,6 +6,7 @@ export function collectActionInputsPresence(): string {
base_branch: "",
branch_prefix: "claude/",
allowed_bots: "",
allow_fork_prs: "true",
restrict_untrusted_prs: "true",
mode: "tag",
model: "",
-103
View File
@@ -1,103 +0,0 @@
#!/usr/bin/env bun
/**
* Prepare the Claude action by checking trigger conditions, verifying human actor,
* and creating the initial tracking comment
*/
import * as core from "@actions/core";
import { setupGitHubToken } from "../github/token";
import { checkWritePermissions } from "../github/validation/permissions";
import { createOctokit } from "../github/api/client";
import {
parseGitHubContext,
isEntityContext,
isWorkflowRunEvent,
} from "../github/context";
import { detectMode } from "../modes/detector";
import { prepareTagMode } from "../modes/tag";
import { prepareAgentMode } from "../modes/agent";
import { checkContainsTrigger } from "../github/validation/trigger";
import { collectActionInputsPresence } from "./collect-inputs";
async function run() {
try {
collectActionInputsPresence();
// Parse GitHub context first to enable mode detection
const context = parseGitHubContext();
// Auto-detect mode based on context
const modeName = detectMode(context);
console.log(
`Auto-detected mode: ${modeName} for event: ${context.eventName}`,
);
// Setup GitHub token
const githubToken = await setupGitHubToken();
const octokit = createOctokit(githubToken);
// Step 3: Check write permissions (entity contexts and workflow_run)
if (isEntityContext(context) || isWorkflowRunEvent(context)) {
// Check if github_token was provided as input (not from app)
const githubTokenProvided = !!process.env.OVERRIDE_GITHUB_TOKEN;
const hasWritePermissions = await checkWritePermissions(
octokit.rest,
context,
context.inputs.allowedNonWriteUsers,
githubTokenProvided,
);
if (!hasWritePermissions) {
throw new Error(
"Actor does not have write permissions to the repository",
);
}
}
// Check trigger conditions
const containsTrigger =
modeName === "tag"
? isEntityContext(context) && checkContainsTrigger(context)
: !!context.inputs?.prompt;
// Debug logging
console.log(`Mode: ${modeName}`);
console.log(`Context prompt: ${context.inputs?.prompt || "NO PROMPT"}`);
console.log(`Trigger result: ${containsTrigger}`);
// Set output for action.yml to check
core.setOutput("contains_trigger", containsTrigger.toString());
if (!containsTrigger) {
console.log("No trigger found, skipping remaining steps");
// Still set github_token output even when skipping
core.setOutput("github_token", githubToken);
return;
}
// Run prepare
console.log(
`Preparing with mode: ${modeName} for event: ${context.eventName}`,
);
if (modeName === "tag") {
await prepareTagMode({ context, octokit, githubToken });
} else {
await prepareAgentMode({ context, octokit, githubToken });
}
// MCP config is handled by individual modes (tag/agent) and included in their claude_args output
// Expose the GitHub token (Claude App token) as an output
core.setOutput("github_token", githubToken);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
core.setFailed(`Prepare step failed with error: ${errorMessage}`);
// Also output the clean error message for the action to capture
core.setOutput("prepare_error", errorMessage);
process.exit(1);
}
}
if (import.meta.main) {
run();
}
+48 -5
View File
@@ -16,6 +16,10 @@ import {
checkBotActorPullRequestAuthor,
checkWritePermissions,
} from "../github/validation/permissions";
import {
isCommentOnRefusedForkPr,
isRefusedForkEvent,
} from "../github/validation/fork-pr";
import { getUntrustedPrDisallowedTools } from "../github/validation/untrusted-pr";
import { createOctokit } from "../github/api/client";
import type { Octokits } from "../github/api/client";
@@ -31,7 +35,10 @@ import type { GitHubContext } from "../github/context";
import { detectMode } from "../modes/detector";
import { prepareTagMode } from "../modes/tag";
import { prepareAgentMode } from "../modes/agent";
import { checkContainsTrigger } from "../github/validation/trigger";
import {
checkContainsTrigger,
isModeration,
} from "../github/validation/trigger";
import {
clearSessionState,
disableGitPrograms,
@@ -49,6 +56,10 @@ import {
restoreToolConfigFromBase,
toolConfigDenyRules,
} from "../github/operations/tool-config";
import {
namedConfigPaths,
restoreConfigPathsFromBase,
} from "../github/operations/config-paths";
import { validateBranchName } from "../github/operations/branch";
import type { BranchInfo } from "../github/operations/branch";
import { collectActionInputsPresence } from "./collect-inputs";
@@ -98,7 +109,7 @@ async function installClaudeCode(): Promise<string> {
return customExecutable;
}
const claudeCodeVersion = "2.1.326";
const claudeCodeVersion = "2.1.330";
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
for (let attempt = 1; attempt <= 3; attempt++) {
@@ -168,6 +179,9 @@ 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.";
async function run() {
// Bun has read this by now, and it's only for the action's own scripts
delete process.env.BUN_RUNTIME_TRANSPILER_CACHE_PATH;
@@ -192,6 +206,13 @@ async function run() {
// Phase 1: Prepare
const actionInputsPresent = collectActionInputsPresence();
context = parseGitHubContext();
// Before a token, which GitHub doesn't give to some of these events
if (isRefusedForkEvent(context)) {
core.warning(FORK_REFUSED);
return;
}
const modeName = detectMode(context);
console.log(
`Auto-detected mode: ${modeName} for event: ${context.eventName}`,
@@ -235,7 +256,8 @@ async function run() {
const containsTrigger =
modeName === "tag"
? isEntityContext(context) && checkContainsTrigger(context)
: !!context.inputs?.prompt;
: !!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}`);
@@ -246,6 +268,12 @@ 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,
@@ -274,7 +302,12 @@ async function run() {
);
const prepareResult =
modeName === "tag"
? await prepareTagMode({ context, octokit, githubToken })
? await prepareTagMode({
context,
octokit,
githubToken,
skipLfsDownloads: hooksOff,
})
: await prepareAgentMode({ context, octokit, githubToken });
commentId = prepareResult.commentId;
@@ -303,6 +336,7 @@ async function run() {
const isUntrustedCheckout =
checkedOutPrHead && untrustedPrDisallowedTools.length > 0;
let restoredToolConfig: string[] = [];
let configPathDenyRules: string[] = [];
// On PRs, .claude/ and .mcp.json in the checkout are attacker-controlled.
// Restore them from a trusted branch before the CLI reads them.
@@ -344,7 +378,15 @@ async function run() {
// Before plugins are installed, which can already start package managers here.
if (isUntrustedCheckout) {
restoredToolConfig = restoreToolConfigFromBase(configBranch);
restoredConfigPaths.push(...restoredToolConfig);
const configPaths = restoreConfigPathsFromBase(
configBranch,
namedConfigPaths(prepareResult.claudeArgs),
);
configPathDenyRules = configPaths.denyRules;
restoredConfigPaths.push(
...restoredToolConfig,
...configPaths.replaced,
);
}
if (isOtherBranch) {
// A branch from the base has none of the pull request's version of them.
@@ -378,6 +420,7 @@ async function run() {
? [
...untrustedPrDisallowedTools,
...toolConfigDenyRules(restoredToolConfig),
...configPathDenyRules,
]
: [];
+1 -1
View File
@@ -37,7 +37,7 @@ export async function checkAndCommitOrDeleteBranch(
// .claude/settings.json. Excluding those there would silently drop the work.
const pathspecArgs =
restoredConfigPaths.length > 0
? ["--", ".", ...restoredConfigPaths.map((p) => `:(exclude)${p}`)]
? ["--", ".", ...restoredConfigPaths.map((p) => `:(exclude,literal)${p}`)]
: [];
if (pathspecArgs.length > 0) {
+17 -4
View File
@@ -16,6 +16,7 @@ import type { Octokits } from "../api/client";
import type { FetchDataResult } from "../data/fetcher";
import { generateBranchName } from "../../utils/branch-template";
import { fetchDepthArgs } from "./fetch-depth";
import { forksAllowed } from "../validation/fork-pr";
/**
* Extracts the first label from GitHub data, or returns undefined if no labels exist
@@ -144,8 +145,8 @@ export function validateBranchName(branchName: string): void {
*
* @param args - Git command arguments (e.g., ["checkout", "branch-name"])
*/
function execGit(args: string[]): void {
execFileSync("git", args, { stdio: "inherit", env: process.env });
function execGit(args: string[], env: NodeJS.ProcessEnv = process.env): void {
execFileSync("git", args, { stdio: "inherit", env });
}
export type BranchInfo = {
@@ -160,7 +161,8 @@ export async function setupBranch(
octokits: Octokits,
githubData: FetchDataResult,
context: ParsedGitHubContext,
triggerTime?: string,
triggerTime: string | undefined,
skipLfsDownloads: boolean,
): Promise<BranchInfo> {
const { owner, repo } = context.repository;
const entityNumber = context.entityNumber;
@@ -178,6 +180,11 @@ export async function setupBranch(
);
// Fall through to create a new branch like we do for issues
} else {
// run.ts has skipped these already.
if (prData.isCrossRepository && !forksAllowed()) {
throw new Error(`PR #${entityNumber} is from a fork`);
}
// Handle open PR: Checkout the PR branch
console.log("This is an open PR, checking out PR branch...");
@@ -241,7 +248,13 @@ export async function setupBranch(
: branchName;
console.log(`PR #${entityNumber}: pinning ${localBranch} to ${headSha}`);
execGit(["fetch", "origin", ...depthArgs, headSha]);
execGit(["checkout", "-B", localBranch, headSha, "--"]);
execGit(
["checkout", "-B", localBranch, headSha, "--"],
// Files that Git LFS would download stay as pointer files.
skipLfsDownloads
? { ...process.env, GIT_LFS_SKIP_SMUDGE: "1" }
: process.env,
);
const checkedOut = execFileSync("git", ["rev-parse", "HEAD"], {
encoding: "utf8",
+381
View File
@@ -0,0 +1,381 @@
import * as core from "@actions/core";
import { mkdirSync, symlinkSync, writeFileSync } from "fs";
import { isAbsolute, posix, relative, resolve, sep } from "path";
import {
ACCUMULATE_DELIMITER,
parseClaudeArgsToExtraArgs,
} from "../../../base-action/src/parse-sdk-options";
import { SENSITIVE_PATHS } from "./restore-config";
import {
fold,
fsPath,
git,
hasRealParents,
isFile,
isLink,
isSubmodule,
onDisk,
readBlobs,
remove,
snapshotForReview,
} from "./tool-config";
import type { Entry } from "./tool-config";
// The arguments that name config in files.
const FILE_FLAGS = new Set([
"agents",
"append-subagent-system-prompt-file",
"append-system-prompt-file",
"mcp-config",
"plugin-dir",
"plugin-dir-no-mcp",
"settings",
"system-prompt-file",
]);
// Only the project's config in this directory.
const PROJECT_FLAG = "project-config-root";
const MARKETPLACE_FILE = ".claude-plugin/marketplace.json";
// Git's entries by path, relative to the working directory. As in tool-config.ts,
// Latin-1 characters stand for bytes.
type Entries = Map<string, Entry>;
const toBytes = (path: string): string => Buffer.from(path).toString("latin1");
const toText = (path: string): string => fsPath(path).toString();
const isSameOrInside = (path: string, parent: string): boolean =>
path === parent || path.startsWith(`${parent}/`);
const isSensitive = (path: string): boolean =>
SENSITIVE_PATHS.some((sensitive) => isSameOrInside(path, sensitive));
// Each is "<mode> <other fields>\t<path>".
function parseEntries(listing: Buffer, oidField: number): Entries {
const entries: Entries = new Map();
for (const line of listing.toString("latin1").split("\0")) {
const [info, path] = line.split(/\t(.*)/s);
if (!info || !path) continue;
const fields = info.split(" ");
entries.set(path, { mode: fields[0]!, oid: fields[oidField]! });
}
return entries;
}
/**
* A path as it is relative to the checkout, or undefined if it's outside. Links are not
* followed, because the pull request can change them. The workspace can have another
* name than the working directory, which is free of links.
*/
function inCheckout(path: string): string | undefined {
const roots = [process.cwd(), process.env.GITHUB_WORKSPACE || process.cwd()];
for (const root of roots) {
const inRoot = relative(root, resolve(path));
if (!isAbsolute(inRoot) && inRoot.split(sep)[0] !== "..") {
return toBytes(inRoot.split(sep).join("/"));
}
}
return undefined;
}
function isJson(value: string): boolean {
if (!value.startsWith("{")) return false;
try {
JSON.parse(value);
return true;
} catch {
return false;
}
}
const WHOLE_REPOSITORY =
"The workflow takes a plugin from the whole repository, which can't come from a trusted branch on a pull request from an author without write access. Put the plugin in a subdirectory, or set restrict_untrusted_prs to false.";
const UNCLEAR_PATH =
'A path in the workflow\'s inputs has ".." after another name, so it can\'t come from a trusted branch on a pull request from an author without write access. Write it without "..", or set restrict_untrusted_prs to false.';
const OTHER_SUBMODULE =
"The pull request and the trusted branch have different commits of a submodule that the workflow's inputs name, so that branch's version can't be used. Bring the pull request up to date, put the files in the repository, or set restrict_untrusted_prs to false.";
class PathError extends Error {}
/**
* Whether a path has ".." after a name in the checkout, which the pull request could
* make a link.
*/
function goesBack(path: string): boolean {
const parts = path.split(/[\\/]/);
return parts.some(
(part, index) =>
part === ".." && !!inCheckout(parts.slice(0, index).join("/") || "/"),
);
}
type NamedPaths = { paths: string[]; marketplaces: string[] };
/** The paths in this checkout that the workflow's inputs name as config. */
export function namedConfigPaths(claudeArgs: string): NamedPaths {
const args = Object.entries(parseClaudeArgsToExtraArgs(claudeArgs)).flatMap(
([key, value]) => {
const [flag, inlineValue] = key.split(/=(.*)/s);
return [...(value?.split(ACCUMULATE_DELIMITER) ?? []), inlineValue ?? ""]
.map((path) => path.trim())
.flatMap((path) => (path ? [{ flag: flag!, path }] : []));
},
);
const fromArgs = args.flatMap(({ flag, path }) =>
flag === PROJECT_FLAG
? SENSITIVE_PATHS.map((name) => `${path}/${name}`)
: FILE_FLAGS.has(flag)
? [path]
: [],
);
const toPaths = (values: string[]): string[] =>
values
.map((value) => value.trim())
.filter((value) => value && !isJson(value))
.flatMap((value) => {
if (goesBack(value)) throw new PathError(UNCLEAR_PATH);
const path = inCheckout(value);
return path === undefined ? [] : [path];
});
return {
paths: toPaths([process.env.INPUT_SETTINGS ?? "", ...fromArgs]),
marketplaces: toPaths(
(process.env.INPUT_PLUGIN_MARKETPLACES ?? "")
.split("\n")
.filter((entry) => /^\s*((\.\.?)?\/|[a-z]:[\\/])/i.test(entry)),
),
};
}
type RestoredPaths = { replaced: string[]; denyRules: string[] };
/**
* On a pull request from an author without write access, takes the files that the
* workflow's inputs name from the base branch. Links are restored but not followed. Only
* files that the pull request changes, or whose .gitattributes it changes, are replaced,
* so what an earlier step created or changed stays. restoreConfigFromBase must run
* first, because it fetches the base branch. Like it, this changes the working tree and
* not the index.
*
* @returns The paths that were replaced, all named by the base branch or the workflow,
* and rules that stop a session from editing these and the rest of that config.
* @throws If the base branch's version can't be put in place.
*/
export function restoreConfigPathsFromBase(
baseBranch: string,
named: NamedPaths,
): RestoredPaths {
if (named.paths.length + named.marketplaces.length === 0) {
return { replaced: [], denyRules: [] };
}
let restored: RestoredPaths;
try {
restored = restoreConfigPaths(`refs/remotes/origin/${baseBranch}`, named);
} catch (error) {
if (error instanceof PathError) throw error;
const { code, status } = error as { code?: string; status?: number };
core.warning(
`Could not replace config files (${code ?? `exit code ${status ?? "unknown"}`})`,
);
throw new Error(
"Could not use the trusted branch's version of the files that the workflow's inputs name",
);
}
if (restored.replaced.length > 0) {
core.warning(
`The pull request and ${baseBranch} differ in files that the workflow's inputs name (${restored.replaced.join(", ")}), so that branch's version is used and Claude can't edit it. See docs/security.md.`,
);
}
return restored;
}
function restoreConfigPaths(ref: string, named: NamedPaths): RestoredPaths {
const base = parseEntries(git(["ls-tree", "-r", "-z", ref]), 2);
const pr = parseEntries(git(["ls-files", "--stage", "-z"]), 1);
// The rest of Claude's config has been restored already.
const targets = [
...named.paths,
...named.marketplaces.flatMap((path) => marketplacePaths(path, base)),
]
.map((path) => posix.join(path || ".").replace(/\/$/, ""))
.filter((path) => !isSameOrInside(path, "..") && !isSensitive(path));
if (targets.includes(".")) throw new PathError(WHOLE_REPOSITORY);
const replaced = replaceFiles([...new Set(targets)], base, pr).map(toText);
return {
replaced,
denyRules: [...new Set([...targets.map(toText), ...replaced])]
.map((path) => path.replace(/[\\*?[\]]/g, "\\$&"))
.flatMap((path) => [`Edit(./${path})`, `Edit(./${path}/**)`]),
};
}
/**
* What a local marketplace is made of. One at the root of the repository has only its
* own plugins in other directories.
*/
function marketplacePaths(path: string, base: Entries): string[] {
const isManifest = path.endsWith(".json");
// The CLI takes the directory above the manifest's as the marketplace's root.
if (isManifest && !path.includes("/")) return [path];
const root = isManifest
? posix.join(posix.dirname(path), "..")
: path === ""
? "."
: path;
if (root !== ".") return [root];
const manifest = isManifest ? path : MARKETPLACE_FILE;
const own = isManifest ? path : posix.dirname(MARKETPLACE_FILE);
const entry = base.get(manifest);
// Without one that the base branch has, there is nothing to take plugins from.
if (!entry || !isFile(entry)) return [own];
const { plugins, metadata } = JSON.parse(
readBlobs([entry])
.get(entry.oid)!
.toString()
.replace(/^\uFEFF/, ""),
) as {
plugins?: ({ source?: unknown } | null)[];
metadata?: { pluginRoot?: unknown };
};
const pluginRoot =
typeof metadata?.pluginRoot === "string" ? metadata.pluginRoot : "";
const sources = (plugins ?? []).flatMap((plugin) =>
typeof plugin?.source === "string" ? [plugin.source] : [],
);
return [
own,
...sources.flatMap((source) =>
// A bare name can be in the marketplace's plugin root.
[source, ...(pluginRoot ? [posix.join(pluginRoot, source)] : [])].map(
(dir) => toBytes(posix.join(".", dir)),
),
),
];
}
/**
* Whether a path that differs from a target at most in case, or in how a character is
* encoded, is in it or above it on this file system.
*/
function namesSameFile(name: string, target: string): boolean {
const names = name.split("/");
const targets = target.split("/");
const spelled = [
...targets.slice(0, names.length),
...names.slice(targets.length),
].join("/");
if (name === spelled) return true;
const [stats, other] = [onDisk(name), onDisk(spelled)];
return !!stats && !!other && stats.ino === other.ino;
}
/** The directories whose .gitattributes the pull request changes, ignoring case. */
function changedAttributes(base: Entries, pr: Entries): string[] {
const names = new Set([...base.keys(), ...pr.keys()]);
return [...names].flatMap((name) =>
fold(posix.basename(name)) === ".gitattributes" &&
base.get(name)?.oid !== pr.get(name)?.oid
? [fold(posix.dirname(name))]
: [],
);
}
const isInside = (name: string, foldedDir: string): boolean =>
foldedDir === "." || fold(name).startsWith(`${foldedDir}/`);
/** Puts the base branch's version of these paths in place. Returns those that differed. */
function replaceFiles(targets: string[], base: Entries, pr: Entries): string[] {
const foldedPr = [...pr.keys()].map((name) => [name, fold(name)] as const);
const namesByTarget = new Map(
targets.map((target) => {
const folded = fold(target);
const names = [
...[...base.keys()].filter(
(name) =>
isSameOrInside(name, target) || isSameOrInside(target, name),
),
// A pull request can also have a file or link where the base branch has a
// directory.
...foldedPr.flatMap(([name, other]) =>
(isSameOrInside(other, folded) || isSameOrInside(folded, other)) &&
namesSameFile(name, target)
? [name]
: [],
),
];
return [target, [...new Set(names)]] as const;
}),
);
const attributes = changedAttributes(base, pr);
const differs = (name: string): boolean => {
const [ours, theirs] = [base.get(name), pr.get(name)];
return (
ours?.oid !== theirs?.oid ||
ours?.mode !== theirs?.mode ||
// Git can write even an unchanged file differently then.
(isFile(theirs!) && attributes.some((dir) => isInside(name, dir)))
);
};
const differing = [...namesByTarget].flatMap(([target, names]) => {
// Names that differ only in case can be the same file.
const folded = new Set(names.filter(differs).map(fold));
const changed = names.filter((name) => folded.has(fold(name)));
return changed.length > 0 ? [[target, changed] as const] : [];
});
const changed = [...new Set(differing.flatMap(([, names]) => names))];
// Claude Code goes on without a plugin that is missing.
if (changed.some((name) => base.has(name) && isSubmodule(base.get(name)!))) {
throw new PathError(OTHER_SUBMODULE);
}
// All of these go before anything is written. A directory where the pull request has
// a file or link came from an earlier step.
const removed = new Set(
changed.filter((name) => {
const entry = pr.get(name);
const stats = entry && onDisk(name);
return (
stats &&
(!stats.isDirectory() || isSubmodule(entry)) &&
hasRealParents(name)
);
}),
);
for (const name of removed) {
const entry = pr.get(name)!;
if (entry.oid !== base.get(name)?.oid) snapshotForReview(name, entry);
remove(name);
}
// One that the pull request has but is not on disk was left out or deleted by the
// workflow. What is on disk now came from an earlier step.
const toWrite = changed.flatMap((name) => {
const entry = base.get(name);
const wanted = pr.has(name) ? removed.has(name) : true;
return entry && !isSubmodule(entry) && wanted && !onDisk(name)
? [{ name, entry }]
: [];
});
const blobs = readBlobs(toWrite.map(({ entry }) => entry));
for (const { name, entry } of toWrite) {
if (!hasRealParents(name)) continue;
const content = blobs.get(entry.oid);
if (!content) throw new Error("missing object");
mkdirSync(fsPath(posix.dirname(name)), { recursive: true });
if (isLink(entry)) symlinkSync(content, fsPath(name));
else {
const mode = entry.mode === "100755" ? 0o755 : 0o644;
writeFileSync(fsPath(name), content, { mode, flag: "wx" });
}
}
// Where the pull request has a file above a target, that is gone too.
return [
...new Set(
differing.flatMap(([target, names]) => [
target,
...names.filter((name) => target.startsWith(`${name}/`)),
]),
),
];
}
+50 -9
View File
@@ -16,7 +16,8 @@ import {
import { homedir } from "os";
import { dirname, isAbsolute, join, resolve } from "path";
type TrackedFile = { label: string; path: string };
// A session may write to one that keeps its writes, but not put a link in its place.
type TrackedFile = { label: string; path: string; keepsWrites?: boolean };
// "opaque" is anything that can't be saved and compared: a directory, a FIFO, a
// device, a file too large to hold, or one that can't be read.
@@ -25,6 +26,7 @@ type FileSnapshot = TrackedFile & {
wasSymlink: boolean;
content?: Buffer;
mode?: number;
names?: number;
// For a symlink: what it points to, and the regular file that ends up at.
link?: { target: string; resolved: string };
};
@@ -38,6 +40,11 @@ const SESSION_STATE_FILES = [
".restored-paths",
];
const NO_IMPLICIT_BARE_REPOSITORY: [string, string] = [
"safe.bareRepository",
"explicit",
];
// How many GIT_CONFIG_* entries were there before disableGitPrograms added any.
let entriesBeforeAction: number | undefined;
@@ -116,8 +123,15 @@ function filesLaterStepsTrust(): TrackedFile[] {
path ? [{ label, path }] : [],
);
// The action adds to these after the session, so a link there would redirect that to
// a file later steps trust.
const written = ["GITHUB_OUTPUT", "GITHUB_STEP_SUMMARY"].flatMap((label) => {
const path = process.env[label];
return path ? [{ label, path, keepsWrites: true }] : [];
});
const seen = new Set<string>();
return [...named, ...gitConfigFilesInUse()].filter(({ path }) => {
return [...named, ...gitConfigFilesInUse(), ...written].filter(({ path }) => {
const absolute = resolve(path);
if (seen.has(absolute)) return false;
seen.add(absolute);
@@ -147,6 +161,7 @@ function readSnapshot(file: TrackedFile): FileSnapshot {
wasSymlink,
content: readFileSync(fd),
mode: stats.mode & 0o777,
names: stats.nlink,
...(wasSymlink && {
link: {
target: readlinkSync(file.path),
@@ -185,6 +200,19 @@ function restorePath(before: FileSnapshot): string {
}
}
/**
* Whether what is written to a file now ends up in that file and no other. A new name
* for a file that later steps trust is as good as a symlink to it.
*/
function isItsOwnFile(before: FileSnapshot): boolean {
try {
const stats = lstatSync(restorePath(before));
return stats.isFile() && stats.nlink <= (before.names ?? 1);
} catch {
return false;
}
}
/**
* Records the files later steps trust, and returns a function that puts them
* back. Call the returned function as soon as the session ends and before the
@@ -207,8 +235,12 @@ export function snapshotSessionFiles(beforeSession?: () => void): () => void {
for (const [index, before] of snapshots.entries()) {
try {
const now = readSnapshot(before);
if (isUnchanged(before, now)) continue;
const changedBySession = !isUnchanged(atStart[index]!, now);
if (before.keepsWrites && isItsOwnFile(before)) continue;
// The file it leads to can have the same content so far.
const leadsElsewhere = before.keepsWrites && now.state === "file";
if (!leadsElsewhere && isUnchanged(before, now)) continue;
const changedBySession =
leadsElsewhere || !isUnchanged(atStart[index]!, now);
if (before.state === "opaque") {
core.warning(
`Could not restore ${before.label} after the session: it was not a regular file before`,
@@ -251,7 +283,14 @@ export function disableGitPrograms({ hooks }: { hooks: boolean }): void {
process.env[`GIT_CONFIG_VALUE_${i}`],
);
}
for (const [key, value] of gitProgramSettings({ hooks })) {
const settings = gitProgramSettings({ hooks });
// A workflow may run the action in a bare repository, where this setting would stop git.
const setting = NO_IMPLICIT_BARE_REPOSITORY.join("=");
const stopsGit =
gitOutput("rev-parse", "--git-dir") !== null &&
gitOutput("-c", setting, "rev-parse", "--git-dir") === null;
if (hooks || !stopsGit) settings.push(NO_IMPLICIT_BARE_REPOSITORY);
for (const [key, value] of settings) {
if (current.get(key) === value) continue;
process.env[`GIT_CONFIG_KEY_${count}`] = key;
process.env[`GIT_CONFIG_VALUE_${count}`] = value;
@@ -290,7 +329,9 @@ export function pinPushBranch(branch: string): void {
export function pinRestoredPaths(paths: string[]): void {
const pathspecs = paths.map((path) =>
// Its commands are replaced in subdirectories too.
path === "package.json" ? ":(top,glob)**/package.json" : `:(top)${path}`,
path === "package.json"
? ":(top,glob)**/package.json"
: `:(top,literal)${path}`,
);
try {
writeSessionFile(".restored-paths", `${pathspecs.join("\n")}\n`);
@@ -330,8 +371,8 @@ const gitOutput = (...args: string[]): string | null => {
* Moves the settings from disableGitPrograms out of the environment for the session.
* Repository config and the wrappers keep them in force instead, and
* snapshotSessionFiles puts the config back afterwards. Elsewhere the concern is a
* repository git finds in a plain folder, with its own config. Git only reads
* safe.bareRepository from global config or the command line.
* repository git finds in a plain folder, with its own config. Git ignores
* safe.bareRepository in repository config, so the session gets it from global config.
*/
export function prepareGitForSession({ hooks }: { hooks: boolean }): void {
const count = Number.parseInt(process.env.GIT_CONFIG_COUNT ?? "", 10) || 0;
@@ -356,7 +397,7 @@ export function prepareGitForSession({ hooks }: { hooks: boolean }): void {
const gitDir = gitOutput("rev-parse", "--absolute-git-dir");
const workTree = gitDir && gitOutput("rev-parse", "--show-toplevel");
if (gitDir) setConfig("--local", gitProgramSettings({ hooks }));
setConfig("--global", [["safe.bareRepository", "explicit"]]);
setConfig("--global", [NO_IMPLICIT_BARE_REPOSITORY]);
try {
if (hooks) writeSessionFile(".no-hooks", "");
+12 -12
View File
@@ -32,14 +32,14 @@ const ENCODING = "working-tree-encoding";
const MAX_OUTPUT_BYTES = 1024 ** 3;
const MAX_PACKAGE_JSON_BYTES = 4 * 1024 * 1024;
type Entry = { mode: string; oid: string };
export type Entry = { mode: string; oid: string };
type Replacement = { path: string; entry: Entry; content?: Buffer };
// File names can be any bytes. Latin-1 keeps each one intact.
const fsPath = (path: string): Buffer => Buffer.from(path, "latin1");
const isFile = (entry: Entry): boolean => entry.mode.startsWith("100");
const isLink = (entry: Entry): boolean => entry.mode === "120000";
const isSubmodule = (entry: Entry): boolean => entry.mode === "160000";
export const fsPath = (path: string): Buffer => Buffer.from(path, "latin1");
export const isFile = (entry: Entry): boolean => entry.mode.startsWith("100");
export const isLink = (entry: Entry): boolean => entry.mode === "120000";
export const isSubmodule = (entry: Entry): boolean => entry.mode === "160000";
// No file name or content, which the pull request controls, reaches the log.
function warn(what: string, error: unknown): void {
@@ -47,7 +47,7 @@ function warn(what: string, error: unknown): void {
core.warning(`${what} (${code ?? `exit code ${status ?? "unknown"}`})`);
}
function git(args: string[], input: string | Buffer = ""): Buffer {
export function git(args: string[], input: string | Buffer = ""): Buffer {
return execFileSync("git", args, {
stdio: ["pipe", "pipe", "ignore"],
input,
@@ -57,7 +57,7 @@ function git(args: string[], input: string | Buffer = ""): Buffer {
}
// A parent that is a file or a looping link means there is nothing there.
function onDisk(path: string) {
export function onDisk(path: string) {
try {
return lstatSync(fsPath(path));
} catch {
@@ -66,7 +66,7 @@ function onDisk(path: string) {
}
// File systems can ignore case, and some the way a character is encoded.
const fold = (path: string): string =>
export const fold = (path: string): string =>
fsPath(path).toString().normalize("NFKC").toLowerCase();
/**
@@ -97,14 +97,14 @@ function rootName(path: string): string | undefined {
}
/** Whether no parent of a path is a link, which could lead out of the checkout. */
function hasRealParents(path: string): boolean {
export function hasRealParents(path: string): boolean {
for (let dir = dirname(path); dir !== "."; dir = dirname(dir)) {
if (onDisk(dir)?.isSymbolicLink()) return false;
}
return true;
}
function remove(path: string): void {
export function remove(path: string): void {
rmSync(fsPath(path), { recursive: true, force: true });
// An empty directory would stand in the way of a file of that name.
try {
@@ -150,7 +150,7 @@ function baseEntries(baseBranch: string): Map<string, Entry> {
}
/** The stored content of each entry, which no .gitattributes has been applied to. */
function readBlobs(entries: Entry[]): Map<string, Buffer> {
export function readBlobs(entries: Entry[]): Map<string, Buffer> {
const blobs = new Map<string, Buffer>();
const oids = [...new Set(entries.map(({ oid }) => oid))];
if (oids.length === 0) return blobs;
@@ -282,7 +282,7 @@ function withBaseCommands(
}
/** Keeps the pull request's version readable, as for the other restored config. */
function snapshotForReview(path: string, entry: Entry): void {
export function snapshotForReview(path: string, entry: Entry): void {
if (!isFile(entry) || rootName(path) === "node_modules") return;
try {
const content = git(["cat-file", "blob", entry.oid]);
+78
View File
@@ -0,0 +1,78 @@
import type { Octokit } from "@octokit/rest";
import { retryWithBackoff } from "../../utils/retry";
import { toLookupError, type LookupError } from "./untrusted-pr";
import {
isEntityContext,
isWorkflowRunEvent,
type GitHubContext,
} from "../context";
type Repository = { id?: number } | null | undefined;
// A deleted fork has no repository.
const isSameRepository = (head: Repository, base: Repository): boolean =>
typeof head?.id === "number" && head.id === base?.id;
// 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";
/**
* Whether allow_fork_prs is off and the event says that it is about a fork's pull
* request, or follows a workflow run of a fork's code. Needs no token. A comment on
* a pull request's conversation doesn't say: see isCommentOnRefusedForkPr.
*/
export function isRefusedForkEvent(context: GitHubContext): boolean {
if (forksAllowed()) return false;
if (isWorkflowRunEvent(context)) {
const { workflow_run: run, repository } = context.payload;
return !isSameRepository(run?.head_repository, repository);
}
if (isEntityContext(context) && "pull_request" in context.payload) {
const { head, base } = context.payload.pull_request;
return !isSameRepository(head.repo, base.repo);
}
return false;
}
/**
* Whether allow_fork_prs is off and the event is a comment on the conversation of a
* fork's pull request. Throws if that can't be found out.
*/
export async function isCommentOnRefusedForkPr(
octokit: Octokit,
context: GitHubContext,
): Promise<boolean> {
if (
forksAllowed() ||
!isEntityContext(context) ||
!context.isPR ||
"pull_request" in context.payload
) {
return false;
}
const { owner, repo } = context.repository;
const lookUp = async () => {
try {
return await octokit.pulls.get({
owner,
repo,
pull_number: context.entityNumber,
});
} catch (error) {
throw toLookupError(error);
}
};
const { data } = await retryWithBackoff(lookUp, {
initialDelayMs: 1000,
shouldRetry: (error) => (error as LookupError).retryable,
}).catch((error: LookupError) => {
// Only the bounded text from toLookupError reaches the log.
throw new Error(
`Could not find out whether pull request #${context.entityNumber} is from a fork (${error.message}). The token needs pull-requests: read.`,
);
});
return !isSameRepository(data.head.repo, data.base.repo);
}
+25 -14
View File
@@ -1,6 +1,5 @@
#!/usr/bin/env bun
import * as core from "@actions/core";
import {
isIssuesEvent,
isIssuesAssignedEvent,
@@ -12,13 +11,11 @@ import {
import type { ParsedGitHubContext } from "../context";
import { isSameLogin } from "./actor";
export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
const {
inputs: { assigneeTrigger, labelTrigger, triggerPhrase, prompt },
} = context;
// Deleting or editing someone else's comment or review fires these events with
// the moderator as the actor. The text must come from the person who was checked.
/**
* Whether the text of a comment or review event comes from the person who was checked.
* Deleting or editing someone else's fires these events with the moderator as the actor.
*/
function isTextFromActor(context: ParsedGitHubContext): boolean {
if (
(isIssueCommentEvent(context) ||
isPullRequestReviewCommentEvent(context)) &&
@@ -35,6 +32,26 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
console.log("Review was written by someone other than the actor");
return false;
}
return true;
}
/**
* Whether a comment or review event comes from moderation, so that its text must not
* start a run. A new comment or review is always its author's own, and some apps have
* one login as its author and another as the actor.
*/
export function isModeration(context: ParsedGitHubContext): boolean {
const isNew =
context.eventAction === "created" || context.eventAction === "submitted";
return !isNew && !isTextFromActor(context);
}
export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
const {
inputs: { assigneeTrigger, labelTrigger, triggerPhrase, prompt },
} = context;
if (!isTextFromActor(context)) return false;
// A prompt replaces the trigger phrase, but a configured label or assignee
// still decides which label or assignment event starts a run. Otherwise any
@@ -195,9 +212,3 @@ function matchesAssigneeTrigger(
export function escapeRegExp(string: string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
export async function checkTriggerAction(context: ParsedGitHubContext) {
const containsTrigger = checkContainsTrigger(context);
core.setOutput("contains_trigger", containsTrigger.toString());
return containsTrigger;
}
+5 -5
View File
@@ -93,15 +93,15 @@ function getPrAuthor(context: ParsedGitHubContext): string | undefined {
return undefined;
}
type LookupError = Error & { retryable: boolean };
export type LookupError = Error & { retryable: boolean };
/**
* Reduces a failed API call to its HTTP status, so that nothing else from the
* error can reach the workflow log, and decides whether to try again. A 404 (not
* a user account) or a plain 403 won't change, but GitHub also uses 403 for rate
* limits. Whatever the outcome, a failed lookup counts as untrusted.
* error can reach the workflow log, and decides whether to try again. A 404 or a
* plain 403 won't change, but GitHub also uses 403 for rate
* limits.
*/
function toLookupError(error: unknown): LookupError {
export function toLookupError(error: unknown): LookupError {
const { status, response } = error as {
status?: number;
response?: { headers?: Record<string, string | number | undefined> };
+3
View File
@@ -40,10 +40,12 @@ export async function prepareTagMode({
context,
octokit,
githubToken,
skipLfsDownloads,
}: {
context: GitHubContext;
octokit: Octokits;
githubToken: string;
skipLfsDownloads: boolean;
}) {
// Tag mode only handles entity-based events
if (!isEntityContext(context)) {
@@ -87,6 +89,7 @@ export async function prepareTagMode({
githubData,
context,
editedAt || triggerTime,
skipLfsDownloads,
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
+11
View File
@@ -68,6 +68,17 @@ describe("action metadata", () => {
);
});
test("should allow 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,
);
expect(metadata).toMatch(
/^ ALLOW_FORK_PRS: \$\{\{ inputs\.allow_fork_prs \}\}$/m,
);
});
test("should start each of the action's scripts with the same Bun options", () => {
const commands = readMetadata("action.yml")
.replace(/\\\n\s*/g, "")
+96
View File
@@ -0,0 +1,96 @@
import { expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
const writer = { login: "writer", type: "User" };
const outsider = { login: "outsider", type: "User" };
const repository = { id: 1, name: "r", owner: { login: "o" } };
const issue = { number: 7, user: outsider };
// The directory is not a git repository, so a run that starts fails later on.
async function runWithPrompt(eventName: string, event: object) {
const dir = mkdtempSync(join(tmpdir(), "moderation-"));
const server = Bun.serve({
port: 0,
hostname: "127.0.0.1",
fetch: (request) =>
request.url.endsWith("/permission")
? Response.json({ permission: "write" })
: Response.json({}, { status: 404 }),
});
try {
for (const file of ["output", "env"]) writeFileSync(join(dir, file), "");
writeFileSync(join(dir, "event.json"), JSON.stringify(event));
const child = Bun.spawn(
[
process.execPath,
"run",
join(import.meta.dir, "../src/entrypoints/run.ts"),
],
{
cwd: dir,
stdout: "pipe",
stderr: "pipe",
env: {
PATH: process.env.PATH,
HOME: dir,
RUNNER_TEMP: dir,
GITHUB_EVENT_NAME: eventName,
GITHUB_EVENT_PATH: join(dir, "event.json"),
GITHUB_REPOSITORY: "o/r",
GITHUB_ACTOR: "writer",
GITHUB_RUN_ID: "1",
GITHUB_OUTPUT: join(dir, "output"),
GITHUB_ENV: join(dir, "env"),
GITHUB_API_URL: `http://127.0.0.1:${server.port}`,
OVERRIDE_GITHUB_TOKEN: "t",
ALLOW_FORK_PRS: "true",
PROMPT: "Respond to this",
},
},
);
const log = await new Response(child.stdout).text();
await child.exited;
return log;
} finally {
server.stop(true);
rmSync(dir, { recursive: true, force: true });
}
}
const SKIPPED = "No trigger found, skipping remaining steps";
const STARTED = "Preparing with mode: agent";
test("a prompt doesn't run when a maintainer edits or deletes someone else's comment", async () => {
for (const action of ["edited", "deleted"]) {
const log = await runWithPrompt("issue_comment", {
action,
repository,
sender: writer,
issue,
comment: { id: 1, body: "x", user: outsider },
});
expect(log).toContain(SKIPPED);
expect(log).not.toContain(STARTED);
}
});
test("a prompt runs on a new comment, and on events that have none", async () => {
const events: [string, object][] = [
[
"issue_comment",
{ action: "created", issue, comment: { id: 1, body: "x", user: writer } },
],
// With a prompt, label_trigger doesn't limit which label starts a run.
["issues", { action: "labeled", issue, label: { name: "triage" } }],
];
for (const [eventName, event] of events) {
const log = await runWithPrompt(eventName, {
repository,
sender: writer,
...event,
});
expect(log).toContain(STARTED);
}
});
+27 -2
View File
@@ -180,7 +180,10 @@ describe("in a shallow checkout of the default branch", () => {
rmSync(dir, { recursive: true, force: true });
});
const checkOutPullRequest = (isCrossRepository: boolean) =>
const checkOutPullRequest = (
isCrossRepository: boolean,
skipLfsDownloads = false,
) =>
setupBranch(
{} as any,
{
@@ -194,6 +197,8 @@ describe("in a shallow checkout of the default branch", () => {
},
} as any,
mockPullRequestCommentContext,
undefined,
skipLfsDownloads,
);
test("setupBranch says whether it checked out a fork", async () => {
@@ -201,6 +206,23 @@ describe("in a shallow checkout of the default branch", () => {
expect((await checkOutPullRequest(false)).isFork).toBe(false);
});
test.each([true, false])(
"setupBranch skips Git LFS downloads for its checkout only: %p",
async (skip) => {
const before = process.env.GIT_LFS_SKIP_SMUDGE;
delete process.env.GIT_LFS_SKIP_SMUDGE;
try {
git(".", "config", "filter.show.smudge", 'echo "$GIT_LFS_SKIP_SMUDGE"');
writeFileSync(".git/info/attributes", "change.txt filter=show\n");
await checkOutPullRequest(true, skip);
expect(readFileSync("change.txt", "utf8").trim()).toBe(skip ? "1" : "");
expect(process.env.GIT_LFS_SKIP_SMUDGE).toBeUndefined();
} finally {
if (before !== undefined) process.env.GIT_LFS_SKIP_SMUDGE = before;
}
},
);
test("the base can still be compared after restoring from another branch", async () => {
await checkOutPullRequest(true);
restoreConfigFromBase("trunk");
@@ -291,7 +313,7 @@ describe("in a shallow checkout whose history contains the config branch", () =>
);
});
test("run.ts restores both kinds of config from the chosen branch", () => {
test("run.ts restores every kind of config from the chosen branch", () => {
const source = readFileSync(
join(import.meta.dir, "../src/entrypoints/run.ts"),
"utf8",
@@ -305,5 +327,8 @@ test("run.ts restores both kinds of config from the chosen branch", () => {
expect(source).toContain("restoreHeadHistory?.();");
expect(source).toContain("pinRestoredPaths(restoredConfigPaths)");
expect(source).toContain("restoreToolConfigFromBase(configBranch)");
expect(source.replace(/\s+/g, " ")).toContain(
"restoreConfigPathsFromBase( configBranch, namedConfigPaths(prepareResult.claudeArgs), )",
);
expect(source).toContain("fetchBranch(restoreBase)");
});
+560
View File
@@ -0,0 +1,560 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import * as core from "@actions/core";
import { execFileSync } from "child_process";
import {
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
readlinkSync,
rmSync,
symlinkSync,
writeFileSync,
} from "fs";
import { tmpdir } from "os";
import { dirname, join } from "path";
import {
namedConfigPaths,
restoreConfigPathsFromBase,
} from "../src/github/operations/config-paths";
import { restoreConfigFromBase } from "../src/github/operations/restore-config";
const INPUTS = [
"INPUT_SETTINGS",
"INPUT_PLUGIN_MARKETPLACES",
"GITHUB_WORKSPACE",
];
let originalCwd: string;
let tempDir: string;
let saved: Record<string, string | undefined>;
let warningSpy: any;
const git = (...args: string[]) =>
execFileSync("git", args, { encoding: "utf8", stdio: "pipe" }).trim();
const write = (path: string, content: string) => {
mkdirSync(dirname(path), { recursive: true });
rmSync(path, { recursive: true, force: true });
writeFileSync(path, content);
};
const link = (path: string, target: string) => {
mkdirSync(dirname(path), { recursive: true });
rmSync(path, { recursive: true, force: true });
symlinkSync(target, path);
};
const read = (path: string) => readFileSync(path, "utf8");
const commit = (message: string) => {
git("add", "-A", "-f");
git("commit", "-qm", message);
};
// Commits the base branch, pushes it and starts the pull request's branch from it.
const startPr = () => {
commit("base");
git("push", "-q", "origin", "main");
git("checkout", "-qb", "pr");
};
const restoreAll = (named = { paths: [], marketplaces: [] } as any) => {
restoreConfigFromBase("main");
return restoreConfigPathsFromBase("main", named);
};
const named = (...paths: string[]) => ({ paths, marketplaces: [] as string[] });
const restore = (named?: any) => restoreAll(named).replaced;
beforeEach(() => {
originalCwd = process.cwd();
saved = Object.fromEntries(INPUTS.map((key) => [key, process.env[key]]));
INPUTS.forEach((key) => delete process.env[key]);
warningSpy = spyOn(core, "warning").mockImplementation(() => {});
tempDir = mkdtempSync(join(tmpdir(), "config-paths-"));
const remote = join(tempDir, "origin.git");
const repo = join(tempDir, "repo");
execFileSync("git", ["init", "-q", "--bare", remote]);
execFileSync("git", ["init", "-q", "-b", "main", repo]);
process.chdir(repo);
git("config", "user.email", "[email protected]");
git("config", "user.name", "Test User");
git("remote", "add", "origin", remote);
write("src/index.ts", "base\n");
});
afterEach(() => {
process.chdir(originalCwd);
warningSpy.mockRestore();
rmSync(tempDir, { recursive: true, force: true });
for (const key of INPUTS) {
if (saved[key] === undefined) delete process.env[key];
else process.env[key] = saved[key];
}
});
describe("a named directory", () => {
const inputs = () => namedConfigPaths("--plugin-dir ci/plugin");
beforeEach(() => write("ci/plugin/a.json", "base\n"));
test("is left alone if the pull request doesn't change it", () => {
startPr();
write("src/index.ts", "pr\n");
commit("pr");
expect(restore(inputs())).toEqual([]);
expect(git("status", "--porcelain")).toBe("");
expect(warningSpy).not.toHaveBeenCalled();
});
test("comes from the base branch, without what the pull request adds", () => {
startPr();
write("ci/plugin/a.json", "pr\n");
write("ci/plugin/b.json", "pr\n");
write("src/index.ts", "pr\n");
commit("pr");
write("ci/plugin/generated.json", "by an earlier step\n");
expect(restore(inputs())).toEqual(["ci/plugin"]);
expect(read("ci/plugin/a.json")).toBe("base\n");
expect(existsSync("ci/plugin/b.json")).toBe(false);
expect(read("ci/plugin/generated.json")).toBe("by an earlier step\n");
expect(read("src/index.ts")).toBe("pr\n");
expect(read(".claude-pr/ci/plugin/a.json")).toBe("pr\n");
// Nothing is staged, so a commit doesn't include it.
expect(git("diff", "--cached", "--name-only")).toBe("");
expect(warningSpy.mock.calls[0][0]).toContain("ci/plugin");
});
test.each(["ci", "ci/plugin", "ci/plugin/a.json"])(
"is put back if the pull request has a link at %s",
(path) => {
startPr();
write(join(tempDir, "outside", "keep"), "untouched\n");
rmSync(path, { recursive: true });
link(path, join(tempDir, "outside"));
commit("pr");
expect(restore(inputs()).sort()).toEqual(
path === "ci" ? ["ci", "ci/plugin"] : ["ci/plugin"],
);
expect(read("ci/plugin/a.json")).toBe("base\n");
expect(read(join(tempDir, "outside", "keep"))).toBe("untouched\n");
},
);
test("is put back if the pull request has a file in its parent's place", () => {
startPr();
rmSync("ci", { recursive: true });
write("ci", "pr\n");
commit("pr");
expect(restore(inputs()).sort()).toEqual(["ci", "ci/plugin"]);
expect(read("ci/plugin/a.json")).toBe("base\n");
});
test("is put back if the pull request makes its parent a submodule", () => {
startPr();
git("rm", "-rq", "ci");
git(
"update-index",
"--add",
"--cacheinfo",
`160000,${git("rev-parse", "HEAD")},ci`,
);
git("commit", "-qm", "pr");
mkdirSync("ci");
expect(restore(inputs()).sort()).toEqual(["ci", "ci/plugin"]);
expect(read("ci/plugin/a.json")).toBe("base\n");
});
test("keeps its own links, and loses the pull request's", () => {
link("ci/plugin/hooks", "../hooks");
startPr();
link("ci/plugin/hooks", "../evil");
link("ci/plugin/more", "../evil");
commit("pr");
expect(restore(inputs())).toEqual(["ci/plugin"]);
expect(readlinkSync("ci/plugin/hooks")).toBe("../hooks");
expect(lstatSync("ci/plugin/more", { throwIfNoEntry: false })).toBe(
undefined,
);
});
});
test("a file that an earlier step created stays", () => {
startPr();
write("generated/settings.json", "by an earlier step\n");
expect(restore(named("generated/settings.json"))).toEqual([]);
expect(read("generated/settings.json")).toBe("by an earlier step\n");
});
test("a link that the pull request puts above a missing path is removed", () => {
startPr();
write("evil/settings.json", "pr\n");
link("generated", "evil");
commit("pr");
expect(restore(named("generated/settings.json")).sort()).toEqual([
"generated",
"generated/settings.json",
]);
expect(existsSync("generated/settings.json")).toBe(false);
});
test("a submodule that the pull request moves stops the run", () => {
const add = (oid: string) =>
git("update-index", "--add", "--cacheinfo", `160000,${oid},vendor`);
commit("first");
add(git("rev-parse", "HEAD"));
git("commit", "-qm", "base");
git("push", "-q", "origin", "main");
git("checkout", "-qb", "pr");
const inputs = namedConfigPaths("--plugin-dir vendor/plugin");
expect(restore(inputs)).toEqual([]);
add(git("rev-parse", "HEAD"));
git("commit", "-qm", "pr");
expect(() => restore(inputs)).toThrow("different commits of a submodule");
});
test("the base branch's link above a named path is put back", () => {
write("tools/ci/plugin/a.json", "base\n");
link("ci", "tools/ci");
startPr();
rmSync("ci");
write("ci/plugin/a.json", "pr\n");
commit("pr");
expect(restore(named("ci/plugin")).sort()).toEqual(["ci", "ci/plugin"]);
expect(readlinkSync("ci")).toBe("tools/ci");
expect(read("ci/plugin/a.json")).toBe("base\n");
});
test.each(["working-tree-encoding=UTF-16", "text eol=crlf", "ident"])(
"a .gitattributes can't make git write a file differently: %s",
(attribute) => {
write("ci/a.sh", "base $Id$\n");
write("ci/b.sh", "base\n");
startPr();
write("ci/b.sh", "pr\n");
commit("pr");
write(".gitattributes", `*.sh ${attribute}\n`);
git("add", ".gitattributes");
git("commit", "-qm", "attributes");
rmSync("ci", { recursive: true });
git("checkout", "-q", "--", "ci");
expect(read("ci/a.sh")).not.toBe("base $Id$\n");
expect(restore(named("ci/a.sh", "ci/b.sh")).sort()).toEqual([
"ci/a.sh",
"ci/b.sh",
]);
expect(read("ci/a.sh")).toBe("base $Id$\n");
expect(read("ci/b.sh")).toBe("base\n");
},
);
test("the base branch's own .gitattributes are left alone", () => {
write("ci/a.sh", "base\n");
write(".gitattributes", "*.sh text eol=crlf\n");
write("other/.gitattributes", "");
startPr();
write("other/.gitattributes", "* text\n");
commit("pr");
rmSync("ci", { recursive: true });
git("checkout", "-q", "--", "ci");
expect(restore(named("ci/a.sh"))).toEqual([]);
expect(read("ci/a.sh")).toBe("base\r\n");
});
test("what an earlier step changed stays if the pull request doesn't change it", () => {
write("ci/plugin/dist.js", "base\n");
write("ci/plugin/a.json", "base\n");
startPr();
write("ci/plugin/a.json", "pr\n");
commit("pr");
write("ci/plugin/dist.js", "by an earlier step\n");
expect(restore(namedConfigPaths("--plugin-dir ci/plugin"))).toEqual([
"ci/plugin",
]);
expect(read("ci/plugin/dist.js")).toBe("by an earlier step\n");
expect(read("ci/plugin/a.json")).toBe("base\n");
});
test("a link that leads out of the checkout can't become a file", () => {
link("ci/mcp.json", "/opt/shared/mcp.json");
startPr();
write("ci/mcp.json", "pr\n");
commit("pr");
expect(restore(named("ci/mcp.json"))).toEqual(["ci/mcp.json"]);
expect(readlinkSync("ci/mcp.json")).toBe("/opt/shared/mcp.json");
});
test("a path can't go back through a directory", () => {
for (const path of [
"tools/../ci/s.json",
"./a/b/../../s.json",
"a/./../s",
"tools/../../shared/s.json",
join(process.cwd(), "tools") + "/../s.json",
]) {
process.env.INPUT_SETTINGS = path;
expect(() => namedConfigPaths("")).toThrow('Write it without ".."');
}
for (const path of [
"./ci/..s.json",
"a..b/s",
"../outside/../s.json",
process.cwd() + "/../s.json",
]) {
process.env.INPUT_SETTINGS = path;
namedConfigPaths("");
}
});
test("a name that differs in case is another file where the file system says so", () => {
write("docs/guide.md", "base\n");
write("Docs/guide.md/readme", "base\n");
const isCaseSensitive = read("docs/guide.md") === "base\n";
startPr();
if (!isCaseSensitive) return;
write("Docs/guide.md/readme", "pr\n");
commit("pr");
expect(restore(named("docs/guide.md"))).toEqual([]);
expect(read("Docs/guide.md/readme")).toBe("pr\n");
});
test("names with glob characters are literal in the rules", () => {
write("plugins/[ci]/x", "base\n");
startPr();
write("plugins/[ci]/x", "pr\n");
commit("pr");
expect(
restoreAll(namedConfigPaths("--plugin-dir 'plugins/[ci]'")).denyRules,
).toEqual(["Edit(./plugins/\\[ci\\])", "Edit(./plugins/\\[ci\\]/**)"]);
});
test("a workspace reached through a link is the same checkout", () => {
write("ci/mcp.json", "base\n");
const workspace = join(tempDir, "workspace");
symlinkSync(process.cwd(), workspace);
process.env.GITHUB_WORKSPACE = workspace;
startPr();
write("ci/mcp.json", "pr\n");
commit("pr");
expect(
restore(namedConfigPaths(`--mcp-config ${workspace}/ci/mcp.json`)),
).toEqual(["ci/mcp.json"]);
expect(read("ci/mcp.json")).toBe("base\n");
});
test("a session can't edit what the inputs name, changed or not", () => {
write("ci/plugin/check.sh", "base\n");
write("ci/s.json", "base\n");
startPr();
write("ci/s.json", "pr\n");
commit("pr");
const { replaced, denyRules } = restoreAll(
namedConfigPaths("--plugin-dir ci/plugin --settings ci/s.json"),
);
expect(replaced).toEqual(["ci/s.json"]);
expect(denyRules.sort()).toEqual([
"Edit(./ci/plugin)",
"Edit(./ci/plugin/**)",
"Edit(./ci/s.json)",
"Edit(./ci/s.json/**)",
]);
});
test("what nothing names stays, also if Claude's config links to it", () => {
write("docs/guide.md", "base\n");
link("CLAUDE.md", "docs/guide.md");
startPr();
write("docs/guide.md", "pr\n");
commit("pr");
expect(restoreAll(namedConfigPaths("--model m"))).toEqual({
replaced: [],
denyRules: [],
});
});
describe("what the workflow's inputs name", () => {
test("comes from the base branch, or is removed if only the pull request has it", () => {
write("ci/settings.json", "base\n");
write("ci/plugin/hooks/hooks.json", "base\n");
startPr();
write("ci/settings.json", "pr\n");
write("ci/plugin/hooks/hooks.json", "pr\n");
write("ci/mcp.json", "pr\n");
write("ci/other.json", "pr\n");
commit("pr");
process.env.INPUT_SETTINGS = "ci/settings.json";
const named = namedConfigPaths(
"--mcp-config ci/mcp.json --plugin-dir ./ci/plugin",
);
expect(restore(named).sort()).toEqual([
"ci/mcp.json",
"ci/plugin",
"ci/settings.json",
]);
expect(read("ci/settings.json")).toBe("base\n");
expect(read("ci/plugin/hooks/hooks.json")).toBe("base\n");
expect(existsSync("ci/mcp.json")).toBe(false);
expect(read("ci/other.json")).toBe("pr\n");
});
test("can't be the whole repository", () => {
startPr();
write("hooks/hooks.json", "pr\n");
commit("pr");
expect(() => restore(namedConfigPaths("--plugin-dir ."))).toThrow(
"Put the plugin in a subdirectory",
);
});
test("is the manifest and the plugins of a marketplace at the root", () => {
write(
".claude-plugin/marketplace.json",
JSON.stringify({
metadata: { pluginRoot: "./more" },
plugins: [
{ name: "a", source: "./plugins/a/" },
{ name: "b", source: "b" },
{ name: "d", source: "../d" },
{ name: "c", source: { source: "github", repo: "o/c" } },
],
}),
);
write("plugins/a/hooks/hooks.json", "base\n");
write("more/b/hooks/hooks.json", "base\n");
startPr();
write(
".claude-plugin/marketplace.json",
JSON.stringify({ plugins: [{ name: "a", source: "./evil" }] }),
);
write("plugins/a/hooks/hooks.json", "pr\n");
write("more/b/hooks/hooks.json", "pr\n");
commit("pr");
process.env.INPUT_PLUGIN_MARKETPLACES = "https://example.com/x.git\n./\n";
expect(restore(namedConfigPaths("")).sort()).toEqual([
".claude-plugin",
"more/b",
"plugins/a",
]);
expect(read("plugins/a/hooks/hooks.json")).toBe("base\n");
expect(read("more/b/hooks/hooks.json")).toBe("base\n");
expect(read(".claude-plugin/marketplace.json")).not.toContain("evil");
expect(read("src/index.ts")).toBe("base\n");
});
test.each([
["ci/marketplace.json", "ci/marketplace.json"],
["./", ".claude-plugin/marketplace.json"],
])("finds the plugins of a marketplace at %s", (input, path) => {
const manifest = JSON.stringify({
plugins: [{ name: "a", source: "./plugins/a" }],
});
write(path, manifest);
write("plugins/a/hooks/hooks.json", "base\n");
startPr();
write("plugins/a/hooks/hooks.json", "pr\n");
commit("pr");
process.env.INPUT_PLUGIN_MARKETPLACES = input.startsWith(".")
? input
: `./${input}`;
expect(restore(namedConfigPaths(""))).toEqual(["plugins/a"]);
expect(read("plugins/a/hooks/hooks.json")).toBe("base\n");
});
test("is a whole marketplace in a directory", () => {
write("market/.claude-plugin/marketplace.json", "base\n");
write("market/a/hooks.json", "base\n");
startPr();
write("market/a/hooks.json", "pr\n");
commit("pr");
for (const input of [
"./market",
"./market/.claude-plugin/marketplace.json",
]) {
process.env.INPUT_PLUGIN_MARKETPLACES = input;
expect(restore(namedConfigPaths(""))).toEqual(["market"]);
expect(read("market/a/hooks.json")).toBe("base\n");
git("checkout", "-q", "--", "market");
}
});
test("can't be a plugin that is the whole repository", () => {
write(
".claude-plugin/marketplace.json",
JSON.stringify({ plugins: [{ name: "a", source: "./" }] }),
);
startPr();
process.env.INPUT_PLUGIN_MARKETPLACES = "./";
expect(() => restore(namedConfigPaths(""))).toThrow(
"Put the plugin in a subdirectory",
);
});
});
describe("namedConfigPaths", () => {
test("finds paths in every input that names files", () => {
process.env.INPUT_SETTINGS = " .github/settings.json ";
process.env.INPUT_PLUGIN_MARKETPLACES =
"./market\n../outside\n/elsewhere\n";
expect(
namedConfigPaths(
`--mcp-config '{"mcpServers":{}}' a.json b.json
--plugin-dir=plugin --settings '{"a":1}' --agents agents.json
--append-system-prompt-file p.md --system-prompt-file ../x.md
--plugin-dir-no-mcp 2024 --append-subagent-system-prompt-file q.md
--setting-sources user --json-schema '{}'
--allowedTools Read --model m`,
),
).toEqual({
paths: [
".github/settings.json",
"a.json",
"b.json",
"plugin",
"agents.json",
"p.md",
"2024",
"q.md",
],
marketplaces: ["market"],
});
});
test("finds the project config in a --project-config-root", () => {
startPr();
const { paths } = namedConfigPaths("--project-config-root app");
expect(paths).toContain("app/.claude");
expect(paths).toContain("app/.mcp.json");
expect(paths).not.toContain("app");
expect(restore(namedConfigPaths(`--project-config-root .`))).toEqual([]);
});
test("finds nothing in inputs that name no files in the checkout", () => {
process.env.INPUT_SETTINGS = '{"permissions":{}}';
process.env.INPUT_PLUGIN_MARKETPLACES = "https://example.com/x.git";
expect(namedConfigPaths("--mcp-config /etc/mcp.json --settings")).toEqual({
paths: [],
marketplaces: [],
});
});
});
+1 -1
View File
@@ -70,7 +70,7 @@ describe("setupBranch fetch depth", () => {
inputs: { useCommitSigning, branchPrefix: "claude/" },
});
await setupBranch(octokits, githubData, context);
await setupBranch(octokits, githubData, context, undefined, false);
expect(git(["rev-parse", "--is-shallow-repository"]).trim()).toBe(
"false",
+303
View File
@@ -0,0 +1,303 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import type { GitHubContext, ParsedGitHubContext } from "../src/github/context";
import { setupBranch } from "../src/github/operations/branch";
import {
isCommentOnRefusedForkPr,
isRefusedForkEvent,
} from "../src/github/validation/fork-pr";
import {
createMockAutomationContext,
mockIssueCommentContext,
mockIssueOpenedContext,
mockPullRequestCommentContext,
mockPullRequestOpenedContext,
mockPullRequestReviewCommentContext,
mockPullRequestReviewContext,
} from "./mockContext";
const BASE = { id: 1 };
const FORK = { id: 2 };
type Head = { id: number } | null;
function octokitWith(reply: () => unknown) {
const calls: unknown[] = [];
const octokit = {
pulls: {
get: async (params: unknown) => {
calls.push(params);
return { data: reply() };
},
},
} as any;
return { octokit, calls };
}
const pullRequest = (head: Head) => ({
head: { repo: head },
base: { repo: BASE },
});
const withHead = (
context: ParsedGitHubContext,
head: Head,
): ParsedGitHubContext => {
const payload = context.payload as any;
return {
...context,
payload: {
...payload,
pull_request: { ...payload.pull_request, ...pullRequest(head) },
},
};
};
const workflowRun = (head: Head | undefined): GitHubContext =>
createMockAutomationContext({
eventName: "workflow_run",
payload: {
workflow_run: { head_repository: head },
repository: BASE,
} as any,
});
// What run.ts asks, in its order.
const isRefusedForkPr = async (octokit: any, context: GitHubContext) =>
isRefusedForkEvent(context) || isCommentOnRefusedForkPr(octokit, context);
describe("allow_fork_prs", () => {
const saved = process.env.ALLOW_FORK_PRS;
const { octokit: unused, calls: unusedCalls } = octokitWith(() => {
throw new Error("unexpected call");
});
beforeEach(() => {
process.env.ALLOW_FORK_PRS = "false";
unusedCalls.length = 0;
});
afterEach(() => {
if (saved === undefined) delete process.env.ALLOW_FORK_PRS;
else process.env.ALLOW_FORK_PRS = saved;
});
const fork = withHead(mockPullRequestOpenedContext, FORK);
test.each(["true", "TRUE", " true "])(
"allows forks when set to %p",
async (value) => {
process.env.ALLOW_FORK_PRS = value;
expect(await isRefusedForkPr(unused, fork)).toBe(false);
expect(await isRefusedForkPr(unused, mockPullRequestCommentContext)).toBe(
false,
);
expect(await isRefusedForkPr(unused, workflowRun(FORK))).toBe(false);
},
);
test("allows forks when action.yml didn't pass the input", async () => {
delete process.env.ALLOW_FORK_PRS;
expect(await isRefusedForkPr(unused, fork)).toBe(false);
});
test.each(["false", "False", "", "no", "flase", "0"])(
"refuses forks when set to %p",
async (value) => {
process.env.ALLOW_FORK_PRS = value;
expect(await isRefusedForkPr(unused, fork)).toBe(true);
},
);
test.each([
["pull_request", mockPullRequestOpenedContext],
["pull_request_review", mockPullRequestReviewContext],
["pull_request_review_comment", mockPullRequestReviewCommentContext],
])("%s: reads the head from the event", async (_event, context) => {
const refused = (head: Head) =>
isRefusedForkPr(unused, withHead(context, head));
expect(await refused(FORK)).toBe(true);
expect(await refused(null)).toBe(true);
expect(await refused(BASE)).toBe(false);
});
test.each([
[FORK, true],
[null, true],
[BASE, false],
])("comment on a pull request with head %p: %p", async (head, expected) => {
const { octokit, calls } = octokitWith(() => pullRequest(head));
expect(await isRefusedForkPr(octokit, mockPullRequestCommentContext)).toBe(
expected,
);
expect(calls).toEqual([
{
owner: mockPullRequestCommentContext.repository.owner,
repo: mockPullRequestCommentContext.repository.repo,
pull_number: mockPullRequestCommentContext.entityNumber,
},
]);
});
test("a comment fails when the pull request can't be read", async () => {
const { octokit, calls } = octokitWith(() => {
throw Object.assign(new Error("secret"), { status: 404 });
});
const refused = isRefusedForkPr(octokit, mockPullRequestCommentContext);
await expect(refused).rejects.toThrow("is from a fork (HTTP 404)");
expect(calls.length).toBe(1);
});
test.each([
[FORK, true],
[null, true],
[undefined, true],
[BASE, false],
])("workflow_run of head %p: %p", async (head, expected) => {
expect(await isRefusedForkPr(unused, workflowRun(head))).toBe(expected);
});
test("issues and other events are not affected", async () => {
for (const context of [
mockIssueOpenedContext,
mockIssueCommentContext,
createMockAutomationContext({ eventName: "workflow_dispatch" }),
createMockAutomationContext({ eventName: "schedule" }),
]) {
expect(await isRefusedForkPr(unused, context)).toBe(false);
}
expect(unusedCalls).toEqual([]);
});
});
test("setupBranch refuses a fork when allow_fork_prs is off", async () => {
const saved = process.env.ALLOW_FORK_PRS;
process.env.ALLOW_FORK_PRS = "false";
try {
const data = { contextData: { state: "OPEN", isCrossRepository: true } };
await expect(
(setupBranch as any)({}, data, mockPullRequestCommentContext),
).rejects.toThrow("is from a fork");
} finally {
if (saved === undefined) delete process.env.ALLOW_FORK_PRS;
else process.env.ALLOW_FORK_PRS = saved;
}
});
describe("run.ts with allow_fork_prs: false", () => {
// 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) {
const dir = mkdtempSync(join(tmpdir(), "fork-pr-"));
const requests: string[] = [];
const server = Bun.serve({
port: 0,
hostname: "127.0.0.1",
fetch(request) {
const { pathname } = new URL(request.url);
requests.push(pathname);
if (pathname.endsWith("/permission")) {
return Response.json({ permission: "write" });
}
return pull && pathname.endsWith("/pulls/7")
? Response.json(pull)
: Response.json({}, { status: 404 });
},
});
try {
for (const file of ["output", "env"]) writeFileSync(join(dir, file), "");
writeFileSync(join(dir, "event.json"), JSON.stringify(event));
const child = Bun.spawn(
[
process.execPath,
"run",
join(import.meta.dir, "../src/entrypoints/run.ts"),
],
{
cwd: dir,
stdout: "pipe",
stderr: "pipe",
env: {
PATH: process.env.PATH,
HOME: dir,
RUNNER_TEMP: dir,
GITHUB_EVENT_NAME: eventName,
GITHUB_EVENT_PATH: join(dir, "event.json"),
GITHUB_REPOSITORY: "o/r",
GITHUB_ACTOR: "writer",
GITHUB_RUN_ID: "1",
GITHUB_OUTPUT: join(dir, "output"),
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" }),
},
},
);
const [stdout, stderr, exitCode] = await Promise.all([
new Response(child.stdout).text(),
new Response(child.stderr).text(),
child.exited,
]);
return { exitCode, log: stdout + stderr, requests };
} finally {
server.stop(true);
rmSync(dir, { recursive: true, force: true });
}
}
const repository = { id: 1, name: "r", owner: { login: "o" } };
const sender = { login: "writer", type: "User" };
test("skips a fork's event before it asks for a token", async () => {
const result = await run("pull_request_review", {
action: "submitted",
repository,
sender,
review: { id: 1, body: "@claude", user: sender },
pull_request: { number: 7, ...pullRequest(FORK) },
});
expect(result.log).toContain("Skipped, because allow_fork_prs");
expect(result.exitCode).toBe(0);
expect(result.requests).toEqual([]);
});
test("skips a comment on a fork's pull request before it does anything else", async () => {
const result = await run(
"issue_comment",
{
action: "created",
repository,
sender,
issue: { number: 7, pull_request: {}, user: { login: "outsider" } },
comment: { id: 1, body: "@claude", user: sender },
},
pullRequest(FORK),
);
expect(result.log).toContain("Skipped, because allow_fork_prs");
expect(result.exitCode).toBe(0);
expect(result.requests).toEqual([
"/repos/o/r/collaborators/writer/permission",
"/repos/o/r/pulls/7",
]);
});
test("goes on with a comment on a pull request in this repository", async () => {
const result = await run(
"issue_comment",
{
action: "created",
repository,
sender,
issue: { number: 7, pull_request: {}, user: { login: "outsider" } },
comment: { id: 1, body: "@claude", user: sender },
},
pullRequest(BASE),
);
expect(result.log).not.toContain("Skipped, because allow_fork_prs");
expect(result.requests.length).toBeGreaterThan(2);
});
});
+1 -1
View File
@@ -282,7 +282,7 @@ describe("git wrappers", () => {
describe("with files taken from another branch", () => {
const RESTORED =
":(top).claude\n:(top)CLAUDE.md\n:(top)AGENTS.md\n:(top).mcp.json\n:(top,glob)**/package.json\n";
":(top,literal).claude\n:(top,literal)CLAUDE.md\n:(top,literal)AGENTS.md\n:(top,literal).mcp.json\n:(top,glob)**/package.json\n";
const write = (path: string, content: string) => {
mkdirSync(join(repo, path, ".."), { recursive: true });
writeFileSync(join(repo, path), content);
+20
View File
@@ -69,6 +69,7 @@ describe("Tag Mode", () => {
context,
octokit: {} as any,
githubToken: "test-token",
skipLfsDownloads: false,
});
expect(configureGitAuthSpy).toHaveBeenCalledTimes(1);
@@ -81,6 +82,21 @@ describe("Tag Mode", () => {
expect(replaceCheckoutCredentialsSpy).not.toHaveBeenCalled();
});
test.each([true, false])(
"tells setupBranch whether to skip Git LFS downloads: %p",
async (skipLfsDownloads) => {
await prepareTagMode({
context: { ...mockIssueCommentContext },
octokit: {} as any,
githubToken: "test-token",
skipLfsDownloads,
});
expect(branch.setupBranch).toHaveBeenCalledTimes(1);
const call = (branch.setupBranch as any).mock.calls[0];
expect(call[4]).toBe(skipLfsDownloads);
},
);
describe("push branch", () => {
const savedPath = process.env.GITHUB_ACTION_PATH;
let actionPath: string;
@@ -104,6 +120,7 @@ describe("Tag Mode", () => {
context: { ...mockIssueCommentContext },
octokit: {} as any,
githubToken: "test-token",
skipLfsDownloads: false,
});
expect(pinned()).toBe("claude/test");
expect(process.env.CLAUDE_PUSH_BRANCH).toBeUndefined();
@@ -120,6 +137,7 @@ describe("Tag Mode", () => {
context: { ...mockIssueCommentContext },
octokit: {} as any,
githubToken: "test-token",
skipLfsDownloads: false,
});
expect(pinned()).toBe("feature");
});
@@ -149,6 +167,7 @@ describe("Tag Mode", () => {
context: { ...mockIssueCommentContext },
octokit: {} as any,
githubToken: "test-token",
skipLfsDownloads: false,
});
return claudeArgs;
};
@@ -216,6 +235,7 @@ describe("Tag Mode", () => {
context,
octokit: {} as any,
githubToken: "test-token",
skipLfsDownloads: false,
});
expect(configureGitAuthSpy).not.toHaveBeenCalled();
+141 -5
View File
@@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import * as core from "@actions/core";
import { execFileSync } from "child_process";
import {
appendFileSync,
existsSync,
linkSync,
lstatSync,
mkdirSync,
mkdtempSync,
@@ -27,7 +29,9 @@ import {
const KEYS = [
"GITHUB_ACTION_PATH",
"GITHUB_ENV",
"GITHUB_OUTPUT",
"GITHUB_PATH",
"GITHUB_STEP_SUMMARY",
"HOME",
"XDG_CONFIG_HOME",
"GIT_CONFIG_GLOBAL",
@@ -38,6 +42,8 @@ const KEYS = [
"GIT_CONFIG_VALUE_1",
"GIT_CONFIG_KEY_2",
"GIT_CONFIG_VALUE_2",
"GIT_CONFIG_KEY_3",
"GIT_CONFIG_VALUE_3",
// git exports these into hooks, such as a pre-commit hook running this suite.
// If inherited, git would act on the enclosing repository, not the temp one.
"GIT_DIR",
@@ -152,6 +158,104 @@ describe("session guard", () => {
expect(statSync(path).mode & 0o777).toBe(0o640);
});
describe.each(["GITHUB_OUTPUT", "GITHUB_STEP_SUMMARY"])(
"%s, which the action adds to after the session",
(name) => {
let path: string;
beforeEach(() => {
path = join(dir, name);
process.env[name] = path;
writeFileSync(path, "by an earlier part\n");
});
test("keeps what a session wrote", () => {
const restore = snapshotSessionFiles();
appendFileSync(path, "by the session\n");
restore();
expect(readFileSync(path, "utf8")).toBe(
"by an earlier part\nby the session\n",
);
expect(warnings()).toEqual([]);
});
test("keeps it if the session replaced the file", () => {
const restore = snapshotSessionFiles();
rmSync(path);
writeFileSync(path, "by the session\n");
restore();
expect(readFileSync(path, "utf8")).toBe("by the session\n");
expect(warnings()).toEqual([]);
});
test.each([
["a symlink", symlinkSync],
["a hard link", linkSync],
])("doesn't follow %s to a file later steps trust", (_, link) => {
const restore = snapshotSessionFiles();
rmSync(path);
link(process.env.GITHUB_PATH!, path);
restore();
appendFileSync(path, "/tmp/shims\n");
expect(readFileSync(process.env.GITHUB_PATH!, "utf8")).toBe(
"/opt/tool\n",
);
expect(readFileSync(path, "utf8")).toBe(
"by an earlier part\n/tmp/shims\n",
);
expect(warnings()[0]).toContain(name);
});
test("doesn't follow a hard link to a file with the same content", () => {
writeFileSync(path, "");
writeFileSync(process.env.GITHUB_ENV!, "");
const restore = snapshotSessionFiles();
rmSync(path);
linkSync(process.env.GITHUB_ENV!, path);
restore();
appendFileSync(path, "X=1\n");
expect(readFileSync(process.env.GITHUB_ENV!, "utf8")).toBe("");
expect(warnings()[0]).toContain(name);
});
test("puts back a file the session deleted", () => {
const restore = snapshotSessionFiles();
rmSync(path);
restore();
expect(readFileSync(path, "utf8")).toBe("by an earlier part\n");
});
test("says nothing if there was no file before and after", () => {
rmSync(path);
snapshotSessionFiles()();
expect(existsSync(path)).toBe(false);
expect(warnings()).toEqual([]);
});
test("keeps what a session wrote to a file that had a second name before", () => {
linkSync(path, join(dir, "second-name"));
const restore = snapshotSessionFiles();
appendFileSync(path, "by the session\n");
restore();
expect(readFileSync(path, "utf8")).toContain("by the session\n");
expect(warnings()).toEqual([]);
});
test("keeps a link that was there before, and what a session wrote to it", () => {
const target = join(dir, "target");
rmSync(path);
writeFileSync(target, "");
symlinkSync(target, path);
const restore = snapshotSessionFiles();
appendFileSync(path, "by the session\n");
restore();
expect(lstatSync(path).isSymbolicLink()).toBe(true);
expect(readFileSync(target, "utf8")).toBe("by the session\n");
expect(warnings()).toEqual([]);
});
},
);
describe("a config that was already a symlink", () => {
let target: string;
let link: string;
@@ -221,7 +325,7 @@ describe("session guard", () => {
test("moves the action's settings from the environment to the repository", () => {
disableGitPrograms({ hooks: true });
expect(process.env.GIT_CONFIG_COUNT).toBe("2");
expect(process.env.GIT_CONFIG_COUNT).toBe("3");
const restore = snapshotSessionFiles(() =>
prepareGitForSession({ hooks: true }),
);
@@ -337,7 +441,7 @@ describe("session guard", () => {
pinRestoredPaths([".claude", "package.json"]);
const restoredFile = join(dir, "scripts/.restored-paths");
expect(readFileSync(restoredFile, "utf8")).toBe(
":(top).claude\n:(top,glob)**/package.json\n",
":(top,literal).claude\n:(top,glob)**/package.json\n",
);
clearSessionState();
expect(existsSync(join(dir, "scripts/.push-branch"))).toBe(false);
@@ -444,14 +548,46 @@ describe("session guard", () => {
test("leaves hooks alone when not asked", () => {
disableGitPrograms({ hooks: false });
expect(process.env.GIT_CONFIG_COUNT).toBe("1");
expect(process.env.GIT_CONFIG_COUNT).toBe("2");
expect(process.env.GIT_CONFIG_KEY_0).toBe("core.fsmonitor");
});
test.each([true, false])(
"sets safe.bareRepository for the action's git commands (disable hooks: %p)",
(hooks) => {
disableGitPrograms({ hooks });
expect(git("config", "safe.bareRepository").trim()).toBe("explicit");
git("init", "-q", "--bare", join(dir, "repo", "folder"));
expect(() => git("-C", "folder", "rev-parse", "--git-dir")).toThrow();
},
);
test("finds a bare repository in the current directory when hooks stay on", () => {
git("init", "-q", "--bare", join(dir, "bare.git"));
process.chdir(join(dir, "bare.git"));
disableGitPrograms({ hooks: false });
expect(git("rev-parse", "--is-bare-repository").trim()).toBe("true");
});
test("sets safe.bareRepository in a repository whose .git file names a bare one", () => {
git("init", "-q", "--bare", join(dir, "tree", ".bare"));
writeFileSync(join(dir, "tree", ".git"), "gitdir: ./.bare\n");
process.chdir(join(dir, "tree"));
disableGitPrograms({ hooks: false });
expect(git("config", "safe.bareRepository").trim()).toBe("explicit");
});
test("refuses a bare repository in the current directory when hooks are off", () => {
git("init", "-q", "--bare", join(dir, "bare.git"));
process.chdir(join(dir, "bare.git"));
disableGitPrograms({ hooks: true });
expect(() => git("rev-parse", "--is-bare-repository")).toThrow();
});
test("does not add a setting twice", () => {
disableGitPrograms({ hooks: true });
disableGitPrograms({ hooks: true });
expect(process.env.GIT_CONFIG_COUNT).toBe("2");
expect(process.env.GIT_CONFIG_COUNT).toBe("3");
});
test("keeps existing GIT_CONFIG entries", () => {
@@ -459,7 +595,7 @@ describe("session guard", () => {
process.env.GIT_CONFIG_KEY_0 = "user.name";
process.env.GIT_CONFIG_VALUE_0 = "someone";
disableGitPrograms({ hooks: true });
expect(process.env.GIT_CONFIG_COUNT).toBe("3");
expect(process.env.GIT_CONFIG_COUNT).toBe("4");
expect(process.env.GIT_CONFIG_KEY_0).toBe("user.name");
expect(process.env.GIT_CONFIG_KEY_1).toBe("core.fsmonitor");
expect(process.env.GIT_CONFIG_KEY_2).toBe("core.hooksPath");
+3 -3
View File
@@ -67,9 +67,9 @@ describe("setupBranch generated branch name validation", () => {
},
});
await expect(setupBranch(octokits, githubData, context)).rejects.toThrow(
"process.exit called",
);
await expect(
setupBranch(octokits, githubData, context, undefined, false),
).rejects.toThrow("process.exit called");
expect(exitCode).toBe(1);
// Must fail on the name itself, not on a later git or API call.
expect(loggedErrors.join("\n")).toContain(
+96
View File
@@ -1,6 +1,7 @@
import {
checkContainsTrigger,
escapeRegExp,
isModeration,
} from "../src/github/validation/trigger";
import { describe, it, expect } from "bun:test";
import {
@@ -625,3 +626,98 @@ describe("checkContainsTrigger when the text is someone else's", () => {
).toBe(false);
});
});
describe("isModeration", () => {
const event = (
base: ParsedGitHubContext,
kind: "comment" | "review",
eventAction: string,
author: string | null,
actor: string,
) =>
({
...base,
eventAction,
actor,
payload: {
...base.payload,
action: eventAction,
[kind]: {
...(base.payload as any)[kind],
user: author && { login: author },
},
},
}) as ParsedGitHubContext;
const comments = [
mockIssueCommentContext,
mockPullRequestReviewCommentContext,
];
it("is true when someone else edits or deletes a comment", () => {
for (const base of comments) {
for (const action of ["edited", "deleted"]) {
for (const author of ["outsider", null]) {
expect(
isModeration(event(base, "comment", action, author, "maintainer")),
).toBe(true);
}
}
}
});
it("is true when someone else edits or dismisses a review", () => {
for (const action of ["edited", "dismissed"]) {
expect(
isModeration(
event(
mockPullRequestReviewContext,
"review",
action,
"outsider",
"maintainer",
),
),
).toBe(true);
}
});
it("is true for any deleted comment", () => {
for (const base of comments) {
expect(
isModeration(event(base, "comment", "deleted", "writer", "writer")),
).toBe(true);
}
});
it("is false for a person's own edit", () => {
for (const base of comments) {
expect(
isModeration(event(base, "comment", "edited", "Writer", "writer")),
).toBe(false);
}
});
it("is false for a new comment or review, whatever login its app has", () => {
for (const base of comments) {
expect(
isModeration(event(base, "comment", "created", "app[bot]", "App")),
).toBe(false);
}
expect(
isModeration(
event(
mockPullRequestReviewContext,
"review",
"submitted",
"app[bot]",
"App",
),
),
).toBe(false);
});
it("is false for events with no comment or review", () => {
expect(isModeration(mockIssueLabeledContext)).toBe(false);
expect(isModeration(mockIssueOpenedContext)).toBe(false);
});
});