Compare commits

..
48 Commits
Author SHA1 Message Date
d1f58ad5e6 Use the base branch's AGENTS.md on pull requests (#2059)
Claude Code can load AGENTS.md as project instructions, as it does CLAUDE.md.
On pull requests the root AGENTS.md now comes from the base branch too. The
pull request's version is kept under .claude-pr/.

Co-authored-by: Claude <[email protected]>
2026-11-16 11:02:42 -08:00
fe99289f39 Keep deny rules that hold commas or parentheses (#2033)
* Keep deny rules that hold commas or parentheses

A narrower deny rule for a git command, such as git add on a path with
parentheses, wasn't carried over whole to the wrapper script that runs it. One
with a comma could lose its end when the same text also appeared in the rule
added for the wrapper.

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

* Find deny rules next to line breaks and across values

A rule after a comma and a line break is read whole too, and a rule written as
two quoted values is carried over again.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-16 11:02:36 -08:00
514ab7e6d3 Close gaps in using the base branch's npm and Bun config (#2026)
On pull requests from authors without write access, check package.json as it is on disk where .gitattributes converts it, take .gitattributes from the index, keep Bash in the repository root, and match restored directories exactly. Other directories fields than bin no longer count as commands.

Co-authored-by: Claude <[email protected]>
2026-11-16 11:01:31 -08:00
bcbcedd16c Start Bun with the action's own tsconfig again (#2058)
The run step, the post steps and the MCP servers pass --tsconfig-override
next to --no-env-file and --config. The Bun message that led to removing it
in #1315 is gone from 1.4.3, and the action pins 1.4.4.

Co-authored-by: Claude <[email protected]>
2026-11-16 19:01:23 +00:00
9fa68854da Use the base branch's npm and Bun config on outside pull requests (#2020)
* Use the base branch's npm and Bun config on outside pull requests

Config from the base branch, such as a hook or an MCP server, can start npm or Bun
in the checkout. On pull requests from authors without write access, what those tools
read from the repository root now comes from the base branch wherever it differs.

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

* Leave already restored directories alone when replacing tool config

The replacement could rewrite files that were restored from the base branch just
before. It also now keeps a new package's name, and handles a directory in a config
file's place and a file that is re-encoded on checkout.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-13 22:23:52 +00:00
GitHub Actions f3b070c881 chore: bump Claude Code to 2.1.325 and Agent SDK to 0.3.325 2026-11-13 20:41:04 +00:00
4d75e5f390 Make the git wrappers independent of the session's environment (#2018)
* Make the git wrappers independent of the session's environment

Tag mode's wrappers for git add, rm, commit and push now take their settings from
files the action writes, and always work on the repository the action checked out.
Git settings passed through the environment no longer reach them, so a workflow that
relies on one, such as GIT_SSH_COMMAND, needs its own allow rule.

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

* Keep narrow deny rules and other folders covered with the git wrappers

A narrower deny rule such as git add -A now carries over to the wrapper. Global git
config refuses a repository found in a plain folder for the session, since the
settings no longer sit in the environment. The add wrapper also takes --chmod, and
the wrappers use the home directory the action recorded.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-12 15:13:42 -08:00
GitHub Actions 7ca5eaf924 chore: bump Claude Code to 2.1.323 and Agent SDK to 0.3.323 2026-11-12 22:13:11 +00:00
274a39507b Let Claude read CI results on outside pull requests (#2009)
* Add restrict_untrusted_prs input and enable it in claude.yml

A command like `bun test` runs whatever the checkout contains, in a job that
holds the workflow's tokens. On a pull request from an outside contributor,
that code is theirs. The new input denies common code-running commands when
the pull request's author does not have write access, even if claude_args
allows them. It is off by default, and this repository's claude.yml opts in.

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

* Deny code-running commands on untrusted PRs by default

Turn restrict_untrusted_prs on by default, so every workflow gets it without
opting in. Only an explicit false turns it off, so a mistyped value keeps the
restriction.

Stop logging the content of claude_args or raw lookup errors: warnings now
report a rule count and the HTTP status. Also retry rate-limited 403s, skip the
restriction when tag mode branches from the base on a closed or merged PR, warn
when permission checks are turned off, and parse unquoted Bash rules the way
the SDK option parser does.

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

* Add an upgrade note for the restrict_untrusted_prs default

Workflows on a floating tag or branch pick up the new default without changing
anything, and the only signal is a log warning, so call that out in the docs.

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

* Let @claude read CI results on outside pull requests

Test commands are denied there, so maintainers approve the CI run and Claude
reports its result instead. Document that path, and give ci.yml a read-only
token on every run.

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

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: mhegazy <[email protected]>
2026-11-12 21:08:36 +00:00
8a29bc6f0a Call out breaking changes in release notes and titles (#2013)
* Call out breaking changes in release notes and titles

Workflows on the floating v1 tag get each release straight away, and notes
listed only pull request titles. Pull requests labeled breaking-change now get
their own section, and the release title says so.

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

* Start release notes from the last published release

A failed run can leave a tag with no release. Starting from the highest tag
would drop that run's pull requests from the next notes, and could lose the
breaking changes flag.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-12 09:52:32 -08:00
e52db45098 Only trust text and runs from the person who passed the write check (#2002)
* Only trust text and runs from the person who passed the write check

A maintainer's triage action could turn someone else's text into the trusted request, or start a run they did not ask for.

- Issue bodies and comments become the request only when their author is the actor.
- Editing or deleting someone else's comment or review no longer starts a run.
- With a prompt and track_progress, label_trigger and assignee_trigger still apply.
- workflow_run also checks the owner of the fork the run came from.
- A bot's push to a pull request also checks the pull request's author.
- The comment cutoff for a label or assignment uses the actor's own event.

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

* Keep bot activity quiet and let workflows accept any label

Review found that the new checks failed jobs with nothing to do and left some paths open.

- The check on a pull request's author now runs only when a run would start, so bot activity with no trigger still skips quietly.
- An empty label_trigger accepts any label when a prompt is set, instead of crashing.
- Editing or deleting someone else's comment or review no longer starts a run with a prompt either.
- The comment cutoff for an assignment follows the person who made it, even if the event's actor is the assignee.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-12 09:50:10 -08:00
75b2776d96 Stop forced pushes and file reads through the git allow rules (#2006)
* Stop forced pushes and file reads through the git allow rules

Tag mode lets Claude run its push wrapper and git commit without asking, and both accepted more than a normal commit and push.

- The push wrapper rejects a ref starting with +, which git treats as a forced update.
- A new commit wrapper replaces the git commit allow rule. It accepts only a literal message and basic flags, so no flag can read a file into a commit.

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

* Keep deny rules working with the git wrappers

Deny rules match command text, so denying git commit or git push no longer blocked the wrappers that run them. The commit wrapper also stops offering to rewrite a commit, because a pushed one could not be published again.

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

* Read deny rules the same way the CLI receives them

Unquoted rules, the equals form and mid-word wildcards all reached the CLI but were missed when carrying deny rules over to the git wrappers, so those workflows could still commit and push.

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

* Only let the push wrapper update the session's own branch (#2008)

* Only let the push wrapper update the session's own branch

The wrapper accepted any valid branch name, so a prompt-injected session could update main or another person's branch once it moved that branch locally. It now pushes only to the branch the run was set up on.

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

* Repair the tag mode tests after merging

The merge left the test file's two new test groups interleaved, so it did not parse.

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

---------

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

* Note the pr-N branch for fork pull requests in the push docs

On a pull request from a fork, the session's branch is pr-N in the base
repository, not the pull request's own branch. A pull request opened from the
default branch can also update that branch, so branch protection still matters.

---------

Co-authored-by: Claude <[email protected]>
2026-11-12 17:49:56 +00:00
650432d396 Keep fork branch names away from this repository's branches (#2007)
* Keep fork branch names away from this repository's branches

With commit signing on, agent mode wrote commits through the API to the branch named by a fork PR. A fork branch named release targeted this repository's release, and main#pwn targeted main, because the # cut the URL short.

- Fork PRs in agent mode now use pr-N as tag mode does.
- Branch names are encoded in the Git references API URLs.

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

* Use pr-N for comments and reviews on pull requests

A comment on a pull request fell through to the default branch, so signed commits from that run landed there. Branch lookups also become exact, because a prefix match made pr-5 fail once pr-50 existed.

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

* Use issue-N for signed commits on plain issues

Prompt runs on an issue wrote commits through the API to the workflow's
branch, usually the default branch. They now use their own branch, as pull
request runs do. CLAUDE_BRANCH still takes precedence.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-12 09:49:27 -08:00
462c312141 Stop a session from leaving programs for later steps to run (#2003)
* Add restrict_untrusted_prs input and enable it in claude.yml

A command like `bun test` runs whatever the checkout contains, in a job that
holds the workflow's tokens. On a pull request from an outside contributor,
that code is theirs. The new input denies common code-running commands when
the pull request's author does not have write access, even if claude_args
allows them. It is off by default, and this repository's claude.yml opts in.

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

* Deny code-running commands on untrusted PRs by default

Turn restrict_untrusted_prs on by default, so every workflow gets it without
opting in. Only an explicit false turns it off, so a mistyped value keeps the
restriction.

Stop logging the content of claude_args or raw lookup errors: warnings now
report a rule count and the HTTP status. Also retry rate-limited 403s, skip the
restriction when tag mode branches from the base on a closed or merged PR, warn
when permission checks are turned off, and parse unquoted Bash rules the way
the SDK option parser does.

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

* Add an upgrade note for the restrict_untrusted_prs default

Workflows on a floating tag or branch pick up the new default without changing
anything, and the only signal is a log warning, so call that out in the docs.

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

* Stop a session from leaving programs for later steps to run

Steps after the session, such as the checkout action's cleanup, hold the job's credentials and trust files the session can change.

- GITHUB_ENV, GITHUB_PATH and git's config files are restored when the session ends.
- Git ignores core.fsmonitor while the session runs and for the action's own commands afterwards.
- Git hooks are off for the action's own commits, and during sessions on restricted pull requests.
- The token revocation step reads the token from the environment, since a session can write step outputs and an expression in a script could run its commands.

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

* Close more ways a session could affect later steps

Review found gaps in the post-session restore, and one regression for Git LFS.

- Restoring can no longer hang on a FIFO or read a device, and removes anything planted at a tracked path.
- Config files pulled in through include.path are restored too, which covers the config actions/checkout keeps there.
- The action's own commits upload Git LFS objects, because the hook that normally does it is off.
- Hooks go off before an untrusted pull request is checked out, not only when the session starts.
- A session can no longer use a step output or ~/.curlrc to stop or redirect token revocation.

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

* Move the session guard import away from the permissions import

This keeps the change from conflicting with the permissions check being added to the same import block.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-12 17:49:00 +00:00
ead3158f27 Keep the token out of .git/config when bots are allowed (#2005)
* Keep the token out of .git/config when bots are allowed

Allowed bots skip the write check and relay text other people wrote, so a prompt injection in that text could read the token from the origin URL. Workflows with allowed_bots now use the credential helper that allowed_non_write_users already uses.

A later step that pushes with the origin remote now needs its own credentials in those workflows.

Test contexts now get their own copy of the default inputs, because one test file's allowedBots value was leaking into later tests.

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

* Stop the default test context sharing its inputs

createMockContext and createMockAutomationContext still returned the shared default inputs when a test passed no overrides, so an allowedBots value set by one test file reached the credential tests.

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

* Limit the credential helper to this server and to runs with a token

The helper answered for every host git contacted, so it could hand the token to
another server. It also answered with an empty password in later steps, which
stopped git from trying their own credentials. Origin now names a username, so
rewrite rules on the server's prefix can't bypass the helper, and the helper
works from a path with a space.

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

* Say which credentials work for later steps using origin

Origin now names a username, so a credential stored under another username is
not found. The docs and the log line now list what does work.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-12 09:24:16 -08:00
8565ca8f18 Run sessions in auto mode by default (#2004)
* Run sessions in auto mode by default

A safety review now decides tool calls that no allow rule covers, instead of those calls being denied outright. Set --permission-mode in claude_args to opt out.

- Runs from mentions used to default to acceptEdits, and runs with a prompt to default.
- Mention runs switch to acceptEdits and warn when auto mode isn't available, such as on an older model, so they keep their file edits.
- Sessions with a custom ANTHROPIC_BASE_URL keep the earlier defaults, because the check depends on what a gateway passes through.

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

* Update the permission mode comment in claude.yml

The action now defaults to auto mode, so the comment no longer describes acceptEdits being replaced.

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

* Keep the earlier default when non-write users are allowed

Anyone's text reaches these runs, so a call the earlier defaults deny shouldn't be left to the safety review. Workflows can still opt in with the flag. The FAQ also no longer says Bash is disabled by default.

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

* Keep a mode or gateway set in the settings input

Workflows that set a permission mode or base URL in the settings input now keep the earlier defaults. Otherwise auto mode would silently replace a chosen mode, or start behind a gateway that may not support it.

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

* Keep earlier defaults for allowed bots and settings files

Allowed bots skip the write check and relay other people's text, so they get the same default as non-write users. A settings file no longer helps choose the default, because a pull request can change it before the base copy is restored.

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

* Keep earlier defaults with a custom Claude Code executable

A version that predates auto mode exits on the flag, so runs that supply their
own executable failed at startup. They now need to opt in. The edit fallback
also applies when auto mode is set in the equals form.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-12 09:24:04 -08:00
3fd089526c Deny code-running commands on PRs from authors without write access (#2001)
* Add restrict_untrusted_prs input and enable it in claude.yml

A command like `bun test` runs whatever the checkout contains, in a job that
holds the workflow's tokens. On a pull request from an outside contributor,
that code is theirs. The new input denies common code-running commands when
the pull request's author does not have write access, even if claude_args
allows them. It is off by default, and this repository's claude.yml opts in.

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

* Deny code-running commands on untrusted PRs by default

Turn restrict_untrusted_prs on by default, so every workflow gets it without
opting in. Only an explicit false turns it off, so a mistyped value keeps the
restriction.

Stop logging the content of claude_args or raw lookup errors: warnings now
report a rule count and the HTTP status. Also retry rate-limited 403s, skip the
restriction when tag mode branches from the base on a closed or merged PR, warn
when permission checks are turned off, and parse unquoted Bash rules the way
the SDK option parser does.

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

* Add an upgrade note for the restrict_untrusted_prs default

Workflows on a floating tag or branch pick up the new default without changing
anything, and the only signal is a log warning, so call that out in the docs.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-12 09:14:31 -08:00
d5f7970ae2 Pass structured output to shell steps through env (#1963)
* Pass structured output to shell steps through env

Claude's answer can contain quotes, which break a script when GitHub writes the value into it before the shell reads it. The example, the docs and the test workflow now pass it through env, and a test checks that they keep doing so.

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

* Keep fromJSON out of env in the structured output docs

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-10 13:07:47 -08:00
GitHub Actions 4fa93a88de chore: bump Claude Code to 2.1.322 and Agent SDK to 0.3.322 2026-11-10 02:30:41 +00:00
GitHub Actions 9eb012b6d0 chore: bump Claude Code to 2.1.321 and Agent SDK to 0.3.321 2026-11-09 19:22:42 +00:00
Chris NormanandGitHub 115e0b2c49 release: push tags with the release deploy key (enables tag-ruleset enforcement) (#1650)
* release: push tags with the release deploy key

So the tag ruleset (terraform-config#81310) can be enforced: GITHUB_TOKEN can never bypass a ruleset, a deploy key can. No change to how releases are cut.

* release: SHA-pin actions/checkout in the deploy-key jobs

The checkout steps now hold the ruleset-bypass deploy key, so resolve actions/checkout by full SHA (v6.0.2, same pin as sync-base-action.yml) rather than the mutable v6 tag.
2026-11-06 14:21:18 -05:00
GitHub Actions 61a9c274fa chore: bump Claude Code to 2.1.319 and Agent SDK to 0.3.319 2026-11-06 17:05:12 +00:00
GitHub Actions c0949c50a7 chore: bump Claude Code to 2.1.318 and Agent SDK to 0.3.318 2026-11-04 00:03:23 +00:00
GitHub Actions 4845bacbb3 chore: bump Claude Code to 2.1.317 and Agent SDK to 0.3.317 2026-11-03 01:27:13 +00:00
GitHub Actions d535f5172d chore: bump Claude Code to 2.1.316 and Agent SDK to 0.3.316 2026-10-31 01:03:26 +00:00
GitHub Actions 6d5ae526d2 chore: bump Claude Code to 2.1.314 and Agent SDK to 0.3.314 2026-10-30 01:07:44 +00:00
GitHub Actions d70510b174 chore: bump Claude Code to 2.1.312 and Agent SDK to 0.3.312 2026-10-27 20:25:35 +00:00
98a9e39fe1 docs: use claude-plugins-official in plugin examples (#1932)
The plugin examples point at the older claude-code-plugins marketplace. New workflows should install from claude-plugins-official, which is where these plugins are developed.

Co-authored-by: Claude <[email protected]>
2026-10-27 12:51:22 -07:00
GitHub Actions 8041f1d17e chore: bump Claude Code to 2.1.311 and Agent SDK to 0.3.311 2026-10-26 21:53:19 +00:00
925afb5377 chore: bump Bun to 1.4.4 (#1916)
Pin oven-sh/setup-bun to Bun 1.4.4 in action.yml, base-action/action.yml
and the CI workflow (the prettier job previously floated on latest), and
update @types/bun to 1.4.3, the newest published types, in both packages.

Co-authored-by: GitHub Actions <[email protected]>
2026-10-24 00:45:41 +00:00
GitHub Actions 16f9f71ab9 chore: bump Claude Code to 2.1.310 and Agent SDK to 0.3.310 2026-10-23 23:40:57 +00:00
Octavian GuzuandGitHub 8d70a0dd26 Pin the PR version a run checks out (#1915)
Squash merge of 2 commits
2026-10-23 09:26:23 -07:00
GitHub Actions ae68417a74 chore: bump Claude Code to 2.1.309 and Agent SDK to 0.3.309 2026-10-22 22:20:35 +00:00
GitHub Actions 6b6870e649 chore: bump Claude Code to 2.1.308 and Agent SDK to 0.3.308 2026-10-22 04:36:28 +00:00
GitHub Actions aa8a7738e4 chore: bump Claude Code to 2.1.307 and Agent SDK to 0.3.307 2026-10-21 22:19:04 +00:00
GitHub Actions a5a423f75c chore: bump Claude Code to 2.1.306 and Agent SDK to 0.3.306 2026-10-21 03:18:30 +00:00
GitHub Actions e4a6faad49 chore: bump Claude Code to 2.1.305 and Agent SDK to 0.3.305 2026-10-20 20:48:51 +00:00
GitHub Actions db77d4d3c9 chore: bump Claude Code to 2.1.304 and Agent SDK to 0.3.304 2026-10-19 21:37:01 +00:00
GitHub Actions 5eb090f3c3 chore: bump Claude Code to 2.1.303 and Agent SDK to 0.3.303 2026-10-18 22:29:02 +00:00
GitHub Actions f27be6b65a chore: bump Claude Code to 2.1.302 and Agent SDK to 0.3.302 2026-10-16 20:54:52 +00:00
GitHub Actions 374f254f5e chore: bump Claude Code to 2.1.301 and Agent SDK to 0.3.301 2026-10-15 19:24:46 +00:00
GitHub Actions a26b07d8c7 chore: bump Claude Code to 2.1.300 and Agent SDK to 0.3.300 2026-10-14 18:27:27 +00:00
GitHub Actions 34968b5981 chore: bump Claude Code to 2.1.299 and Agent SDK to 0.3.299 2026-10-14 02:51:42 +00:00
GitHub Actions 1d6de8cb0c chore: bump Claude Code to 2.1.296 and Agent SDK to 0.3.296 2026-10-09 19:32:29 +00:00
GitHub Actions 2dca132ff0 chore: bump Claude Code to 2.1.295 and Agent SDK to 0.3.295 2026-10-08 19:51:21 +00:00
GitHub Actions 38c80c1a32 chore: bump Claude Code to 2.1.294 and Agent SDK to 0.3.294 2026-10-08 17:21:17 +00:00
GitHub Actions 6fed3ca145 chore: bump Claude Code to 2.1.293 and Agent SDK to 0.3.293 2026-10-07 18:13:38 +00:00
GitHub Actions 58985842b8 chore: bump Claude Code to 2.1.292 and Agent SDK to 0.3.292 2026-10-06 19:02:41 +00:00
72 changed files with 5543 additions and 270 deletions
+11
View File
@@ -0,0 +1,11 @@
# Groups the notes of each release. Merged pull requests with no label go under
# "Other changes". .github/workflows/release.yml reads the first heading to flag
# the release's title, so keep the two in step.
changelog:
categories:
- title: "⚠️ Breaking changes"
labels:
- breaking-change
- title: Other changes
labels:
- "*"
+7 -4
View File
@@ -4,6 +4,9 @@ on:
pull_request:
workflow_call:
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
@@ -12,7 +15,7 @@ jobs:
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.2.12
bun-version: 1.4.4
- name: Install dependencies
run: bun install
@@ -25,9 +28,9 @@ jobs:
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v1
- uses: oven-sh/setup-bun@v2
with:
bun-version: latest
bun-version: 1.4.4
- name: Install dependencies
run: bun install
@@ -42,7 +45,7 @@ jobs:
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.2.12
bun-version: 1.4.4
- name: Install dependencies
run: bun install
+8 -2
View File
@@ -25,6 +25,7 @@ jobs:
pull-requests: write
issues: write
id-token: write
actions: read # Lets Claude read CI results on pull requests
steps:
- name: Checkout repository
uses: actions/checkout@v6
@@ -42,9 +43,14 @@ jobs:
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
# --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. The action sets
# --permission-mode acceptEdits for @claude mentions, and this one, which comes after it, wins.
# 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.
# --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.
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."
--model "claude-opus-4-7"
--permission-mode auto
+37 -6
View File
@@ -32,9 +32,16 @@ jobs:
next_version: ${{ steps.next_version.outputs.next_version }}
steps:
- name: Checkout code
uses: actions/checkout@v6
# SHA-pinned (same pin as sync-base-action.yml): this step is handed
# the ruleset-bypass deploy key, so it must not resolve a mutable tag.
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
# Tag pushes below authenticate as the release deploy key (a
# bypass actor on the "Protect release tags" ruleset) instead of
# GITHUB_TOKEN, which can never bypass a ruleset. The key lives
# only in the main-restricted `production` environment.
ssh-key: ${{ secrets.RELEASE_TAG_DEPLOY_KEY }}
- name: Get latest tag
id: get_latest_tag
@@ -87,12 +94,29 @@ jobs:
if: ${{ !inputs.dry_run }}
env:
GH_TOKEN: ${{ github.token }}
NEXT_VERSION: ${{ steps.next_version.outputs.next_version }}
run: |
next_version="${{ steps.next_version.outputs.next_version }}"
# Start from the last published release, not the highest tag: a failed run
# can leave a tag with no release, and its pull requests would be dropped.
previous_release=$(gh api "repos/$GITHUB_REPOSITORY/releases?per_page=10" \
--jq '[.[] | select(.draft | not) | .tag_name | select(test("^v[0-9]+\\.[0-9]+\\.[0-9]+$"))][0]')
gh release create "$next_version" \
--title "$next_version" \
--generate-notes \
notes_file="$RUNNER_TEMP/release-notes.md"
gh api "repos/$GITHUB_REPOSITORY/releases/generate-notes" \
-f tag_name="$NEXT_VERSION" \
-f previous_tag_name="$previous_release" \
--jq .body > "$notes_file"
# The heading comes from .github/release.yml. Matching it, not the words
# alone, keeps a pull request's title from flagging the release.
title="$NEXT_VERSION"
if grep -qxF "### ⚠️ Breaking changes" "$notes_file"; then
title="$NEXT_VERSION (breaking changes)"
fi
gh release create "$NEXT_VERSION" \
--title "$title" \
--notes-file "$notes_file" \
--latest=false # keep v1 as latest
update-major-tag:
@@ -105,9 +129,16 @@ jobs:
contents: write
steps:
- name: Checkout code
uses: actions/checkout@v6
# SHA-pinned (same pin as sync-base-action.yml): this step is handed
# the ruleset-bypass deploy key, so it must not resolve a mutable tag.
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
# Tag pushes below authenticate as the release deploy key (a
# bypass actor on the "Protect release tags" ruleset) instead of
# GITHUB_TOKEN, which can never bypass a ruleset. The key lives
# only in the main-restricted `production` environment.
ssh-key: ${{ secrets.RELEASE_TAG_DEPLOY_KEY }}
- name: Update major version tag
run: |
+8 -12
View File
@@ -48,10 +48,9 @@ jobs:
--json-schema '{"type":"object","properties":{"text_field":{"type":"string"},"number_field":{"type":"number"},"boolean_true":{"type":"boolean"},"boolean_false":{"type":"boolean"}},"required":["text_field","number_field","boolean_true","boolean_false"]}'
- name: Verify outputs
env:
OUTPUT: ${{ steps.test.outputs.structured_output }}
run: |
# Parse the structured_output JSON
OUTPUT='${{ steps.test.outputs.structured_output }}'
# Test string pass-through
TEXT_FIELD=$(echo "$OUTPUT" | jq -r '.text_field')
if [ "$TEXT_FIELD" != "hello" ]; then
@@ -111,10 +110,9 @@ jobs:
--json-schema '{"type":"object","properties":{"items":{"type":"array","items":{"type":"string"}},"config":{"type":"object"},"empty_array":{"type":"array"}},"required":["items","config","empty_array"]}'
- name: Verify JSON stringification
env:
OUTPUT: ${{ steps.test.outputs.structured_output }}
run: |
# Parse the structured_output JSON
OUTPUT='${{ steps.test.outputs.structured_output }}'
# Arrays should be JSON stringified
if ! echo "$OUTPUT" | jq -e '.items | length == 3' > /dev/null; then
echo "❌ Array not properly formatted"
@@ -168,10 +166,9 @@ jobs:
--json-schema '{"type":"object","properties":{"zero":{"type":"number"},"empty_string":{"type":"string"},"negative":{"type":"number"},"decimal":{"type":"number"}},"required":["zero","empty_string","negative","decimal"]}'
- name: Verify edge cases
env:
OUTPUT: ${{ steps.test.outputs.structured_output }}
run: |
# Parse the structured_output JSON
OUTPUT='${{ steps.test.outputs.structured_output }}'
# Zero should be "0", not empty or falsy
ZERO=$(echo "$OUTPUT" | jq -r '.zero')
if [ "$ZERO" != "0" ]; then
@@ -227,10 +224,9 @@ jobs:
--json-schema '{"type":"object","properties":{"test-result":{"type":"string"},"item_count":{"type":"number"}},"required":["test-result","item_count"]}'
- name: Verify sanitized names work
env:
OUTPUT: ${{ steps.test.outputs.structured_output }}
run: |
# Parse the structured_output JSON
OUTPUT='${{ steps.test.outputs.structured_output }}'
# Hyphens should be preserved in the JSON
TEST_RESULT=$(echo "$OUTPUT" | jq -r '.["test-result"]')
if [ "$TEST_RESULT" != "passed" ]; then
+3
View File
@@ -1,4 +1,7 @@
.DS_Store
node_modules
scripts/.push-branch
scripts/.no-hooks
scripts/.git-repo
**/.claude/settings.local.json
+1 -1
View File
@@ -51,7 +51,7 @@ Workflow jobs in this repository that call Claude run with three protections. Ke
2. **Network allow list.** `.github/egress-firewall.yaml` lists the hosts those jobs may reach, besides any that GitHub's firewall allows by default. Keep `mode: enforce`, which is what makes the firewall block the rest. Follow that file's header when you add a host.
3. **Auto permission mode.** Every step that runs the Claude Code action (`uses: anthropics/claude-code-action`, or this repository's own `./` and `./base-action`) passes `--permission-mode auto` in `claude_args`. A tool call that needs permission and that the allowed tools do not cover then runs only if Claude Code's safety review passes it. Allow only the tools the job needs, and keep any `--disallowedTools` list a step has. Use `claude-opus-4-6` or a newer model: on an older one Claude Code falls back to its default permission mode.
`claude.yml` answers `@claude` mentions. The Claude Code action sets `--permission-mode acceptEdits` for those, and the `--permission-mode auto` in the workflow's `claude_args`, which comes after it, replaces it.
The action starts sessions in auto mode by default (`src/modes/permission-mode.ts`), except with `allowed_non_write_users`, `allowed_bots`, a custom `ANTHROPIC_BASE_URL`, `path_to_claude_code_executable`, or a `settings` input that sets a base URL or another mode or is a file path. Workflows here still pass the flag, so that the check below can see it and a change to the default can't weaken them.
`.github/workflows/workflow-hardening.yml` fails when a job that runs the Claude Code action or mentions `ANTHROPIC_FEDERATION_RULE_ID` breaks protection 1 or 3, or when the allow list is missing, empty, not `mode: enforce`, or names a host with `*`. It cannot see a job that calls Claude another way, so check new workflows by hand too. If a job cannot meet protection 1 or 3, add it with the reason to the matching exemption table in `.github/scripts/check_workflow_hardening.py`. A job in `EXEMPT_FROM_AUTO_MODE` must set no permission mode at all. Do not skip or weaken the check.
+16 -1
View File
@@ -79,10 +79,25 @@ 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
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.
6. Request review from maintainers
### Breaking changes
Add the `breaking-change` label if a workflow that works today could fail or behave differently after upgrading, with no change on the workflow's side. Workflows on `@v1` get each release straight away, so this is their only warning.
Labeled pull requests go in their own section of the release notes, and the release title says `(breaking changes)`. The notes show only the pull request's title, so make it say what changes.
### For Maintainers: Pull Requests from Outside Contributors
These steps are for pull requests from forks whose author does not have write access.
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).
## Action Development
### Testing Your Changes
+18 -11
View File
@@ -44,6 +44,10 @@ inputs:
only use for workflows with very limited permissions and validate all outputs.
required: false
default: ""
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
default: "true"
include_comments_by_actor:
description: "Comma-separated list of actor usernames to INCLUDE in comments. Supports wildcards: '*[bot]' matches all bots, 'dependabot[bot]' matches specific bot. Empty (default) includes all actors."
required: false
@@ -158,7 +162,7 @@ inputs:
required: false
default: "false"
plugins:
description: "Newline-separated list of Claude Code plugin names to install (e.g., 'code-review@claude-code-plugins\nfeature-dev@claude-code-plugins')"
description: "Newline-separated list of Claude Code plugin names to install (e.g., 'code-review@claude-plugins-official\nfeature-dev@claude-plugins-official')"
required: false
default: ""
plugin_marketplaces:
@@ -194,7 +198,7 @@ runs:
if: inputs.path_to_bun_executable == ''
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # https://github.com/oven-sh/setup-bun/releases/tag/v2.2.0
with:
bun-version: 1.3.14
bun-version: 1.4.4
token: ${{ inputs.github_token || github.token }}
# Disable setup-bun's cache. The upstream save step uses a deterministic
# key (Bun version) and isn't ref-aware: on every second-and-subsequent
@@ -277,13 +281,12 @@ runs:
id: run
shell: bash
run: |
# Do NOT pass --tsconfig-override here. It triggers a Bun runtime bug
# ("Internal error: directory mismatch for directory .../tsconfig.json")
# that aborts the run with exit code 1. Bun already auto-discovers the
# action's own tsconfig.json by walking up from the entry file, so the
# override is redundant. See oven-sh/bun#25730.
# Keep these options wherever the action runs its own scripts, so that Bun
# takes its settings from the action's directory. Bun before 1.4.3 logs
# "directory mismatch" for --tsconfig-override (oven-sh/bun#25730).
bun --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/run.ts
env:
# Prepare inputs
@@ -298,6 +301,7 @@ runs:
OVERRIDE_GITHUB_TOKEN: ${{ inputs.github_token }}
ALLOWED_BOTS: ${{ inputs.allowed_bots }}
ALLOWED_NON_WRITE_USERS: ${{ inputs.allowed_non_write_users }}
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 || '' }}
INCLUDE_COMMENTS_BY_ACTOR: ${{ inputs.include_comments_by_actor }}
@@ -423,9 +427,9 @@ runs:
run: |
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
# No --tsconfig-override: see the "Run Claude Code Action" step above.
"$BUN_BIN" --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/cleanup-ssh-signing.ts
- name: Post buffered inline comments
@@ -440,20 +444,23 @@ runs:
run: |
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
# No --tsconfig-override: see the "Run Claude Code Action" step above.
"$BUN_BIN" --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/post-buffered-inline-comments.ts
- name: Revoke app token
if: always() && inputs.github_token == '' && steps.run.outputs.github_token != '' && steps.run.outputs.skipped_due_to_workflow_validation_mismatch != 'true'
shell: bash
env:
APP_TOKEN: ${{ steps.run.outputs.github_token }}
run: |
curl -L \
# -q comes first and skips ~/.curlrc, which a session can write.
curl -q -L \
--connect-timeout 5 \
--max-time 10 \
-X DELETE \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ steps.run.outputs.github_token }}" \
-H "Authorization: Bearer $APP_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
${GITHUB_API_URL:-https://api.github.com}/installation/token || true
+3 -3
View File
@@ -84,7 +84,7 @@ inputs:
required: false
default: "false"
plugins:
description: "Newline-separated list of Claude Code plugin names to install (e.g., 'code-review@claude-code-plugins\nfeature-dev@claude-code-plugins')"
description: "Newline-separated list of Claude Code plugin names to install (e.g., 'code-review@claude-plugins-official\nfeature-dev@claude-plugins-official')"
required: false
default: ""
plugin_marketplaces:
@@ -120,7 +120,7 @@ runs:
if: inputs.path_to_bun_executable == ''
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # https://github.com/oven-sh/setup-bun/releases/tag/v2.2.0
with:
bun-version: 1.3.14
bun-version: 1.4.4
# Disable setup-bun's cache. See action.yml for details and issue #1252.
no-cache: true
@@ -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.291"
CLAUDE_CODE_VERSION="2.1.325"
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
for attempt in 1 2 3; do
echo "Installation attempt $attempt..."
+17 -19
View File
@@ -6,11 +6,11 @@
"name": "@anthropic-ai/claude-code-base-action",
"dependencies": {
"@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.291",
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
"shell-quote": "^1.8.4",
},
"devDependencies": {
"@types/bun": "^1.2.12",
"@types/bun": "^1.4.3",
"@types/node": "^20.0.0",
"@types/shell-quote": "^1.7.5",
"prettier": "3.5.3",
@@ -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].291", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.291", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.291", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.291", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.291", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.291", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.291", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.291", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.291" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-XLEhng37jyekLlB/bCgqHTFeHSgdqAhQw/Xcf8KZGFm8Iwy/UiNt5FvUxA5FK9BYw0MBKHSFbLIs32WOjad5tg=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected].325", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.325", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.325" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-MhSm2Fhk3DA/hhjdCKXDZWlnykpPWJjX42SogllAHMplY9ZKT+Ltb8QPtQxpe225Imfs4A8IKaNE4biivA+fHg=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected].291", "", { "os": "darwin", "cpu": "arm64" }, "sha512-i+BSETc+SE77PZ7uaIqlxODsLdWukB2AwXEEjzih+D2C3S7AKTZTL2trJs1kealZJHLVRWq5utuQjxr9u/ZwAQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected].325", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0u8bTug2zH+zWE8CMiFrm/ldmH20uA9B/zhXpI7ATHFJnpPMdwTqE56CFM0m3LOwnNum0jpRn7XV1dn6Pf2pqA=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected].291", "", { "os": "darwin", "cpu": "x64" }, "sha512-hJ3ys972EImbEIbImvBv+vwX9JgstZQ3HkOx6fKEBlqp8NXoxTVchdiHrJ/IBTV1qzfzuvCI6ZjptuvBDPCutA=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected].325", "", { "os": "darwin", "cpu": "x64" }, "sha512-HD3YRFyM5H5QH2usS/WD6gobk3BEp2jq9dKyrkhAVdQIqFMlrcSrRhGA0i3R1IOLxtPAYkmDGepZ62k1kMOW9Q=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected].291", "", { "os": "linux", "cpu": "arm64" }, "sha512-hDRXpKfniuNWwFuSfu/MTp2uTKJyRW3QqhphVfx02VwOPd9gmOne9KWxp9N+FXA0I3TzVi7fF6mVNGIxhMjnXQ=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected].325", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-28oVrCEN6M6MJP8Od4SK/scal1QdLbn5Sci+qL8j55l6csHtPeUYF9zdjWLniFKph43pejfZf5te/Vf/bwehkw=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected].291", "", { "os": "linux", "cpu": "arm64" }, "sha512-pHrXszKDedaBiJAiVdgJZ9HRKRmBTFjIhMrBZCcn6evCPD97iwiS3vbGnC+oM4Usqgvplpj6Zv0vKYGxXud3fA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected].325", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-72y6QNRZC4eMCxne/wNsuwNHsViSkgFKlYMCUVXxmiR9gpIMd3rf++oJMIsSuEAQqzqT7jwCrdtibv6R4bx5PA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected].291", "", { "os": "linux", "cpu": "x64" }, "sha512-KZGLgT5HF2wyJuzTOpRj/iipRjhI7MZ9bsMpIcJZjYt6d1azMDABo8rr5vrlU+7kcZZJq/oBKqbLN0M1DaO30g=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected].325", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-wXEWbDmNYiorY5EKASYjvQct8zHShUPmAS9N/IAsgPA/cx2vsOFqPQw8jRQKeaW6AmFgx7k/Wf7THalNXbMEkQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected].291", "", { "os": "linux", "cpu": "x64" }, "sha512-r7HzdHvlXo4nvzVKyqEYfILRUqfsC5S6fGLivXutxkyFLnhYpuuOxaSMzK0OAhyS/HPdg9PbK2i4u52yljVhvQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected].325", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-BHewYUTd7mDLR5iHTVt6Q28gJKLC5C24b1H3NM0qGt9dxnjVUh1Lza52GzHY2Rb9hAPQymLSXWuVh1OFoFQatA=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected].291", "", { "os": "win32", "cpu": "arm64" }, "sha512-oY79rhNEkPB+yCQTPMkuwHiBAwHwodoj+6jwJAB578pHqOTsMWn91MJySsLTJlHlPMbwCUpbwen4RGMiGhnwOw=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected].325", "", { "os": "win32", "cpu": "arm64" }, "sha512-NH3I2o105oKK8lfJ5RlzCp+YTZn3qncwQ1xSzQ4jqn7LUddThIidpFU7B+TKQxh1X9eayAp7EtrBQ36mXflQwQ=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected].291", "", { "os": "win32", "cpu": "x64" }, "sha512-Kf+Xjdymr9xP6KLiQdnKJAykO79HPWr2q1JPVdlAYm0vz67KaUiKA8H/YFiMzoFurpdaJfqm9HvlQss+zeDlew=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected].325", "", { "os": "win32", "cpu": "x64" }, "sha512-pjqVL++V/2oMJ6u1HdB608bcTUvzts1e8hX93Q8khasy2JB+R823bnvpQapcOurOWB3+v1X2JXIjXyWcGPJCQQ=="],
"@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=="],
@@ -55,12 +55,10 @@
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
"@types/bun": ["@types/bun@1.2.19", "", { "dependencies": { "bun-types": "1.2.19" } }, "sha512-d9ZCmrH3CJ2uYKXQIUuZ/pUnTqIvLDS0SK7pFmbx8ma+ziH/FRMoAq5bYpRG7y+w1gl+HgyNZbtqgMq4W4e2Lg=="],
"@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-cuVNgarYWZqxRJDQHEB58GEONhOK79QVR/qYx4S7kcUObQvUwvFnYxJuuHUKm2aieN9X3yZB4LZsuYNU1Qphsw=="],
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-AwAfQ2Wa5bCx9WP8nZL2uMZWod7J7/JSplxbTmBQ5ms6QpqNYm672H0Vu9ZVKVngQ+ii4R/byguVEUZQyeg44g=="],
"@types/shell-quote": ["@types/[email protected]", "", {}, "sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw=="],
"accepts": ["[email protected]", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
@@ -71,7 +69,7 @@
"body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"bun-types": ["bun-types@1.2.19", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-uAOTaZSPuYsWIXRpj7o56Let0g/wjihKCkeRqUBhlLVM/Bt+Fj9xTo+LhC1OV1XDaGkz4hNC80et5xgy+9KTHQ=="],
"bun-types": ["bun-types@1.4.3", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
"bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
@@ -91,8 +89,6 @@
"cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"csstype": ["[email protected]", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"depd": ["[email protected]", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
@@ -257,8 +253,10 @@
"wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
"@modelcontextprotocol/sdk/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@modelcontextprotocol/sdk/zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
}
}
+2 -2
View File
@@ -11,11 +11,11 @@
},
"dependencies": {
"@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.291",
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
"shell-quote": "^1.8.4"
},
"devDependencies": {
"@types/bun": "^1.2.12",
"@types/bun": "^1.4.3",
"@types/node": "^20.0.0",
"@types/shell-quote": "^1.7.5",
"prettier": "3.5.3",
+29 -5
View File
@@ -9,6 +9,7 @@ export type ParsedSdkOptions = {
sdkOptions: SdkOptions;
showFullOutput: boolean;
hasJsonSchema: boolean;
fallbackPermissionMode?: SdkOptions["permissionMode"];
};
// Flags that should accumulate multiple values instead of overwriting
@@ -23,7 +24,7 @@ const ACCUMULATING_FLAGS = new Set([
]);
// Delimiter used to join accumulated flag values
const ACCUMULATE_DELIMITER = "\x00";
export const ACCUMULATE_DELIMITER = "\x00";
// shell-quote treats ()|&;<> as control operators and splits adjacent text
// around them into separate tokens (returned as `{op}` objects, which we then
@@ -46,11 +47,11 @@ const SHELL_META_UNESCAPE = new Map(SHELL_META_PAIRS.map(([k, v]) => [v, k]));
const SHELL_META_ESCAPE_RE = /[()|&;<>]/g;
const SHELL_META_UNESCAPE_RE = /[-]/g;
function escapeShellMeta(s: string): string {
export function escapeShellMeta(s: string): string {
return s.replace(SHELL_META_ESCAPE_RE, (c) => SHELL_META_ESCAPE.get(c)!);
}
function unescapeShellMeta(s: string): string {
export function unescapeShellMeta(s: string): string {
return s.replace(SHELL_META_UNESCAPE_RE, (c) => SHELL_META_UNESCAPE.get(c)!);
}
@@ -130,7 +131,7 @@ function stripShellComments(input: string): string {
* Accumulating flags also consume all consecutive non-flag values
* (e.g., --allowed-tools "Tool1" "Tool2" "Tool3" captures all three).
*/
function parseClaudeArgsToExtraArgs(
export function parseClaudeArgsToExtraArgs(
claudeArgs?: string,
): Record<string, string | null> {
if (!claudeArgs?.trim()) return {};
@@ -186,6 +187,21 @@ function parseClaudeArgsToExtraArgs(
return result;
}
/**
* The permission mode the CLI ends up with: the last one given. `--permission-mode=x`
* is kept under its own key, with the value in the key's name.
*/
function lastPermissionMode(
extraArgs: Record<string, string | null>,
): string | null | undefined {
const modes = Object.entries(extraArgs).flatMap(([flag, value]) => {
if (flag === "permission-mode") return [value];
const [name, inlineValue] = flag.split(/=(.*)/s);
return name === "permission-mode" ? [inlineValue ?? null] : [];
});
return modes.at(-1);
}
/**
* Parse ClaudeOptions into SDK-compatible options
* Uses extraArgs for CLI pass-through instead of duplicating option parsing
@@ -259,8 +275,11 @@ export function parseSdkOptions(options: ClaudeOptions): ParsedSdkOptions {
const directDisallowedTools = options.disallowedTools
? options.disallowedTools.split(",").map((t) => t.trim())
: [];
// Not deduplicated: a rule can hold a comma, so these can be pieces of rules, and the
// SDK joins them again. Dropping a repeated piece would break a rule and the ones after it.
const mergedDisallowedTools = [
...new Set([...extraArgsDisallowedTools, ...directDisallowedTools]),
...extraArgsDisallowedTools,
...directDisallowedTools,
];
delete extraArgs["disallowedTools"];
delete extraArgs["disallowed-tools"];
@@ -351,5 +370,10 @@ export function parseSdkOptions(options: ClaudeOptions): ParsedSdkOptions {
sdkOptions,
showFullOutput,
hasJsonSchema,
// Only when auto mode is what the session ends up asking for: a mode someone
// chose in claude_args must stay as they set it.
...(lastPermissionMode(extraArgs) === "auto" && {
fallbackPermissionMode: options.fallbackPermissionMode,
}),
};
}
+54 -5
View File
@@ -36,11 +36,14 @@ async function fileExists(path: string): Promise<boolean> {
* Creates a prompt configuration for the SDK.
* If a user request file exists alongside the prompt file, returns a multi-block
* SDKUserMessage that enables slash command processing in the CLI.
* Otherwise, returns the prompt as a simple string.
* Otherwise, returns the prompt as a simple string, or as a single-block message
* when the session has to take control requests. Those need its input open, and
* the SDK closes it once the prompt ends, so the prompt then waits for holdOpenUntil.
*/
async function createPromptConfig(
promptPath: string,
showFullOutput: boolean,
holdOpenUntil?: Promise<void>,
): Promise<string | AsyncIterable<SDKUserMessage>> {
const promptContent = await readFile(promptPath, "utf-8");
@@ -50,7 +53,19 @@ async function createPromptConfig(
if (!hasUserRequest) {
// No user request file - use simple string prompt
return promptContent;
if (!holdOpenUntil) return promptContent;
return (async function* (): AsyncGenerator<SDKUserMessage> {
yield {
type: "user",
session_id: "",
message: {
role: "user",
content: [{ type: "text", text: promptContent }],
},
parent_tool_use_id: null,
};
await holdOpenUntil;
})();
}
// User request file exists - create multi-block message
@@ -77,6 +92,7 @@ async function createPromptConfig(
},
parent_tool_use_id: null,
};
await holdOpenUntil;
}
return createMultiBlockMessage();
@@ -164,10 +180,23 @@ function sanitizeSdkOutput(
*/
export async function runClaudeWithSdk(
promptPath: string,
{ sdkOptions, showFullOutput, hasJsonSchema }: ParsedSdkOptions,
{
sdkOptions,
showFullOutput,
hasJsonSchema,
fallbackPermissionMode,
}: ParsedSdkOptions,
): Promise<ClaudeRunResult> {
// Create prompt configuration - may be a string or multi-block message
const prompt = await createPromptConfig(promptPath, showFullOutput);
let releasePrompt = () => {};
const promptHeldOpen = new Promise<void>((resolve) => {
releasePrompt = resolve;
});
const prompt = await createPromptConfig(
promptPath,
showFullOutput,
fallbackPermissionMode ? promptHeldOpen : undefined,
);
if (!showFullOutput) {
console.log(
@@ -187,9 +216,27 @@ export async function runClaudeWithSdk(
let resultMessage: SDKResultMessage | undefined;
try {
for await (const message of query({ prompt, options: sdkOptions })) {
const session = query({ prompt, options: sdkOptions });
for await (const message of session) {
messages.push(message);
if (message.type === "system" && message.subtype === "init") {
// A session that can't use auto mode starts in Manual without an error.
if (fallbackPermissionMode && message.permissionMode === "default") {
core.warning(
`Auto mode is not available for this run, for example because of its model. Using ${fallbackPermissionMode} instead.`,
);
try {
await session.setPermissionMode(fallbackPermissionMode);
} catch {
core.warning(
`Could not switch to ${fallbackPermissionMode}, so tool calls that need permission will be denied.`,
);
}
}
releasePrompt();
}
const sanitized = sanitizeSdkOutput(message, showFullOutput);
if (sanitized) {
console.log(sanitized);
@@ -213,6 +260,8 @@ export async function runClaudeWithSdk(
console.error("SDK execution error:", error);
await writeExecutionFile(messages);
throw new Error(`SDK execution error: ${error}`);
} finally {
releasePrompt();
}
const result: ClaudeRunResult = {
+4
View File
@@ -2,6 +2,8 @@ import { runClaudeWithSdk } from "./run-claude-sdk";
import type { ClaudeRunResult } from "./run-claude-sdk";
import { parseSdkOptions } from "./parse-sdk-options";
import type { PermissionMode } from "@anthropic-ai/claude-agent-sdk";
export type ClaudeOptions = {
claudeArgs?: string;
model?: string;
@@ -14,6 +16,8 @@ export type ClaudeOptions = {
appendSystemPrompt?: string;
fallbackModel?: string;
showFullOutput?: string;
/** Mode to switch to when auto mode was asked for but isn't available. */
fallbackPermissionMode?: PermissionMode;
};
export async function runClaude(
@@ -269,6 +269,17 @@ describe("parseSdkOptions", () => {
expect(result.sdkOptions.extraArgs?.["disallowedTools"]).toBeUndefined();
});
test("keeps rules that share text after a comma", () => {
const result = parseSdkOptions({
claudeArgs: `--disallowedTools 'Bash(/x.sh {a,b}/*)' --disallowedTools 'Bash(git add {a,b}/*)'`,
disallowedTools: "Bash(bun:*)",
});
expect(result.sdkOptions.disallowedTools?.join(",")).toBe(
"Bash(/x.sh {a,b}/*),Bash(git add {a,b}/*),Bash(bun:*)",
);
});
test("should merge disallowedTools from both sources", () => {
const options: ClaudeOptions = {
claudeArgs: '--disallowedTools "Bash"',
@@ -639,3 +650,49 @@ describe("parseSdkOptions", () => {
});
});
});
describe("fallbackPermissionMode", () => {
const fallback = (claudeArgs: string) =>
parseSdkOptions({ claudeArgs, fallbackPermissionMode: "acceptEdits" })
.fallbackPermissionMode;
test("applies when auto mode is the mode asked for", () => {
expect(fallback("--permission-mode auto")).toBe("acceptEdits");
});
test("applies when a later flag asks for auto mode", () => {
expect(fallback("--permission-mode default --permission-mode auto")).toBe(
"acceptEdits",
);
});
test("does not override a mode set after auto", () => {
expect(
fallback("--permission-mode auto --permission-mode default"),
).toBeUndefined();
});
test("does not override a mode set with an equals sign", () => {
expect(
fallback("--permission-mode auto --permission-mode=default"),
).toBeUndefined();
});
test("applies when auto mode is set with an equals sign", () => {
expect(fallback("--permission-mode=auto")).toBe("acceptEdits");
expect(fallback("--permission-mode default --permission-mode=auto")).toBe(
"acceptEdits",
);
});
test("does not apply with no mode", () => {
expect(fallback("--model x")).toBeUndefined();
});
test("is unset unless the caller asks for it", () => {
expect(
parseSdkOptions({ claudeArgs: "--permission-mode auto" })
.fallbackPermissionMode,
).toBeUndefined();
});
});
+15 -27
View File
@@ -7,7 +7,7 @@
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.291",
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
@@ -17,7 +17,7 @@
"zod": "^3.24.4",
},
"devDependencies": {
"@types/bun": "1.2.11",
"@types/bun": "1.4.3",
"@types/node": "^20.0.0",
"@types/node-fetch": "^2.6.12",
"@types/shell-quote": "^1.7.5",
@@ -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].291", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.291", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.291", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.291", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.291", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.291", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.291", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.291", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.291" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-XLEhng37jyekLlB/bCgqHTFeHSgdqAhQw/Xcf8KZGFm8Iwy/UiNt5FvUxA5FK9BYw0MBKHSFbLIs32WOjad5tg=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected].325", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.325", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.325" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-MhSm2Fhk3DA/hhjdCKXDZWlnykpPWJjX42SogllAHMplY9ZKT+Ltb8QPtQxpe225Imfs4A8IKaNE4biivA+fHg=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected].291", "", { "os": "darwin", "cpu": "arm64" }, "sha512-i+BSETc+SE77PZ7uaIqlxODsLdWukB2AwXEEjzih+D2C3S7AKTZTL2trJs1kealZJHLVRWq5utuQjxr9u/ZwAQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected].325", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0u8bTug2zH+zWE8CMiFrm/ldmH20uA9B/zhXpI7ATHFJnpPMdwTqE56CFM0m3LOwnNum0jpRn7XV1dn6Pf2pqA=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected].291", "", { "os": "darwin", "cpu": "x64" }, "sha512-hJ3ys972EImbEIbImvBv+vwX9JgstZQ3HkOx6fKEBlqp8NXoxTVchdiHrJ/IBTV1qzfzuvCI6ZjptuvBDPCutA=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected].325", "", { "os": "darwin", "cpu": "x64" }, "sha512-HD3YRFyM5H5QH2usS/WD6gobk3BEp2jq9dKyrkhAVdQIqFMlrcSrRhGA0i3R1IOLxtPAYkmDGepZ62k1kMOW9Q=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected].291", "", { "os": "linux", "cpu": "arm64" }, "sha512-hDRXpKfniuNWwFuSfu/MTp2uTKJyRW3QqhphVfx02VwOPd9gmOne9KWxp9N+FXA0I3TzVi7fF6mVNGIxhMjnXQ=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected].325", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-28oVrCEN6M6MJP8Od4SK/scal1QdLbn5Sci+qL8j55l6csHtPeUYF9zdjWLniFKph43pejfZf5te/Vf/bwehkw=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected].291", "", { "os": "linux", "cpu": "arm64" }, "sha512-pHrXszKDedaBiJAiVdgJZ9HRKRmBTFjIhMrBZCcn6evCPD97iwiS3vbGnC+oM4Usqgvplpj6Zv0vKYGxXud3fA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected].325", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-72y6QNRZC4eMCxne/wNsuwNHsViSkgFKlYMCUVXxmiR9gpIMd3rf++oJMIsSuEAQqzqT7jwCrdtibv6R4bx5PA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected].291", "", { "os": "linux", "cpu": "x64" }, "sha512-KZGLgT5HF2wyJuzTOpRj/iipRjhI7MZ9bsMpIcJZjYt6d1azMDABo8rr5vrlU+7kcZZJq/oBKqbLN0M1DaO30g=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected].325", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-wXEWbDmNYiorY5EKASYjvQct8zHShUPmAS9N/IAsgPA/cx2vsOFqPQw8jRQKeaW6AmFgx7k/Wf7THalNXbMEkQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected].291", "", { "os": "linux", "cpu": "x64" }, "sha512-r7HzdHvlXo4nvzVKyqEYfILRUqfsC5S6fGLivXutxkyFLnhYpuuOxaSMzK0OAhyS/HPdg9PbK2i4u52yljVhvQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected].325", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-BHewYUTd7mDLR5iHTVt6Q28gJKLC5C24b1H3NM0qGt9dxnjVUh1Lza52GzHY2Rb9hAPQymLSXWuVh1OFoFQatA=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected].291", "", { "os": "win32", "cpu": "arm64" }, "sha512-oY79rhNEkPB+yCQTPMkuwHiBAwHwodoj+6jwJAB578pHqOTsMWn91MJySsLTJlHlPMbwCUpbwen4RGMiGhnwOw=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected].325", "", { "os": "win32", "cpu": "arm64" }, "sha512-NH3I2o105oKK8lfJ5RlzCp+YTZn3qncwQ1xSzQ4jqn7LUddThIidpFU7B+TKQxh1X9eayAp7EtrBQ36mXflQwQ=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected].291", "", { "os": "win32", "cpu": "x64" }, "sha512-Kf+Xjdymr9xP6KLiQdnKJAykO79HPWr2q1JPVdlAYm0vz67KaUiKA8H/YFiMzoFurpdaJfqm9HvlQss+zeDlew=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected].325", "", { "os": "win32", "cpu": "x64" }, "sha512-pjqVL++V/2oMJ6u1HdB608bcTUvzts1e8hX93Q8khasy2JB+R823bnvpQapcOurOWB3+v1X2JXIjXyWcGPJCQQ=="],
"@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=="],
@@ -75,8 +75,6 @@
"@octokit/plugin-paginate-rest": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^12.6.0" }, "peerDependencies": { "@octokit/core": "5" } }, "sha512-u3KYkGF7GcZnSD/3UP0S7K5XUFT2FkOQdcfXZGZQPGv3lm4F2Xbf71lvjldr8c1H3nNbF+33cLEkWYbokGWqiQ=="],
"@octokit/plugin-request-log": ["@octokit/[email protected]", "", { "peerDependencies": { "@octokit/core": ">=6" } }, "sha512-n/lNeCtq+9ofhC15xzmJCNKP2BWTv8Ih2TTy+jatNCCq/gQP/V7rK3fjIfuz0pDWDALO/o/4QY4hyOF6TQQFUw=="],
"@octokit/plugin-rest-endpoint-methods": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^12.6.0" }, "peerDependencies": { "@octokit/core": "5" } }, "sha512-xV1b+ceKV9KytQe3zCVqjg+8GTGfDYwaT1ATU5isiUyVtlVAO3HNdzpS4sr4GBx4hxQ46s7ITtZrAsxG22+rVg=="],
"@octokit/request": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/endpoint": "^9.0.6", "@octokit/request-error": "^5.1.1", "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" } }, "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw=="],
@@ -89,7 +87,7 @@
"@octokit/webhooks-types": ["@octokit/[email protected]", "", {}, "sha512-S8u2cJzklBC0FgTwWVLaM8tMrDuDMVE4xiTK4EYXM9GntyvrdbSoxqDQa+Fh57CCNApyIpyeqPhhFEmHPfrXgw=="],
"@types/bun": ["@types/bun@1.2.11", "", { "dependencies": { "bun-types": "1.2.11" } }, "sha512-ZLbbI91EmmGwlWTRWuV6J19IUiUC5YQ3TCEuSHI3usIP75kuoA8/0PVF+LTrbEnVc8JIhpElWOxv1ocI1fJBbw=="],
"@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-cuVNgarYWZqxRJDQHEB58GEONhOK79QVR/qYx4S7kcUObQvUwvFnYxJuuHUKm2aieN9X3yZB4LZsuYNU1Qphsw=="],
@@ -107,7 +105,7 @@
"body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.0", "http-errors": "^2.0.0", "iconv-lite": "^0.6.3", "on-finished": "^2.4.1", "qs": "^6.14.0", "raw-body": "^3.0.0", "type-is": "^2.0.0" } }, "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg=="],
"bun-types": ["bun-types@1.2.11", "", { "dependencies": { "@types/node": "*" } }, "sha512-dbkp5Lo8HDrXkLrONm6bk+yiiYQSntvFUzQp0v3pzTAsXk6FtgVMjdQ+lzFNVAmQFUkPQZ3WMZqH5tTo+Dp/IA=="],
"bun-types": ["bun-types@1.4.3", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
"bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
@@ -333,8 +331,6 @@
"@octokit/plugin-paginate-rest/@octokit/types": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/openapi-types": "^20.0.0" } }, "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw=="],
"@octokit/plugin-request-log/@octokit/core": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/auth-token": "^5.0.0", "@octokit/graphql": "^8.2.2", "@octokit/request": "^9.2.3", "@octokit/request-error": "^6.1.8", "@octokit/types": "^14.0.0", "before-after-hook": "^3.0.2", "universal-user-agent": "^7.0.0" } }, "sha512-kIU8SLQkYWGp3pVKiYzA5OSaNF5EE03P/R8zEmmrG6XwOg5oBjXyQVVIauQ0dgau4zYhpZEhJrvIYt6oM+zZZA=="],
"@octokit/plugin-rest-endpoint-methods/@octokit/types": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/openapi-types": "^20.0.0" } }, "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw=="],
"@octokit/request/@octokit/types": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/openapi-types": "^24.2.0" } }, "sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA=="],
@@ -347,6 +343,8 @@
"@octokit/rest/@octokit/plugin-paginate-rest": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^13.10.0" }, "peerDependencies": { "@octokit/core": ">=6" } }, "sha512-n5KPteiF7pWKgBIBJSk8qzoZWcUkza2O6A0za97pMGVrGfPdltxrfmfF5GucHYvHGZD8BdaZmmHGz5cX/3gdpw=="],
"@octokit/rest/@octokit/plugin-request-log": ["@octokit/[email protected]", "", { "peerDependencies": { "@octokit/core": ">=6" } }, "sha512-n/lNeCtq+9ofhC15xzmJCNKP2BWTv8Ih2TTy+jatNCCq/gQP/V7rK3fjIfuz0pDWDALO/o/4QY4hyOF6TQQFUw=="],
"@octokit/rest/@octokit/plugin-rest-endpoint-methods": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^13.10.0" }, "peerDependencies": { "@octokit/core": ">=6" } }, "sha512-9Pas60Iv9ejO3WlAX3maE1+38c5nqbJXV5GrncEfkndIpZrJ/WPMRd2xYDcPPEt5yzpxcjw9fWNoPhsSGzqKqw=="],
"accepts/mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA=="],
@@ -367,14 +365,6 @@
"@octokit/plugin-paginate-rest/@octokit/types/@octokit/openapi-types": ["@octokit/[email protected]", "", {}, "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA=="],
"@octokit/plugin-request-log/@octokit/core/@octokit/auth-token": ["@octokit/[email protected]", "", {}, "sha512-JcQDsBdg49Yky2w2ld20IHAlwr8d/d8N6NiOXbtuoPCqzbsiJgF633mVUw3x4mo0H5ypataQIX7SFu3yy44Mpw=="],
"@octokit/plugin-request-log/@octokit/core/@octokit/request": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/endpoint": "^10.1.4", "@octokit/request-error": "^6.1.8", "@octokit/types": "^14.0.0", "fast-content-type-parse": "^2.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-q8ybdytBmxa6KogWlNa818r0k1wlqzNC+yNkcQDECHvQo8Vmstrg18JwqJHdJdUiHD2sjlwBgSm9kHkOKe2iyA=="],
"@octokit/plugin-request-log/@octokit/core/@octokit/request-error": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^14.0.0" } }, "sha512-WEi/R0Jmq+IJKydWlKDmryPcmdYSVjL3ekaiEL1L9eo1sUnqMJ+grqmC9cjk7CA7+b2/T397tO5d8YLOH3qYpQ=="],
"@octokit/plugin-request-log/@octokit/core/before-after-hook": ["[email protected]", "", {}, "sha512-Nik3Sc0ncrMK4UUdXQmAnRtzmNQTAAXmXIopizwZ1W1t8QmfJj+zL4OA2I7XPTPW5z5TDqv4hRo/JzouDJnX3A=="],
"@octokit/plugin-rest-endpoint-methods/@octokit/types/@octokit/openapi-types": ["@octokit/[email protected]", "", {}, "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA=="],
"@octokit/request-error/@octokit/types/@octokit/openapi-types": ["@octokit/[email protected]", "", {}, "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg=="],
@@ -401,8 +391,6 @@
"type-is/mime-types/mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"@octokit/plugin-request-log/@octokit/core/@octokit/request/@octokit/endpoint": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^14.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-OlYOlZIsfEVZm5HCSR8aSg02T2lbUWOsCQoPKfTXJwDzcHQBrVBGdGXb89dv2Kw2ToZaRtudp8O3ZIYoaOjKlA=="],
"@octokit/rest/@octokit/core/@octokit/request/@octokit/endpoint": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^14.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-OlYOlZIsfEVZm5HCSR8aSg02T2lbUWOsCQoPKfTXJwDzcHQBrVBGdGXb89dv2Kw2ToZaRtudp8O3ZIYoaOjKlA=="],
"@octokit/rest/@octokit/plugin-paginate-rest/@octokit/types/@octokit/openapi-types": ["@octokit/[email protected]", "", {}, "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg=="],
+5 -2
View File
@@ -15,12 +15,15 @@
## What Claude Cannot Do
The action doesn't give Claude tools for these. In [auto mode](./usage.md#permission-mode), the default, a tool call outside your allow rules can still run if the safety review passes it. For a strict list, use `--permission-mode acceptEdits`.
- **Submit PR Reviews**: Claude cannot submit formal GitHub PR reviews
- **Approve PRs**: For security reasons, Claude cannot approve pull requests
- **Push to Other Branches**: By default, Claude can only push to the branch it was set up on: a new branch for an issue or closed PR, or the branch of an open PR. For a PR from a fork, that is a `pr-N` branch in your repository, and the fork's branch is not updated
- **Post Multiple Comments**: Claude only acts by updating its initial comment
- **Execute Commands Outside Its Context**: Claude only has access to the repository and PR/issue context it's triggered in
- **Run Arbitrary Bash Commands**: By default, Claude cannot execute Bash commands unless explicitly allowed using the `allowed_tools` configuration
- **Perform Branch Operations**: Cannot merge branches, rebase, or perform other git operations beyond pushing commits
- **Run Bash Commands Unchecked**: A Bash command runs only if an allow rule covers it or the safety review passes it
- **Perform Branch Operations**: Claude is instructed not to merge branches, rebase, or perform other git operations beyond pushing commits
## How It Works
+6 -1
View File
@@ -140,10 +140,13 @@ To allow Claude to view workflow run results, job logs, and CI status:
3. **Claude will automatically get access to CI/CD tools**:
When you enable `actions: read`, Claude can use the following MCP tools:
- `mcp__github_ci__get_ci_status` - View workflow run statuses
- `mcp__github_ci__get_workflow_run_details` - Get detailed workflow information
- `mcp__github_ci__download_job_log` - Download and analyze job logs
On pull requests from outside contributors, the contributor can control the text of job logs. See [Security](./security.md#running-code-from-pull-requests) for how to turn off the tools that read them.
### Example: Debugging Failed CI Runs
```yaml
@@ -228,7 +231,7 @@ By default, Claude only has access to:
- Comment management (creating/updating comments)
- Basic GitHub operations
Claude does **not** have access to execute arbitrary Bash commands by default. If you want Claude to run specific commands (e.g., npm install, npm test), you must explicitly allow them using the `claude_args` configuration:
In [auto mode](./usage.md#permission-mode), the default, a safety review decides any Bash command that no allow rule covers. To let specific commands (e.g., npm install, npm test) run without review, or to allow them under `--permission-mode acceptEdits`, add them with `--allowedTools`:
**Note**: If your repository has a `.mcp.json` file in the root directory, Claude will automatically detect and use the MCP server tools defined there. However, these tools still need to be explicitly allowed.
@@ -241,6 +244,8 @@ Claude does **not** have access to execute arbitrary Bash commands by default. I
# ... other inputs
```
**Note**: On pull requests whose author does not have write access, commands that commonly run repository code, such as `npm`, are denied even if you allow them here. See [Security](./security.md#running-code-from-pull-requests).
**Note**: The base GitHub tools are always included. Use `--allowedTools` to add additional tools (including specific Bash commands), and `--disallowedTools` to prevent specific tools from being used.
## Custom Model
+3 -3
View File
@@ -98,7 +98,7 @@ Yes! Claude can access GitHub Actions workflow runs, job logs, and test results
actions: read
```
Claude will then be able to analyze CI failures and help debug workflow issues. For running tests locally before commits, you can still instruct Claude to do so in your request.
Claude will then be able to analyze CI failures and help debug workflow issues. For running tests locally before commits, you can still instruct Claude to do so in your request, except on pull requests whose author does not have write access. For pull requests from forks, see [Security](./security.md#running-code-from-pull-requests) for another way to get test results.
### Why does Claude only update one comment instead of creating new ones?
@@ -170,11 +170,11 @@ claude_args: |
### Why doesn't Claude execute my bash commands?
The Bash tool is **disabled by default** for security. To enable individual bash commands using `claude_args`:
In [auto mode](./usage.md#permission-mode), the default, a safety review decides any Bash command that no allow rule covers, and it can block yours. With `--permission-mode acceptEdits` or `default`, most Bash commands are denied unless allowed. To allow individual bash commands using `claude_args`:
```yaml
claude_args: |
--allowedTools "Bash(npm:*),Bash(git:*)" # Allows only npm and git commands
--allowedTools "Bash(npm:*),Bash(git:*)" # Allows npm and git commands without asking
```
### Can Claude work across multiple repositories?
+2
View File
@@ -142,6 +142,8 @@ The `track_progress` input only works with these GitHub events:
- `labeled` - Label added to issue
- `assigned` - Issue assigned to user
> **Note**: On `labeled` and `assigned` issue events with `track_progress` and a `prompt`, the label must match `label_trigger` (default `claude`), and the assignee must match `assignee_trigger` if you set one. To use another label, set `label_trigger` to it. To filter labels in your workflow's `if:`, set `label_trigger: ""`, which accepts any label when a `prompt` is set.
> **Note**: Using `track_progress: true` with unsupported events will cause an error.
### Custom Template with Variables
+64 -6
View File
@@ -2,9 +2,12 @@
## 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`.
- **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.
- On `pull_request` events, a bot's activity does not vouch for the pull request. Before a run starts, its author must also have write access or be an allowed bot.
- When `allowed_bots` is set, the token stays out of `.git/config` and git gets it from a credential helper that reads `GH_TOKEN`. A later step that uses the `origin` remote to push, or to fetch, pull or update submodules on a private repository, then needs its own credentials. `origin` names the username `x-access-token`, so those must come from `GH_TOKEN`, `GIT_ASKPASS`, a credential saved under that username, or a remote URL the step sets itself. The token is still in Claude's environment.
- Prefer an explicit list over `'*'`
- Only list App names you trust
- If you need `'*'`, scope workflow `permissions:` to the minimum required
@@ -15,6 +18,7 @@
- Is designed for automation workflows where user permissions are already restricted by the workflow's permission scope
- When set, Claude does a best-effort scrub of Anthropic, cloud, and GitHub Actions secrets from subprocess environments. On Linux runners with bubblewrap available, subprocesses additionally run with PID-namespace isolation. This reduces but does not eliminate prompt injection risk — keep workflow permissions minimal and validate all outputs. Set `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: 0` in your workflow or job `env:` block to opt out.
- Optionally set `CLAUDE_CODE_SCRIPT_CAPS` in your workflow `env:` block to limit how many times Claude can call specific scripts per run. Value is JSON: `{"script-name.sh": maxCalls}`. Example: `CLAUDE_CODE_SCRIPT_CAPS: '{"edit-issue-labels.sh":2}'` allows at most 2 calls to `edit-issue-labels.sh`. Useful for write-capable helper scripts.
- Runs with this input or `allowed_bots` keep the earlier permission defaults instead of auto mode, so the safety review can't pass a call those defaults deny, unless `claude_args` sets another [permission mode](./usage.md#permission-mode)
- When using `allowed_non_write_users`, always pass `github_token: ${{ secrets.GITHUB_TOKEN }}`. The auto-generated workflow token is scoped to the job's declared permissions and expires when the job completes. **Do not use a personal access token** — a static token does not rotate between runs and could be partially or fully recovered over time via prompt injection. Restricting allowed tools via `claude_args` reduces the rate of recovery but may not eliminate the risk. We recommend restricting allowed tools (e.g. `claude_args: '--allowedTools "Bash(gh issue view:*)"'`) to the minimum required when using `allowed_non_write_users`.
- **Token Permissions**: The GitHub app receives only a short-lived token scoped specifically to the repository it's operating in
- **No Cross-Repository Access**: Each action invocation is limited to the repository where it was triggered
@@ -22,7 +26,7 @@
## Using this action with `pull_request_target` or `workflow_run`
For `workflow_run` events, the action checks the repository access of the actor that started the upstream run (for example, the author of the fork pull request that triggered your CI workflow) in addition to the workflow actor. If that actor does not have write access, the action stops before running Claude. To run on `workflow_run` events downstream of pull requests from contributors without write access, add those users to `allowed_non_write_users` and pass `github_token: ${{ secrets.GITHUB_TOKEN }}` — see the notes on that input above and keep the workflow's permissions minimal.
For `workflow_run` events, the action checks the repository access of the actor that started the upstream run (for example, the author of the fork pull request that triggered your CI workflow) in addition to the workflow actor. When the run came from a fork, it also checks the fork's owner, because GitHub credits a run to whoever caused it, such as a maintainer reopening the pull request. If any of these accounts does not have write access, the action stops before running Claude. To run on `workflow_run` events downstream of pull requests from contributors without write access, add those users to `allowed_non_write_users` and pass `github_token: ${{ secrets.GITHUB_TOKEN }}` — see the notes on that input above and keep the workflow's permissions minimal.
`pull_request_target` and `workflow_run` execute with the **base repository's secrets**. If your workflow checks out the PR head (`ref: ${{ github.event.pull_request.head.sha }}` for `pull_request_target`, `ref: ${{ github.event.workflow_run.head_sha }}` for `workflow_run`) into `$GITHUB_WORKSPACE` before this action, the action and Claude run with that checkout as the working directory.
@@ -53,21 +57,69 @@ This is general guidance for these event types — see [GitHub's documentation](
### Which files come from the base branch on pull requests
When the action runs against a pull request, it restores a fixed list of Claude configuration paths from the PR base branch before starting Claude: `.claude/`, `.mcp.json`, `.claude.json`, `.gitmodules`, `.ripgreprc`, `CLAUDE.md`, `CLAUDE.local.md`, and `.husky/`. Paths in that list that do not exist on the base branch are removed, and the PR-authored versions are kept under `.claude-pr/` for reference only.
When the action runs against a pull request, it restores a fixed list of Claude configuration paths from the PR base branch before starting Claude: `.claude/`, `.mcp.json`, `.claude.json`, `.gitmodules`, `.ripgreprc`, `CLAUDE.md`, `CLAUDE.local.md`, `AGENTS.md`, and `.husky/`. Paths in that list that do not exist on the base branch are removed, and the PR-authored versions are kept under `.claude-pr/` for reference only.
Everything else in the working tree — including `package.json`, lockfiles, `Makefile`, `node_modules/`, and formatter/linter config files — stays at the PR head. If a hook, `apiKeyHelper`, or `statusLine` command in your base-branch `.claude/settings.json` runs a package-manager script (`bun run …`, `npm run …`, `yarn …`, `pnpm run …`), a `make` target, a repo-relative script, or a tool that loads executable project config, that command resolves through files the pull request supplies. Keep such commands self-contained: invoke the tool directly with a pinned version and pass its configuration on the command line (for example `bunx [email protected] --no-config --write .` rather than `bun run format`).
Everything else in the working tree — including `package.json`, lockfiles, `Makefile`, `node_modules/`, and formatter/linter config files — stays at the PR head, apart from the files described below. If a hook, `apiKeyHelper`, or `statusLine` command in your base-branch `.claude/settings.json` runs a package-manager script (`bun run …`, `npm run …`, `yarn …`, `pnpm run …`), a `make` target, a repo-relative script, or a tool that loads executable project config, that command resolves through files the pull request supplies. Keep such commands self-contained: invoke the tool directly with a pinned version and pass its configuration on the command line (for example `bunx [email protected] --no-config --write .` rather than `bun run format`).
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 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.
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.
### 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.
By default, when the pull request's author does not have write access, the action denies commands that commonly run repository code (package managers, test runners, interpreters and shells), even if `claude_args` allows them. Claude can still read and edit files, commit and push. Bots count as authors without write access, even if they are listed in `allowed_bots`, and if the check fails the author is treated the same way. Issues and pull requests from authors with write access are not affected. Runs on `workflow_run`, `workflow_dispatch`, `repository_dispatch` and `schedule` events are not covered, so follow the checkout guidance above if those check out pull request code. On a closed or merged pull request, tag mode works from the base branch rather than the pull request's code, so nothing is denied.
- **This is a list of common commands, not a sandbox.** A rule such as `Bash(./scripts/test.sh)` stays allowed, and the action logs a warning with the number of `Bash` rules in `claude_args` that the list does not cover. Rules in the `settings` input or settings files are not checked. Other ways of writing a command, such as `git --no-pager -c`, may not match the list. Add your own rules with `--disallowedTools` if they can run pull request code.
- **Trust follows the pull request's author.** If someone with write access opens a pull request from another person's branch, or pushes someone else's commits, that code is treated as theirs. Review it before asking Claude to run it.
- **Commands outside the list follow your permission mode.** With `--permission-mode auto`, a command that no rule covers runs only if Claude Code's safety review passes it, which we recommend where it is available. In the modes that ask for approval, such a command is denied, because a workflow has no one to approve it. Either way, a rule in `--allowedTools` skips that decision, so don't rely on the review for commands you allow. If `claude_args` turns off permission checks, for example with `bypassPermissions`, commands outside the list run without approval, and the action logs a warning.
- **Text can still steer Claude.** On an issue or a trusted author's pull request these commands stay allowed, so text from an outside contributor could try to get Claude to edit a file and then run it. Keep the rules you grant in `claude_args` as narrow as you can.
- **Other broad rules weaken the protections.** `Write` lets Claude write outside the workspace, and `Bash(git:*)` can still run programs through forms this list does not deny, such as `git rebase --exec`. Avoid them in workflows that handle outside contributions.
**Getting test results:** on pull requests from forks, run the tests in a separate `pull_request` workflow that needs no secrets, and let Claude read the outcome. The pull request's code then runs outside the job that holds Claude's tokens, which is not the case with `restrict_untrusted_prs: false`.
1. In the test workflow, set `permissions: contents: read`. GitHub also limits the token to read access and withholds secrets on pull requests from forks of a public repository. That limit is the real protection, because a pull request can edit the workflow file.
2. Set your repository to require approval for all external contributors. Review the changes, including workflow files, and then approve the runs. GitHub doesn't ask for approval on pull requests from members of your organization.
3. In Claude's workflow, add `actions: read` to the job's `permissions`. In tag mode, Claude can then see the pull request's workflow runs and their results.
4. When the runs finish, mention `@claude` in a comment on the pull request's conversation. Mentions in reviews don't work on pull requests from forks, because GitHub gives those runs no credentials.
Treat what Claude reports as a pointer to the run. Results are for the latest commit on the pull request, so they don't cover edits Claude makes. A run with the conclusion `action_required` is waiting for approval and has neither passed nor failed. A pull request can also change what a workflow does and what it is called.
Job logs, and job and step names, are text the pull request controls. To turn off the tools that read them, add `--disallowedTools "mcp__github_ci__download_job_log,mcp__github_ci__get_workflow_run_details"` to `claude_args`. Claude may still reach logs through other commands that you allow or that auto mode's review passes, such as `gh`.
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, tool config comes from the base 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.
### 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.
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.
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:
- It is not a sandbox. Code running on the runner, for example through an allowed `npm test`, can stop the action before it restores anything, or change the files later steps run, including the code of this and other actions. An allow rule for `Write` can reach those files too, so treat it like allowing code to run.
- A run that is cancelled or times out during the session does not restore anything, and later `always()` and post steps still run.
- Submodule config, a repository checked out to a subdirectory, and an `include.path` target that does not exist yet are not restored.
- The git settings need git 2.31 or newer, and `safe.bareRepository` needs 2.38. On older versions they have no effect.
### `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 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, 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
In its default configuration, **Claude does not create pull requests automatically** when responding to `@claude` mentions. Instead:
- Claude commits code changes to a new branch
- Claude commits code changes to a new branch, or to the pull request's branch, through wrapper scripts in the action. A deny rule for `git add`, `git rm`, `git commit` or `git push` in `claude_args` also covers those scripts, including a narrower rule such as `git add -A:*`. A deny rule in a settings file doesn't, so pass it in `claude_args`
- Claude's push command can't update any other branch. For a pull request from a fork, its branch is `pr-N` in your repository, and the fork's branch is not updated
- Branch protection on your default branch is still worth having: a workflow can allow other push commands, and a pull request opened from the default branch has that branch as its own
- Claude provides a **link to the GitHub PR creation page** in its response
- **The user must click the link and create the PR themselves**, ensuring human oversight before any code is proposed for merging
@@ -79,6 +131,10 @@ This design ensures that users retain full control over what pull requests are c
On public repos, you can also use `include_comments_by_actor` to allowlist which users' comments are passed to Claude, reducing exposure to untrusted input. Use `exclude_comments_by_actor` to filter out noisy bot comments (e.g., `dependabot[bot]`, `renovate[bot]`). If an actor matches both lists, exclusion takes priority. See [Usage](./usage.md) for details.
### Auto mode is a review, not a boundary
By default the action uses [auto mode](./usage.md#permission-mode), where a safety review decides tool calls that your allow rules don't cover. It catches many unsafe actions, but a call can still run if the review passes it. For a strict list of what Claude may run, use `--permission-mode acceptEdits` or `default`.
## GitHub App Permissions
The [Claude Code GitHub app](https://github.com/apps/claude) requests the following permissions:
@@ -114,6 +170,8 @@ This uses GitHub's API to create commits, which automatically signs them as veri
This is the simplest option and requires no additional setup. However, because it uses the GitHub API instead of git CLI, it cannot perform complex git operations like rebasing, cherry-picking, or interactive history manipulation.
With `prompt`, a run on an issue commits to `issue-N`. A run on a pull request commits to the pull request's branch, or to `pr-N` if that branch isn't known to be in this repository. `issue-N` and `pr-N` start from the base branch. To use another branch, set `CLAUDE_BRANCH` in the step's `env`.
### Option 2: SSH Signing Key (ssh_signing_key)
This uses an SSH key to sign commits via git CLI. Use this option when you need both signed commits AND standard git operations (rebasing, cherry-picking, etc.):
+52 -7
View File
@@ -33,9 +33,9 @@ jobs:
# --model claude-4-0-sonnet-20250805
# Optional: add custom plugin marketplaces
# plugin_marketplaces: "https://github.com/user/marketplace1.git\nhttps://github.com/user/marketplace2.git"
# plugin_marketplaces: "https://github.com/anthropics/claude-plugins-official.git\nhttps://github.com/user/marketplace.git"
# Optional: install Claude Code plugins
# plugins: "code-review@claude-code-plugins\nfeature-dev@claude-code-plugins"
# plugins: "code-review@claude-plugins-official\nfeature-dev@claude-plugins-official"
# Optional: add custom trigger phrase (default: @claude)
# trigger_phrase: "/claude"
@@ -72,7 +72,7 @@ jobs:
| `use_bedrock` | Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API | No | `false` |
| `use_vertex` | Use Google Vertex AI with OIDC authentication instead of direct Anthropic API | No | `false` |
| `assignee_trigger` | The assignee username that triggers the action (e.g. @claude). Only used for issue assignment | No | - |
| `label_trigger` | The label name that triggers the action when applied to an issue (e.g. "claude") | No | - |
| `label_trigger` | The label name that triggers the action when applied to an issue (e.g. "claude"). With `prompt` and `track_progress`, an empty value accepts any label | No | - |
| `trigger_phrase` | The trigger phrase to look for in comments, issue/PR bodies, and issue titles | No | `@claude` |
| `branch_prefix` | The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format) | No | `claude/` |
| `settings` | Claude Code settings as JSON string or path to settings JSON file | No | "" |
@@ -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 | "" |
| `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 | "" |
| `path_to_bun_executable` | Optional path to a custom Bun executable. Skips automatic Bun installation. Useful for Nix, custom containers, or specialized environments | No | "" |
@@ -112,6 +113,46 @@ These inputs are deprecated and will be removed in a future version:
> **Note**: This action is currently in beta. Features and APIs may change as we continue to improve the integration.
## Permission Mode
The action runs Claude in [auto mode](https://code.claude.com/docs/en/permission-modes) by default. Reads and file edits in the workspace run without asking, and a safety review decides any other tool call that your allow rules don't cover. Narrow allow rules like `Bash(npm test)` skip the review, and broad ones like `Bash(*)` or package-manager run commands are ignored in this mode.
### Opting out
Set another mode in `claude_args`. These are the earlier defaults:
```yaml
- uses: anthropics/claude-code-action@v1
with:
# For @claude mentions: allow file edits in the workspace, and deny what no rule covers
claude_args: --permission-mode acceptEdits
# For workflows with a prompt: deny what no rule covers
# claude_args: --permission-mode default
```
Opt out if your workflow relies on `--allowedTools` as a strict list, because auto mode can run other tool calls when the review passes.
### When auto mode doesn't apply
- **Unsupported model or organization setting:** auto mode needs a [supported model](https://code.claude.com/docs/en/permission-modes#eliminate-prompts-with-auto-mode), and an administrator can turn it off. The session then starts in Manual. For `@claude` mentions, the action logs a warning and switches to `acceptEdits`. With a `prompt`, it stays in Manual and denies what no rule covers.
- **`allowed_non_write_users` or `allowed_bots` is set:** sessions keep the earlier defaults, because other people's text reaches these runs without a write-access check, so the review can't pass a call those defaults deny. Add `--permission-mode auto` to opt in.
- **`ANTHROPIC_BASE_URL` is set:** sessions keep the earlier defaults, because the safety check depends on what a gateway passes through. Add `--permission-mode auto` once your gateway supports it.
- **`path_to_claude_code_executable` is set:** sessions keep the earlier defaults, because a Claude Code version that predates auto mode exits on the flag. Add `--permission-mode auto` if your version supports it.
- **The `settings` input sets `env.ANTHROPIC_BASE_URL`, sets a `permissions.defaultMode` other than `auto`, or is a file path:** sessions keep the earlier defaults, including for a file that sets neither, because a pull request can change the file. Workflows with a prompt then use the mode in your settings. For `@claude` mentions, `acceptEdits` still overrides it, so pass yours in `claude_args`.
- **`--dangerously-skip-permissions`:** this still takes priority over any mode.
### Provider notes
- Where the server's check doesn't reach a session, Claude Code makes its own [classifier requests, which count toward token usage](https://code.claude.com/docs/en/auto-mode-classifier-billing).
- On Amazon Bedrock, your account may need access to the classifier's model, or actions that need the review are blocked. See the [error reference](https://code.claude.com/docs/en/errors.md#auto-mode-cannot-determine-the-safety-of-an-action).
### Upgrading
- Tool calls that used to be denied can now run if the review passes.
- Allow rules that auto mode ignores no longer approve those commands on their own.
- The action checks only JSON in the `settings` input, not settings files such as `.claude/settings.json` in your repository. If one of those points `ANTHROPIC_BASE_URL` to a gateway or sets `permissions.defaultMode`, auto mode still applies, so set the mode you want in `claude_args`.
## Upgrading from v0.x?
For a comprehensive guide on migrating from v0.x to v1.0, including step-by-step instructions and examples, see our **[Migration Guide](./migration-guide.md)**.
@@ -231,21 +272,25 @@ All structured output fields are available in the `structured_output` output as
**In GitHub Actions expressions:**
```yaml
if: fromJSON(steps.analyze.outputs.structured_output).is_flaky == true
run: |
CONFIDENCE=${{ fromJSON(steps.analyze.outputs.structured_output).confidence }}
if: |
fromJSON(steps.analyze.outputs.structured_output).is_flaky == true &&
fromJSON(steps.analyze.outputs.structured_output).confidence >= 0.7
run: ./retry-tests.sh
```
**In bash with jq:**
```yaml
- name: Process results
env:
OUTPUT: ${{ steps.analyze.outputs.structured_output }}
run: |
OUTPUT='${{ steps.analyze.outputs.structured_output }}'
IS_FLAKY=$(echo "$OUTPUT" | jq -r '.is_flaky')
SUMMARY=$(echo "$OUTPUT" | jq -r '.summary')
```
Always pass these values to a script through `env:`, as above. GitHub puts a `${{ }}` expression's value into the script before the shell reads it, so a quote or other shell syntax in Claude's answer can break the script or run as a command.
**Note**: Due to GitHub Actions limitations, composite actions cannot expose dynamic outputs. All fields are bundled in the single `structured_output` JSON string.
### Complete Example
+4 -3
View File
@@ -55,8 +55,8 @@ jobs:
GH_TOKEN: ${{ github.token }}
WORKFLOW_NAME: ${{ github.event.workflow_run.name }}
HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
OUTPUT: ${{ steps.detect.outputs.structured_output }}
run: |
OUTPUT='${{ steps.detect.outputs.structured_output }}'
CONFIDENCE=$(echo "$OUTPUT" | jq -r '.confidence')
SUMMARY=$(echo "$OUTPUT" | jq -r '.summary')
@@ -72,8 +72,9 @@ jobs:
if: |
fromJSON(steps.detect.outputs.structured_output).is_flaky == true &&
fromJSON(steps.detect.outputs.structured_output).confidence < 0.7
env:
OUTPUT: ${{ steps.detect.outputs.structured_output }}
run: |
OUTPUT='${{ steps.detect.outputs.structured_output }}'
CONFIDENCE=$(echo "$OUTPUT" | jq -r '.confidence')
echo "⚠️ Possible flaky test but confidence too low ($CONFIDENCE)"
@@ -85,8 +86,8 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
OUTPUT: ${{ steps.detect.outputs.structured_output }}
run: |
OUTPUT='${{ steps.detect.outputs.structured_output }}'
IS_FLAKY=$(echo "$OUTPUT" | jq -r '.is_flaky')
CONFIDENCE=$(echo "$OUTPUT" | jq -r '.confidence')
SUMMARY=$(echo "$OUTPUT" | jq -r '.summary')
+2 -2
View File
@@ -12,7 +12,7 @@
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.291",
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
@@ -22,7 +22,7 @@
"zod": "^3.24.4"
},
"devDependencies": {
"@types/bun": "1.2.11",
"@types/bun": "1.4.3",
"@types/node": "^20.0.0",
"@types/node-fetch": "^2.6.12",
"@types/shell-quote": "^1.7.5",
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
# Wrapper around `git add` that only stages files. Without it, an allow rule for
# `git add` also permits flags that open an editor or read a file of paths.
#
# Usage:
# git-add.sh [-A] [-u] [-v] [--chmod=+x|--chmod=-x] [--] <paths>
source "$(dirname "${BASH_SOURCE[0]}")/git-env.sh"
paths_only=false
for arg in "$@"; do
if [[ "$paths_only" == true ]]; then
continue
fi
case "$arg" in
-A | --all | -u | --update | -v | --verbose | --chmod=+x | --chmod=-x) ;;
--) paths_only=true ;;
-*)
echo "Error: only -A, -u, -v, --chmod and file paths are allowed (got: $arg)" >&2
exit 1
;;
esac
done
exec git "${git_args[@]}" add "$@"
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
set -euo pipefail
# Wrapper around `git commit` that only allows a literal message. Without it, an
# allow rule for `git commit` also permits flags that make git read a file into
# the commit, such as -F .git/config, which a later push would then publish.
#
# Usage:
# git-commit.sh -m "<message>" [-m "<message>"] [-a] [--allow-empty] [-- <paths>]
source "$(dirname "${BASH_SOURCE[0]}")/git-env.sh"
has_message=false
expect_message=false
paths_only=false
for arg in "$@"; do
if [[ "$expect_message" == true ]]; then
expect_message=false
has_message=true
continue
fi
if [[ "$paths_only" == true ]]; then
continue
fi
case "$arg" in
-m | --message | -am)
expect_message=true
;;
--message=*)
has_message=true
;;
-a | --all | --allow-empty | -q | --quiet | -s | --signoff)
;;
--)
paths_only=true
;;
-*)
echo "Error: only -m with a literal message and basic commit flags are allowed (got: $arg)" >&2
exit 1
;;
esac
done
if [[ "$expect_message" == true ]]; then
echo "Error: -m needs a message" >&2
exit 1
fi
if [[ "$has_message" != true ]]; then
echo "Error: a message is required, with -m" >&2
exit 1
fi
exec git "${git_args[@]}" commit "$@"
+25
View File
@@ -0,0 +1,25 @@
# Sourced by the git wrappers. Clears settings in the environment that change what
# git runs, and sets the arguments every wrapper passes to git. Files beside this
# script, written by the action, record the session's repository and hook setting.
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
while IFS= read -r name; do
case "$name" in
GIT_AUTHOR_* | GIT_COMMITTER_*) ;;
GIT_*) unset "$name" ;;
esac
done < <(compgen -e)
unset XDG_CONFIG_HOME EDITOR VISUAL PAGER SSH_ASKPASS
git_args=(-c core.fsmonitor=false -c safe.bareRepository=explicit)
if [[ -e "$script_dir/.no-hooks" ]]; then
git_args+=(-c core.hooksPath=/dev/null)
fi
if [[ -e "$script_dir/.git-repo" ]]; then
{ IFS= read -r git_dir; IFS= read -r work_tree; IFS= read -r home || true; } <"$script_dir/.git-repo"
git_args+=("--git-dir=$git_dir" "--work-tree=$work_tree")
if [[ -n "$home" ]]; then
export HOME="$home"
fi
fi
+22 -5
View File
@@ -1,7 +1,10 @@
#!/usr/bin/env bash
set -euo pipefail
# Wrapper around `git push` that only allows `origin <ref>` with no flags.
# Wrapper around `git push` that only allows `origin <ref>` with no flags, and only
# updates the branch this session was set up on. That stops a prompt-injected session
# from updating main or anyone else's branch. Tag mode records the branch in a file
# beside this script. Elsewhere, set CLAUDE_PUSH_BRANCH.
# Defends against --receive-pack / --exec RCE and arbitrary-remote exfiltration
# (H1 #3556799). `git push:*` in allowedTools permits `git push --receive-pack='sh -c ...' ext::sh`
# which runs arbitrary shell on the Actions runner. This wrapper closes that.
@@ -27,10 +30,24 @@ if [[ "$1" != "origin" ]]; then
exit 1
fi
REF="$2"
if [[ "$REF" != "HEAD" ]] && ! git check-ref-format --branch "$REF" >/dev/null 2>&1; then
echo "Error: invalid ref: $REF" >&2
BRANCH="${CLAUDE_PUSH_BRANCH:-}"
source "$(dirname "${BASH_SOURCE[0]}")/git-env.sh"
if [[ -e "$script_dir/.push-branch" ]]; then
BRANCH="$(<"$script_dir/.push-branch")"
fi
if [[ -z "$BRANCH" ]]; then
echo "Error: CLAUDE_PUSH_BRANCH is not set, so there is no branch to push to" >&2
exit 1
fi
exec git push origin "$REF"
case "$2" in
HEAD) SOURCE="HEAD" ;;
"$BRANCH") SOURCE="refs/heads/$BRANCH" ;;
*)
echo "Error: this session can only push to $BRANCH (got: $2)" >&2
exit 1
;;
esac
# The full refspec fixes the target, whatever HEAD points at, and can't be forced.
exec git "${git_args[@]}" push origin "$SOURCE:refs/heads/$BRANCH"
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
set -euo pipefail
# Wrapper around `git rm` that only takes basic flags and file paths.
#
# Usage:
# git-rm.sh [-r] [-f] [--cached] [-q] [--] <paths>
source "$(dirname "${BASH_SOURCE[0]}")/git-env.sh"
paths_only=false
for arg in "$@"; do
if [[ "$paths_only" == true ]]; then
continue
fi
case "$arg" in
-r | -f | -rf | -fr | --force | --cached | -q | --quiet) ;;
--) paths_only=true ;;
-*)
echo "Error: only -r, -f, --cached, -q and file paths are allowed (got: $arg)" >&2
exit 1
;;
esac
done
exec git "${git_args[@]}" rm "$@"
+62 -23
View File
@@ -3,6 +3,7 @@
import * as core from "@actions/core";
import { writeFile, mkdir, rm } from "fs/promises";
import type { FetchDataResult } from "../github/data/fetcher";
import { isSameLogin } from "../github/validation/actor";
import {
formatContext,
formatBody,
@@ -17,20 +18,23 @@ import {
isPullRequestReviewEvent,
isPullRequestReviewCommentEvent,
} from "../github/context";
import type { ParsedGitHubContext } from "../github/context";
import type { GitHubContext, ParsedGitHubContext } from "../github/context";
import type { CommonFields, PreparedContext, EventData } from "./types";
import { GITHUB_SERVER_URL } from "../github/api/config";
import { extractUserRequest } from "../utils/extract-user-request";
export type { CommonFields, PreparedContext } from "./types";
const GIT_ADD_WRAPPER = `${process.env.GITHUB_ACTION_PATH}/scripts/git-add.sh`;
const GIT_RM_WRAPPER = `${process.env.GITHUB_ACTION_PATH}/scripts/git-rm.sh`;
const GIT_PUSH_WRAPPER = `${process.env.GITHUB_ACTION_PATH}/scripts/git-push.sh`;
const GIT_COMMIT_WRAPPER = `${process.env.GITHUB_ACTION_PATH}/scripts/git-commit.sh`;
/** Filename for the user request file, read by the SDK runner */
const USER_REQUEST_FILENAME = "claude-user-request.txt";
// Tag mode defaults - these tools are needed for tag mode to function.
// Edit/MultiEdit/Write are intentionally omitted: acceptEdits permission mode
// auto-allows file edits inside $GITHUB_WORKSPACE and denies writes outside it.
// Edit/MultiEdit/Write are intentionally omitted: the permission mode allows file
// edits inside $GITHUB_WORKSPACE and doesn't allow every write outside it.
const BASE_ALLOWED_TOOLS = ["Glob", "Grep", "LS", "Read"];
export function buildAllowedToolsString(
@@ -53,10 +57,10 @@ export function buildAllowedToolsString(
} else {
// When not using commit signing, add specific Bash git commands
baseTools.push(
"Bash(git add:*)",
"Bash(git commit:*)",
`Bash(${GIT_ADD_WRAPPER}:*)`,
`Bash(${GIT_COMMIT_WRAPPER}:*)`,
`Bash(${GIT_PUSH_WRAPPER}:*)`,
"Bash(git rm:*)",
`Bash(${GIT_RM_WRAPPER}:*)`,
);
}
@@ -282,7 +286,7 @@ export function prepareContext(
...(assigneeTrigger && { assigneeTrigger }),
};
} else if (eventAction === "labeled") {
if (!labelTrigger) {
if (!labelTrigger && !prompt) {
throw new Error("LABEL_TRIGGER is required for issue labeled event");
}
eventData = {
@@ -292,7 +296,7 @@ export function prepareContext(
issueNumber,
baseBranch,
claudeBranch,
labelTrigger,
...(labelTrigger && { labelTrigger }),
};
} else if (eventAction === "opened") {
eventData = {
@@ -370,7 +374,9 @@ export function getEventTypeAndContext(envVars: PreparedContext): {
} else if (eventData.eventAction === "labeled") {
return {
eventType: "ISSUE_LABELED",
triggerContext: `issue labeled with '${eventData.labelTrigger}'`,
triggerContext: eventData.labelTrigger
? `issue labeled with '${eventData.labelTrigger}'`
: "issue labeled",
};
}
return {
@@ -432,12 +438,12 @@ function getCommitInstructions(
if (eventData.isPR && !eventData.claudeBranch) {
return `
- Use git commands via the Bash tool to commit and push your changes:
- Stage files: Bash(git add <files>)
- Commit with a descriptive message: Bash(git commit -m "<message>")
- Stage files: Bash(${GIT_ADD_WRAPPER} <files>)
- Commit with a descriptive message: Bash(${GIT_COMMIT_WRAPPER} -m "<message>")
${
coAuthorLine
? `- When committing and the trigger user is not "Unknown", include a Co-authored-by trailer:
Bash(git commit -m "<message>\\n\\n${coAuthorLine}")`
Bash(${GIT_COMMIT_WRAPPER} -m "<message>\\n\\n${coAuthorLine}")`
: ""
}
- Push to the remote: Bash(${GIT_PUSH_WRAPPER} origin HEAD)`;
@@ -446,12 +452,12 @@ function getCommitInstructions(
return `
- You are already on the correct branch (${eventData.claudeBranch || "the PR branch"}). Do not create a new branch.
- Use git commands via the Bash tool to commit and push your changes:
- Stage files: Bash(git add <files>)
- Commit with a descriptive message: Bash(git commit -m "<message>")
- Stage files: Bash(${GIT_ADD_WRAPPER} <files>)
- Commit with a descriptive message: Bash(${GIT_COMMIT_WRAPPER} -m "<message>")
${
coAuthorLine
? `- When committing and the trigger user is not "Unknown", include a Co-authored-by trailer:
Bash(git commit -m "<message>\\n\\n${coAuthorLine}")`
Bash(${GIT_COMMIT_WRAPPER} -m "<message>\\n\\n${coAuthorLine}")`
: ""
}
- Push to the remote: Bash(${GIT_PUSH_WRAPPER} origin ${branchName})`;
@@ -826,10 +832,10 @@ ${
- mcp__github_file_ops__commit_files: {"files": ["path/to/file1.js", "path/to/file2.py"], "message": "feat: add new feature"}
- mcp__github_file_ops__delete_files: {"paths": ["path/to/old.js"], "message": "chore: remove deprecated file"}`
: `- Use git commands via the Bash tool for version control (remember that you have access to these git commands):
- Stage files: Bash(git add <files>)
- Commit changes: Bash(git commit -m "<message>")
- Push to remote: Bash(${GIT_PUSH_WRAPPER} origin <branch>)
- Delete files: Bash(git rm <files>) followed by commit and push
- Stage files: Bash(${GIT_ADD_WRAPPER} <files>)
- Commit changes: Bash(${GIT_COMMIT_WRAPPER} -m "<message>")
- Push to remote: Bash(${GIT_PUSH_WRAPPER} origin HEAD)
- Delete files: Bash(${GIT_RM_WRAPPER} <files>) followed by commit and push
- Check status: Bash(git status)
- View diff: Bash(git diff)${eventData.isPR && eventData.baseBranch ? `\n - IMPORTANT: For PR diffs, use: Bash(git diff origin/${eventData.baseBranch}...HEAD)` : ""}`
}
@@ -877,6 +883,22 @@ f. If you are unable to complete certain steps, such as running a linter or test
return promptContent;
}
function getCommentOrReviewAuthor(
context: GitHubContext | undefined,
): string | undefined {
if (!context) return undefined;
if (
isIssueCommentEvent(context) ||
isPullRequestReviewCommentEvent(context)
) {
return context.payload.comment.user?.login;
}
if (isPullRequestReviewEvent(context)) {
return context.payload.review.user?.login;
}
return undefined;
}
/**
* Extracts the user's request from the prepared context and GitHub data.
*
@@ -893,12 +915,17 @@ f. If you are unable to complete certain steps, such as running a linter or test
* // Issue body with "@claude fix this" -> returns "fix this"
* // Issue assigned without @claude in body -> returns null
*/
function extractUserRequestFromContext(
export function extractUserRequestFromContext(
context: PreparedContext,
githubData: FetchDataResult,
): string | null {
const { eventData, triggerPhrase } = context;
// The request gets the highest trust in the prompt and can run slash commands,
// so it only comes from the person who passed the permission check. When
// someone else triggers the run, for example by labeling another person's
// issue or editing their comment, that text stays ordinary context.
// For comment events, extract from comment body
if (
"commentBody" in eventData &&
@@ -907,11 +934,23 @@ function extractUserRequestFromContext(
eventData.eventName === "pull_request_review_comment" ||
eventData.eventName === "pull_request_review")
) {
return extractUserRequest(eventData.commentBody, triggerPhrase);
return isSameLogin(
getCommentOrReviewAuthor(context.githubContext),
context.githubContext?.actor,
)
? extractUserRequest(eventData.commentBody, triggerPhrase)
: null;
}
// For issue/PR events triggered by body content, extract from the body
if (githubData.contextData?.body) {
// For issue/PR events triggered by body content, extract from the body.
// GraphQL gives a bot's login without the "[bot]" suffix that actors have.
const author = githubData.contextData?.author;
const authorLogin =
author?.__typename === "Bot" ? `${author.login}[bot]` : author?.login;
if (
githubData.contextData?.body &&
isSameLogin(authorLogin, context.githubContext?.actor)
) {
const request = extractUserRequest(
githubData.contextData.body,
triggerPhrase,
+1 -1
View File
@@ -76,7 +76,7 @@ type IssueLabeledEvent = {
issueNumber: string;
baseBranch: string;
claudeBranch: string;
labelTrigger: string;
labelTrigger?: string;
};
type PullRequestBaseEvent = {
+1
View File
@@ -6,6 +6,7 @@ export function collectActionInputsPresence(): string {
base_branch: "",
branch_prefix: "claude/",
allowed_bots: "",
restrict_untrusted_prs: "true",
mode: "tag",
model: "",
anthropic_model: "",
+90 -9
View File
@@ -12,7 +12,11 @@ import { spawn } from "child_process";
import { appendFile } from "fs/promises";
import { existsSync, readFileSync } from "fs";
import { setupGitHubToken, WorkflowValidationSkipError } from "../github/token";
import { checkWritePermissions } from "../github/validation/permissions";
import {
checkBotActorPullRequestAuthor,
checkWritePermissions,
} from "../github/validation/permissions";
import { getUntrustedPrDisallowedTools } from "../github/validation/untrusted-pr";
import { createOctokit } from "../github/api/client";
import type { Octokits } from "../github/api/client";
import {
@@ -28,7 +32,17 @@ import { detectMode } from "../modes/detector";
import { prepareTagMode } from "../modes/tag";
import { prepareAgentMode } from "../modes/agent";
import { checkContainsTrigger } from "../github/validation/trigger";
import {
clearSessionState,
disableGitPrograms,
prepareGitForSession,
snapshotSessionFiles,
} from "../github/operations/session-guard";
import { restoreConfigFromBase } from "../github/operations/restore-config";
import {
restoreToolConfigFromBase,
toolConfigDenyRules,
} from "../github/operations/tool-config";
import { validateBranchName } from "../github/operations/branch";
import { collectActionInputsPresence } from "./collect-inputs";
import { updateCommentLink } from "./update-comment-link";
@@ -77,7 +91,7 @@ async function installClaudeCode(): Promise<string> {
return customExecutable;
}
const claudeCodeVersion = "2.1.291";
const claudeCodeVersion = "2.1.325";
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
for (let attempt = 1; attempt <= 3; attempt++) {
@@ -222,7 +236,29 @@ async function run() {
return;
}
const botActorAllowed = await checkBotActorPullRequestAuthor(
octokit.rest,
context,
context.inputs.allowedNonWriteUsers,
!!process.env.OVERRIDE_GITHUB_TOKEN,
);
if (!botActorAllowed) {
throw new Error(
"A bot acted on this pull request, but its author does not have write access",
);
}
// Run prepare
// Commands that run checkout code are denied on PRs from authors without write
// access. Hooks go off here, before the action checks out such a PR's head, and
// keep running for trusted authors, whose repositories may rely on them.
const untrustedPrDisallowedTools = isEntityContext(context)
? await getUntrustedPrDisallowedTools(octokit.rest, context)
: [];
const hooksOff = untrustedPrDisallowedTools.length > 0;
disableGitPrograms({ hooks: hooksOff });
clearSessionState();
console.log(
`Preparing with mode: ${modeName} for event: ${context.eventName}`,
);
@@ -251,6 +287,13 @@ async function run() {
validateEnvironmentVariables();
// Tag mode sets claudeBranch only when it branched from the base instead of
// checking out the PR's head, as for a closed or merged PR.
const checkedOutPrHead = modeName !== "tag" || !claudeBranch;
const isUntrustedCheckout =
checkedOutPrHead && untrustedPrDisallowedTools.length > 0;
let restoredToolConfig: string[] = [];
// On PRs, .claude/ and .mcp.json in the checkout are attacker-controlled.
// Restore them from the base branch before the CLI reads them.
//
@@ -272,6 +315,11 @@ async function run() {
}
if (restoreBase) {
restoredConfigPaths = restoreConfigFromBase(restoreBase);
// Before plugins are installed, which can already start package managers here.
if (isUntrustedCheckout) {
restoredToolConfig = restoreToolConfigFromBase(restoreBase);
restoredConfigPaths.push(...restoredToolConfig);
}
}
}
@@ -291,13 +339,45 @@ async function run() {
promptFile,
});
const claudeResult: ClaudeRunResult = await runClaude(promptConfig.path, {
claudeArgs: prepareResult.claudeArgs,
appendSystemPrompt: process.env.APPEND_SYSTEM_PROMPT,
model: process.env.ANTHROPIC_MODEL,
pathToClaudeCodeExecutable: claudeExecutable,
showFullOutput: process.env.INPUT_SHOW_FULL_OUTPUT,
});
// Passed separately because text added to claudeArgs can be lost: a comment at
// the end of the user's claude_args would swallow it.
const disallowedTools = isUntrustedCheckout
? [
...untrustedPrDisallowedTools,
...toolConfigDenyRules(restoredToolConfig),
]
: [];
// A hook runs in the session's current directory, and only the repository root's tool
// config comes from the base branch. This keeps Bash from moving the session.
if (isUntrustedCheckout) {
process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR = "1";
}
const restoreSessionFiles = snapshotSessionFiles(() =>
prepareGitForSession({ hooks: hooksOff }),
);
let claudeResult: ClaudeRunResult;
try {
claudeResult = await runClaude(promptConfig.path, {
claudeArgs: prepareResult.claudeArgs,
disallowedTools: disallowedTools.join(","),
appendSystemPrompt: process.env.APPEND_SYSTEM_PROMPT,
model: process.env.ANTHROPIC_MODEL,
pathToClaudeCodeExecutable: claudeExecutable,
showFullOutput: process.env.INPUT_SHOW_FULL_OUTPUT,
// Tag mode has no allow rules for file edits, so it needs a mode that allows them.
...(modeName === "tag" && { fallbackPermissionMode: "acceptEdits" }),
});
} finally {
restoreSessionFiles();
// The action's own git commands from here on hold the job's credentials,
// and the session could have edited a tracked hook.
disableGitPrograms({ hooks: true });
// Revoking the app token depends on this output, and a session can write it.
core.setOutput("skipped_due_to_workflow_validation_mismatch", "false");
}
claudeSuccess = claudeResult.conclusion === "success";
executionFile = claudeResult.executionFile;
@@ -324,6 +404,7 @@ async function run() {
core.setFailed(`Action failed with error: ${redactSecrets(errorMessage)}`);
} finally {
// Phase 4: Cleanup (always runs)
clearSessionState();
// Stop refreshing the workload identity token file and delete the token
// material so it doesn't outlive this step
+16 -2
View File
@@ -1,6 +1,7 @@
import { execFileSync } from "child_process";
import type { IssuesEvent } from "@octokit/webhooks-types";
import type { Octokits } from "../api/client";
import { isSameLogin } from "../validation/actor";
import { ISSUE_QUERY, PR_QUERY, USER_QUERY } from "../api/queries/github";
import {
isIssueCommentEvent,
@@ -116,18 +117,31 @@ async function findIssueEventTime(
event: string;
label?: { name?: string | null };
assignee?: { login?: string } | null;
actor?: { login?: string } | null;
assigner?: { login?: string } | null;
}) => boolean;
// Only the event from the person who passed the permission check counts. Someone
// else removing and re-adding the label must not move the cutoff for comments.
// Assignments name the person who made them separately, as the assigner.
const byActor = (event: {
actor?: { login?: string } | null;
assigner?: { login?: string } | null;
}) => isSameLogin((event.assigner ?? event.actor)?.login, context.actor);
if (payload.action === "labeled") {
const labelName = payload.label?.name;
if (!labelName) return undefined;
matches = (event) =>
event.event === "labeled" && event.label?.name === labelName;
event.event === "labeled" &&
event.label?.name === labelName &&
byActor(event);
} else if (payload.action === "assigned") {
const assigneeLogin = payload.assignee?.login;
if (!assigneeLogin) return undefined;
matches = (event) =>
event.event === "assigned" && event.assignee?.login === assigneeLogin;
event.event === "assigned" &&
event.assignee?.login === assigneeLogin &&
byActor(event);
} else {
return undefined;
}
+13
View File
@@ -3,6 +3,16 @@ import { GITHUB_SERVER_URL } from "../api/config";
import { encodeBranchNameForUrl } from "./comments/common";
import { $ } from "bun";
async function pushLfsObjects(branch: string): Promise<void> {
let tracked: string;
try {
tracked = await $`git lfs ls-files --name-only`.quiet().text();
} catch {
return; // Git LFS isn't installed here
}
if (tracked.trim()) await $`git lfs push origin ${branch}`;
}
export async function checkAndCommitOrDeleteBranch(
octokit: Octokits,
owner: string,
@@ -99,6 +109,9 @@ export async function checkAndCommitOrDeleteBranch(
const commitMessage = `Auto-commit: Save uncommitted changes from Claude\n\nRun ID: ${runId}`;
await $`git commit -m ${commitMessage}`;
// Hooks are off by now, and Git LFS uploads from a hook.
await pushLfsObjects(claudeBranch);
// Push the changes
await $`git push origin ${claudeBranch}`;
+75 -17
View File
@@ -9,6 +9,8 @@
import { $ } from "bun";
import { execFileSync } from "child_process";
import type { ParsedGitHubContext } from "../context";
import { isPullRequestEvent } from "../context";
import { retryWithBackoff } from "../../utils/retry";
import type { GitHubPullRequest } from "../types";
import type { Octokits } from "../api/client";
import type { FetchDataResult } from "../data/fetcher";
@@ -156,6 +158,7 @@ export async function setupBranch(
octokits: Octokits,
githubData: FetchDataResult,
context: ParsedGitHubContext,
triggerTime?: string,
): Promise<BranchInfo> {
const { owner, repo } = context.repository;
const entityNumber = context.entityNumber;
@@ -177,6 +180,7 @@ export async function setupBranch(
console.log("This is an open PR, checking out PR branch...");
const branchName = prData.headRefName;
const headSha = prData.headRefOid;
// Determine optimal fetch depth based on PR commit count, with a minimum
// of 20. Only applied to a checkout that is already shallow — see
@@ -195,25 +199,56 @@ export async function setupBranch(
// Validate branch names before use to prevent command injection
validateBranchName(branchName);
if (!/^[0-9a-f]{40}$/.test(headSha)) {
throw new Error(
`Unexpected head SHA for PR #${entityNumber}: ${headSha}`,
);
}
// For cross-repository (fork) PRs, fetch via the pull ref since the
// branch only exists on the fork's remote, not on origin.
if (prData.isCrossRepository) {
console.log(
`PR #${entityNumber} is from a fork, fetching via refs/pull/${entityNumber}/head...`,
if (isPullRequestEvent(context)) {
const eventSha = context.payload.pull_request.head.sha;
if (eventSha !== headSha) {
throw new Error(
`PR #${entityNumber} was updated after the trigger (${eventSha} -> ${headSha}). Push again or mention Claude to run on the latest version.`,
);
}
} else if (triggerTime) {
if (!prData.headRepository) {
throw new Error(
`PR #${entityNumber}: head repository is not available, cannot pin the PR version`,
);
}
const pushedAt = await headPushedAt(
octokits,
{
owner: prData.headRepository.owner.login,
repo: prData.headRepository.name,
},
branchName,
headSha,
);
if (new Date(pushedAt).getTime() >= new Date(triggerTime).getTime()) {
throw new Error(
`PR #${entityNumber} was updated after the trigger (${pushedAt} >= ${triggerTime}). Mention Claude again to run on the latest version.`,
);
}
}
const localBranch = prData.isCrossRepository
? `pr-${entityNumber}`
: branchName;
console.log(`PR #${entityNumber}: pinning ${localBranch} to ${headSha}`);
execGit(["fetch", "origin", ...depthArgs, headSha]);
execGit(["checkout", "-B", localBranch, headSha, "--"]);
const checkedOut = execFileSync("git", ["rev-parse", "HEAD"], {
encoding: "utf8",
}).trim();
if (checkedOut !== headSha) {
throw new Error(
`PR #${entityNumber}: checked out ${checkedOut}, expected ${headSha}`,
);
execGit([
"fetch",
"origin",
...depthArgs,
`pull/${entityNumber}/head:${branchName}`,
]);
} else {
// Execute git commands to checkout PR branch (dynamic depth based on PR size)
// Using execFileSync instead of shell template literals for security
execGit(["fetch", "origin", ...depthArgs, branchName]);
}
execGit(["checkout", branchName, "--"]);
console.log(`Successfully checked out PR branch for PR #${entityNumber}`);
@@ -223,7 +258,7 @@ export async function setupBranch(
return {
baseBranch,
currentBranch: branchName,
currentBranch: localBranch,
};
}
}
@@ -350,3 +385,26 @@ export async function setupBranch(
process.exit(1);
}
}
async function headPushedAt(
octokits: Octokits,
headRepo: { owner: string; repo: string },
branchName: string,
headSha: string,
): Promise<string> {
const { data } = await retryWithBackoff(() =>
octokits.rest.request("GET /repos/{owner}/{repo}/activity", {
owner: headRepo.owner,
repo: headRepo.repo,
ref: `refs/heads/${branchName}`,
per_page: 1,
}),
);
const latest = (data as Array<{ after: string; timestamp: string }>)[0];
if (!latest || latest.after !== headSha) {
throw new Error(
`Could not determine when ${headSha} was pushed to ${headRepo.owner}/${headRepo.repo}:${branchName}`,
);
}
return latest.timestamp;
}
+25 -8
View File
@@ -53,8 +53,8 @@ export async function configureGitAuth(
* actions/checkout stores its token as an `http.<server>/.extraheader` entry
* in .git/config for the duration of the job. Claude and the tools it invokes
* run inside this working tree, so remove that entry and back git with the
* action's own token instead (a credential helper when non-write users are
* allowed, otherwise the origin URL). This applies to every mode, including API
* action's own token instead (a credential helper when non-write users or bots
* are allowed, otherwise the origin URL). This applies to every mode, including API
* commit signing where no other git configuration is needed.
*
* actions/checkout < v6 stored the header directly in the repo-local config,
@@ -105,9 +105,11 @@ export async function replaceCheckoutCredentials(
: "No existing authentication headers to remove",
);
if (process.env.ALLOWED_NON_WRITE_USERS) {
if (process.env.ALLOWED_NON_WRITE_USERS || context.inputs.allowedBots) {
// When processing content from non-write users, use a credential helper
// instead of embedding the token in the remote URL. The helper script reads
// instead of embedding the token in the remote URL. Allowed bots count too:
// their access isn't checked, and they relay text that other people wrote.
// The helper script reads
// from GH_TOKEN at auth time, so .git/config stays token-free. Written as a
// file to avoid shell-escaping the helper body; placed under
// GITHUB_ACTION_PATH so it sits alongside the action source.
@@ -117,15 +119,30 @@ export async function replaceCheckoutCredentials(
process.env.GITHUB_ACTION_PATH || homedir(),
".git-credential-gh-token",
);
// With no token it answers nothing, so that git goes on to a later step's own
// credentials. An empty password would count as an answer.
await writeFile(
helperPath,
'#!/bin/sh\necho username=x-access-token\necho password="$GH_TOKEN"\n',
'#!/bin/sh\n[ -n "$GH_TOKEN" ] || exit 0\necho username=x-access-token\necho password="$GH_TOKEN"\n',
{ mode: 0o700 },
);
const cleanUrl = `https://${serverUrl.host}/${context.repository.owner}/${context.repository.repo}.git`;
await $`git remote set-url origin ${cleanUrl}`;
await $`git config credential.helper ${helperPath}`;
// The username holds no secret. It keeps the URL out of rewrite rules on the
// server's prefix, as the token URL below is, and they would bypass the helper.
const helperUrl = `https://x-access-token@${serverUrl.host}/${context.repository.owner}/${context.repository.repo}.git`;
await $`git remote set-url origin ${helperUrl}`;
// git runs the helper through sh, which would strip Windows backslashes and split
// a path with a space.
const shellSafePath = helperPath
.replaceAll("\\", "/")
.replaceAll("'", "'\\''");
// Only for this server: git asks a helper about every host it contacts, and the
// helper answers without looking at which one.
const helperKey = `credential.https://${serverUrl.host}.helper`;
await $`git config ${helperKey} ${`!'${shellSafePath}'`}`;
console.log("✓ Configured credential helper");
console.log(
"Later steps that use the origin remote need their own credentials: GH_TOKEN, GIT_ASKPASS, a credential saved for the username x-access-token, or their own remote URL",
);
} else {
// Update the remote URL to include the token for authentication
console.log("Updating remote URL with authentication...");
+4 -2
View File
@@ -31,6 +31,7 @@ export const SENSITIVE_PATHS = [
".ripgreprc",
"CLAUDE.md",
"CLAUDE.local.md",
"AGENTS.md",
".husky",
];
@@ -206,7 +207,7 @@ function snapshotSensitivePath(
}
}
function ensureClaudePrExcludedFromGit(): void {
export function ensureClaudePrExcludedFromGit(): void {
const excludePath = execFileSync(
"git",
["rev-parse", "--git-path", "info/exclude"],
@@ -258,7 +259,8 @@ function ensureClaudePrExcludedFromGit(): void {
* extends to the runtime itself: `bunx <tool>` runs the tool under `node` when
* `node` is on PATH, but on a Bun-only runner Bun executes the script and reads
* `bunfig.toml` (e.g. `preload`) from the checkout, so `bunfig.toml` and
* `.npmrc` there are PR-controlled runtime config too.
* `.npmrc` there are PR-controlled runtime config too. On PRs from authors without
* write access, restoreToolConfigFromBase replaces those.
*
* @param baseBranch - PR base branch name. Must be pre-validated (branch.ts
* calls validateBranchName on it before returning).
+349
View File
@@ -0,0 +1,349 @@
import * as core from "@actions/core";
import { execFileSync } from "child_process";
import {
closeSync,
constants,
fstatSync,
lstatSync,
mkdirSync,
openSync,
readFileSync,
readlinkSync,
realpathSync,
rmSync,
writeFileSync,
} from "fs";
import { homedir } from "os";
import { dirname, isAbsolute, join, resolve } from "path";
type TrackedFile = { label: string; path: string };
// "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.
type FileSnapshot = TrackedFile & {
state: "absent" | "file" | "opaque";
wasSymlink: boolean;
content?: Buffer;
mode?: number;
// For a symlink: what it points to, and the regular file that ends up at.
link?: { target: string; resolved: string };
};
const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
const SESSION_STATE_FILES = [".push-branch", ".no-hooks", ".git-repo"];
// How many GIT_CONFIG_* entries were there before disableGitPrograms added any.
let entriesBeforeAction: number | undefined;
const codeOf = (error: unknown): string =>
(error as { code?: string }).code ?? "unknown error";
function gitProgramSettings({ hooks }: { hooks: boolean }): [string, string][] {
return hooks
? [
["core.fsmonitor", "false"],
["core.hooksPath", "/dev/null"],
]
: [["core.fsmonitor", "false"]];
}
function resolveGitPath(file: string): string | null {
try {
const path = execFileSync("git", ["rev-parse", "--git-path", file], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
env: { ...process.env },
}).trim();
return isAbsolute(path) ? path : join(process.cwd(), path);
} catch {
return null;
}
}
/**
* Every config file git reads here, which includes those pulled in through
* include.path. actions/checkout keeps its config in one of those.
*/
function gitConfigFilesInUse(): TrackedFile[] {
try {
const listing = execFileSync(
"git",
["config", "--list", "--includes", "--show-origin", "--name-only", "-z"],
{
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
env: { ...process.env },
},
);
return listing
.split("\0")
.filter((token, index) => index % 2 === 0 && token.startsWith("file:"))
.map((origin) => ({
label: "a git config file",
path: origin.slice("file:".length),
}));
} catch {
return [];
}
}
/**
* Files that later steps trust and that a session can change. The runner applies
* GITHUB_ENV and GITHUB_PATH to every later step, post steps included, and those
* steps run git, which reads these config files and can run programs they name.
*/
function filesLaterStepsTrust(): TrackedFile[] {
const home = process.env.HOME || homedir();
const candidates: [string, string | null | undefined][] = [
["GITHUB_ENV", process.env.GITHUB_ENV],
["GITHUB_PATH", process.env.GITHUB_PATH],
[".git/config", resolveGitPath("config")],
[".git/config.worktree", resolveGitPath("config.worktree")],
["~/.gitconfig", join(home, ".gitconfig")],
["GIT_CONFIG_GLOBAL", process.env.GIT_CONFIG_GLOBAL],
[
"git config in XDG_CONFIG_HOME",
join(process.env.XDG_CONFIG_HOME || join(home, ".config"), "git/config"),
],
];
const named = candidates.flatMap(([label, path]) =>
path ? [{ label, path }] : [],
);
const seen = new Set<string>();
return [...named, ...gitConfigFilesInUse()].filter(({ path }) => {
const absolute = resolve(path);
if (seen.has(absolute)) return false;
seen.add(absolute);
return true;
});
}
function readSnapshot(file: TrackedFile): FileSnapshot {
let wasSymlink: boolean;
try {
wasSymlink = lstatSync(file.path).isSymbolicLink();
} catch {
return { ...file, state: "absent", wasSymlink: false };
}
let fd: number | undefined;
try {
// Non-blocking, because opening a FIFO would otherwise wait for a writer.
fd = openSync(file.path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
const stats = fstatSync(fd);
if (!stats.isFile() || stats.size > MAX_SNAPSHOT_BYTES) {
return { ...file, state: "opaque", wasSymlink };
}
return {
...file,
state: "file",
wasSymlink,
content: readFileSync(fd),
mode: stats.mode & 0o777,
...(wasSymlink && {
link: {
target: readlinkSync(file.path),
resolved: realpathSync(file.path),
},
}),
};
} catch {
return { ...file, state: "opaque", wasSymlink };
} finally {
if (fd !== undefined) closeSync(fd);
}
}
function isUnchanged(before: FileSnapshot, now: FileSnapshot): boolean {
if (before.state !== now.state || before.wasSymlink !== now.wasSymlink) {
return false;
}
return before.state !== "file" || before.content!.equals(now.content!);
}
/**
* Where to restore a file. A symlink that was there before the session and still
* leads to the same file is left alone, and that file is restored, so a runner's
* own link keeps working. One a session added or re-pointed gets replaced.
*/
function restorePath(before: FileSnapshot): string {
if (!before.link) return before.path;
try {
return readlinkSync(before.path) === before.link.target &&
realpathSync(before.path) === before.link.resolved
? before.link.resolved
: before.path;
} catch {
return before.path;
}
}
/**
* 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
* action runs git again. Replacing a file rather than writing to it means a
* session cannot redirect the write by swapping in a symlink.
*
* This stops a session that can only write through its tools. It is not a
* sandbox: code running as the runner's user can stop the action before it
* restores anything.
*/
export function snapshotSessionFiles(beforeSession?: () => void): () => void {
const files = filesLaterStepsTrust();
const snapshots = files.map(readSnapshot);
// What the action changes for the session goes back too, without a warning.
beforeSession?.();
const atStart = files.map(readSnapshot);
return () => {
const restored: string[] = [];
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.state === "opaque") {
core.warning(
`Could not restore ${before.label} after the session: it was not a regular file before`,
);
continue;
}
const path = restorePath(before);
rmSync(path, { force: true, recursive: true });
if (before.state === "file") {
writeFileSync(path, before.content!, { mode: before.mode });
}
if (changedBySession) restored.push(before.label);
} catch (error) {
// The label is fixed text, and the error code carries no file content.
core.warning(
`Could not restore ${before.label} after the session (${codeOf(error)})`,
);
}
}
if (restored.length > 0) {
core.warning(
`The session changed files that later steps trust, so they were restored: ${restored.join(", ")}`,
);
}
};
}
/**
* Makes git ignore settings that run programs, for this process and everything
* it starts. GIT_CONFIG_* outranks every config file, and existing entries are
* kept. It is not written to GITHUB_ENV, so later steps are unaffected.
*/
export function disableGitPrograms({ hooks }: { hooks: boolean }): void {
let count = Number.parseInt(process.env.GIT_CONFIG_COUNT ?? "", 10) || 0;
entriesBeforeAction ??= count;
const current = new Map<string, string | undefined>();
for (let i = 0; i < count; i++) {
current.set(
process.env[`GIT_CONFIG_KEY_${i}`] ?? "",
process.env[`GIT_CONFIG_VALUE_${i}`],
);
}
for (const [key, value] of gitProgramSettings({ hooks })) {
if (current.get(key) === value) continue;
process.env[`GIT_CONFIG_KEY_${count}`] = key;
process.env[`GIT_CONFIG_VALUE_${count}`] = value;
count++;
}
process.env.GIT_CONFIG_COUNT = String(count);
}
const sessionFile = (name: string): string | undefined =>
process.env.GITHUB_ACTION_PATH
? join(process.env.GITHUB_ACTION_PATH, "scripts", name)
: undefined;
function writeSessionFile(name: string, content: string): void {
const path = sessionFile(name);
if (!path) return;
mkdirSync(dirname(path), { recursive: true });
rmSync(path, { force: true, recursive: true });
writeFileSync(path, content, { mode: 0o444 });
}
/** Records the only branch the push wrapper may update. */
export function pinPushBranch(branch: string): void {
try {
writeSessionFile(".push-branch", branch);
} catch (error) {
// With no file and no variable, the wrapper refuses to push.
core.warning(`Could not record the session's branch (${codeOf(error)})`);
}
}
/** Removes what the wrappers read, so another step in this job can't inherit it. */
export function clearSessionState(): void {
for (const name of SESSION_STATE_FILES) {
const path = sessionFile(name);
if (!path) continue;
try {
rmSync(path, { force: true, recursive: true });
} catch (error) {
core.warning(`Could not remove ${name} (${codeOf(error)})`);
}
}
}
const gitOutput = (...args: string[]): string | null => {
try {
return execFileSync("git", args, {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
env: { ...process.env },
}).trim();
} catch {
return 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.
*/
export function prepareGitForSession({ hooks }: { hooks: boolean }): void {
const count = Number.parseInt(process.env.GIT_CONFIG_COUNT ?? "", 10) || 0;
const before = entriesBeforeAction ?? count;
for (let i = before; i < count; i++) {
delete process.env[`GIT_CONFIG_KEY_${i}`];
delete process.env[`GIT_CONFIG_VALUE_${i}`];
}
if (before > 0) process.env.GIT_CONFIG_COUNT = String(before);
else delete process.env.GIT_CONFIG_COUNT;
entriesBeforeAction = undefined;
const setConfig = (scope: string, entries: [string, string][]): void => {
for (const [key, value] of entries) {
if (gitOutput("config", scope, "--replace-all", key, value) === null) {
core.warning(`Could not set ${key} for the session`);
}
}
};
// Before the global setting, which stops git from finding a bare repository here.
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"]]);
try {
if (hooks) writeSessionFile(".no-hooks", "");
if (gitDir && workTree) {
const home = process.env.HOME || homedir();
writeSessionFile(".git-repo", `${gitDir}\n${workTree}\n${home}\n`);
}
} catch (error) {
core.warning(
`Could not record git settings for the wrappers (${codeOf(error)})`,
);
}
}
+422
View File
@@ -0,0 +1,422 @@
import * as core from "@actions/core";
import { execFileSync } from "child_process";
import {
lstatSync,
mkdirSync,
readdirSync,
readFileSync,
rmdirSync,
rmSync,
symlinkSync,
writeFileSync,
} from "fs";
import { dirname } from "path";
import {
ensureClaudePrExcludedFromGit,
SENSITIVE_PATHS,
} from "./restore-config";
// What npm and Bun read from the repository root to decide which program to run and
// where to download it from. Config from the base branch can start them, for example
// in a hook or an MCP server. node_modules counts because its .bin comes first on PATH,
// and package.json because npx looks for commands there first.
const TOOL_CONFIG = [".npmrc", "bunfig.toml", "node_modules"];
const PACKAGE_JSON = "package.json";
// The fields that provide commands. A bin that is a string is named after the package,
// and npx looks in workspaces too.
const COMMAND_FIELDS = ["name", "bin", "directories", "workspaces"];
const NO_COMMANDS = "none";
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 };
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";
// No file name or content, which the pull request controls, reaches the log.
function warn(what: string, error: unknown): void {
const { code, status } = error as { code?: string; status?: number };
core.warning(`${what} (${code ?? `exit code ${status ?? "unknown"}`})`);
}
function git(args: string[], input: string | Buffer = ""): Buffer {
return execFileSync("git", args, {
stdio: ["pipe", "pipe", "ignore"],
input,
env: { ...process.env },
maxBuffer: MAX_OUTPUT_BYTES,
});
}
// A parent that is a file or a looping link means there is nothing there.
function onDisk(path: string) {
try {
return lstatSync(fsPath(path));
} catch {
return undefined;
}
}
// File systems can ignore case, and some the way a character is encoded.
const fold = (path: string): string =>
fsPath(path).toString().normalize("NFKC").toLowerCase();
/**
* Whether a path is in a directory that comes from the base branch already. The index
* has the pull request's version of it, so nothing there may be rebuilt from that.
*/
function isRestored(path: string, topLevel: Set<string>): boolean {
const [dir] = path.split("/") as [string];
return SENSITIVE_PATHS.some(
(restored) =>
dir === restored ||
// Another spelling is a directory of its own only if the file system lists it.
(fold(dir) === fold(restored) && !topLevel.has(dir)),
);
}
/** Which tool config a path belongs to. */
function rootName(path: string): string | undefined {
const folded = fold(path);
// A directory with one of these names is in the file's place, whatever it holds.
const name = TOOL_CONFIG.find(
(name) => folded === name || folded.startsWith(`${name}/`),
);
if (name) return name;
return folded === PACKAGE_JSON || folded.endsWith(`/${PACKAGE_JSON}`)
? PACKAGE_JSON
: undefined;
}
/** Whether no parent of a path is a link, which could lead out of the checkout. */
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 {
rmSync(fsPath(path), { recursive: true, force: true });
// An empty directory would stand in the way of a file of that name.
try {
for (let dir = dirname(path); dir !== "."; dir = dirname(dir)) {
rmdirSync(fsPath(dir));
}
} catch {
// It isn't empty.
}
}
// Each entry is "<mode> <other fields>\t<path>", relative to the working directory.
function parseEntries(listing: Buffer, oidField: number): Map<string, Entry> {
const entries = new Map<string, Entry>();
const topLevel = new Set(
readdirSync(".", { encoding: "buffer" }).map((name) =>
name.toString("latin1"),
),
);
for (const line of listing.toString("latin1").split("\0")) {
const [info, path] = line.split(/\t(.*)/s);
if (!info || !path || !rootName(path) || isRestored(path, topLevel)) {
continue;
}
const fields = info.split(" ");
entries.set(path, { mode: fields[0]!, oid: fields[oidField]! });
}
return entries;
}
const pullRequestEntries = (): Map<string, Entry> =>
parseEntries(git(["ls-files", "--stage", "-z"]), 1);
// A checkout with a narrow refspec has no remote-tracking branch, only FETCH_HEAD.
function baseEntries(baseBranch: string): Map<string, Entry> {
let ref = `refs/remotes/origin/${baseBranch}`;
try {
git(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
} catch {
ref = "FETCH_HEAD";
}
return parseEntries(git(["ls-tree", "-r", "-z", ref]), 2);
}
/** The stored content of each entry, which no .gitattributes has been applied to. */
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;
const output = git(["cat-file", "--batch"], `${oids.join("\n")}\n`);
// "<oid> <type> <size>\n<content>\n", or "<oid> missing\n"
for (let at = 0; at < output.length; ) {
const end = output.indexOf("\n", at);
const [oid, , size] = output.toString("latin1", at, end).split(" ");
at = end + 1;
if (size === undefined) continue;
blobs.set(oid!, output.subarray(at, at + Number(size)));
at += Number(size) + 1;
}
return blobs;
}
type Json = Record<string, unknown>;
/** Parses a package.json, or returns undefined if it can't be understood. */
function parsePackageJson(size: number, read: () => Buffer): Json | undefined {
if (size > MAX_PACKAGE_JSON_BYTES) return undefined;
// trimStart also drops a byte order mark.
const json = JSON.parse(read().toString().trimStart());
return json && typeof json === "object" ? json : undefined;
}
/** The package.json that git stores. */
function readPackageJson(entry: Entry): Json | undefined {
if (!isFile(entry)) return undefined;
try {
const size = Number(git(["cat-file", "-s", entry.oid]).toString());
return parsePackageJson(size, () => git(["cat-file", "blob", entry.oid]));
} catch {
return undefined;
}
}
/** The package.json on disk, which .gitattributes can make differ from what git stores. */
function readPackageJsonOnDisk(path: string): Json | undefined {
try {
const { size } = lstatSync(fsPath(path));
return parsePackageJson(size, () => readFileSync(fsPath(path)));
} catch {
return undefined;
}
}
/** The commands a package.json provides, or undefined if that can't be told. */
function commands(json: Json | undefined): string | undefined {
if (!json) return undefined;
// Other directories, such as the one for tests, provide no commands.
const directories = (json.directories as Json | null | undefined)?.bin;
if (!json.bin && !directories && !json.workspaces) return NO_COMMANDS;
const provided: Json = { ...json, directories };
return JSON.stringify(COMMAND_FIELDS.map((field) => provided[field] ?? null));
}
/**
* The attributes that make git write each file differently from what it stores. The
* pull request controls .gitattributes.
*/
function conversions(paths: string[]): Map<string, Set<string>> {
const found = new Map<string, Set<string>>();
if (paths.length === 0) return found;
// Checkout uses the index's .gitattributes, and the one on disk can be converted too.
// If the index has none, it uses the one on disk.
for (const source of [["--cached"], []]) {
const fields = git(
["check-attr", ...source, "-z", "--stdin", ENCODING, "ident", "filter"],
Buffer.from(paths.map((path) => `${path}\0`).join(""), "latin1"),
)
.toString("latin1")
.split("\0");
// "<path> <attribute> <value>", each ended by a NUL
for (let i = 0; i + 2 < fields.length; i += 3) {
const [path, attribute, value] = fields.slice(i) as [
string,
string,
string,
];
if (value === "unspecified" || value === "unset") continue;
// Git takes this as no conversion.
if (attribute === ENCODING && /^utf-?8$/i.test(value)) continue;
found.set(path, (found.get(path) ?? new Set()).add(attribute));
}
}
return found;
}
function differs(
path: string,
converted: Set<string> | undefined,
pr?: Entry,
base?: Entry,
): boolean {
const isSame = pr?.oid === base?.oid && pr?.mode === base?.mode;
// Even an unchanged file can then be one that npm or Bun can't read.
if (converted?.has(ENCODING)) return true;
if (rootName(path) !== PACKAGE_JSON) return !isSame;
if (!pr || isSame) return false;
const provided = [commands(readPackageJson(pr))];
// npm reads what is on disk, unless an earlier step removed it.
if (converted && hasRealParents(path) && onDisk(path)?.isFile()) {
provided.push(commands(readPackageJsonOnDisk(path)));
}
// Only one that provides commands matters, so most pull requests keep their own.
const allowed = [
NO_COMMANDS,
base ? commands(readPackageJson(base)) : NO_COMMANDS,
];
return provided.some((value) => !value || !allowed.includes(value));
}
/** The pull request's package.json with the base branch's commands. */
function withBaseCommands(
pr: Entry,
base: Entry | undefined,
): Buffer | undefined {
const json = readPackageJson(pr);
const baseJson = base ? readPackageJson(base) : {};
if (!json || !baseJson) return undefined;
for (const field of COMMAND_FIELDS) {
// Without a bin, a new package's name provides no command.
if (field === "name" && !base) continue;
if (baseJson[field] === undefined) delete json[field];
else json[field] = baseJson[field];
}
return Buffer.from(`${JSON.stringify(json, null, 2)}\n`);
}
/** Keeps the pull request's version readable, as for the other restored config. */
function snapshotForReview(path: string, entry: Entry): void {
if (!isFile(entry) || rootName(path) === "node_modules") return;
try {
const content = git(["cat-file", "blob", entry.oid]);
const copy = fsPath(`.claude-pr/${path}`);
mkdirSync(fsPath(`.claude-pr/${dirname(path)}`), { recursive: true });
writeFileSync(copy, content);
ensureClaudePrExcludedFromGit();
} catch (error) {
warn("Could not keep a copy of tool config for review", error);
}
}
/**
* Replaces the pull request's tool config with the base branch's wherever they differ.
* Like restoreConfigFromBase, which must run first because it fetches the base branch,
* it changes the working tree and not the index. Only tracked files are replaced, so
* what an earlier step created stays. In a package.json only the commands are replaced.
*
* @returns The names that were replaced, from a fixed list. Callers that stage files
* must exclude them.
* @throws If the base branch's version can't be put in place. The message holds no
* file name, because the pull request controls those.
*/
export function restoreToolConfigFromBase(baseBranch: string): string[] {
try {
return restoreToolConfig(baseBranch);
} catch (error) {
warn("Could not replace tool config", error);
throw new Error(
"Could not use the base branch's version of the files that npm and Bun read",
);
}
}
function restoreToolConfig(baseBranch: string): string[] {
const pr = pullRequestEntries();
const base = baseEntries(baseBranch);
const all = [...new Set([...pr.keys(), ...base.keys()])];
// npx reads the packages in subdirectories only through the root's workspaces, and
// a pull request's own are replaced below.
const rootJson = base.get(PACKAGE_JSON);
const hasWorkspaces =
rootJson !== undefined &&
readPackageJson(rootJson)?.workspaces !== undefined;
const matters = (path: string): boolean =>
hasWorkspaces || rootName(path) !== PACKAGE_JSON || !path.includes("/");
const converted = conversions(
[...pr].flatMap(([path, entry]) =>
isFile(entry) && matters(path) && rootName(path) !== "node_modules"
? [path]
: [],
),
);
// Names that differ only in case can be the same file.
const differing = new Set(
all
.filter(
(path) =>
matters(path) &&
differs(path, converted.get(path), pr.get(path), base.get(path)),
)
.map(fold),
);
const candidates = all.filter((path) => differing.has(fold(path)));
// A directory where the pull request has a file or link came from an earlier step.
const replaced = candidates.filter((path) => {
const entry = pr.get(path);
const stats = entry && onDisk(path);
return (
stats &&
(!stats.isDirectory() || isSubmodule(entry)) &&
hasRealParents(path)
);
});
// All of these go before anything is written.
for (const path of replaced) {
snapshotForReview(path, pr.get(path)!);
remove(path);
}
const removed = new Set(replaced);
const toWrite = candidates.flatMap((path): Replacement[] => {
const entry = base.get(path);
const prEntry = pr.get(path);
// One that the pull request has but is not on disk was left out or deleted by the
// workflow. One that only the base has matters unless it's a package.json.
const wanted = prEntry
? removed.has(path)
: rootName(path) !== PACKAGE_JSON;
if (!wanted || onDisk(path)) return [];
const content =
prEntry && rootName(path) === PACKAGE_JSON
? withBaseCommands(prEntry, entry)
: undefined;
if (content) return [{ path, entry: prEntry!, content }];
return entry && !isSubmodule(entry) ? [{ path, entry, content }] : [];
});
const blobs = readBlobs(
toWrite.flatMap(({ entry, content }) => (content ? [] : [entry])),
);
const written: string[] = [];
for (const { path, entry, content = blobs.get(entry.oid) } of toWrite) {
if (!hasRealParents(path)) continue;
if (!content) throw new Error("missing object");
mkdirSync(fsPath(dirname(path)), { recursive: true });
if (isLink(entry)) symlinkSync(content, fsPath(path));
else {
const mode = entry.mode === "100755" ? 0o755 : 0o644;
writeFileSync(fsPath(path), content, { mode, flag: "wx" });
}
written.push(path);
}
const names = [
...new Set([...replaced, ...written].map((path) => rootName(path)!)),
];
if (names.length > 0) {
core.warning(
`The pull request and its base branch differ in what npm and Bun read (${names.join(", ")}), so the base branch's version is used and Claude can't edit it. See docs/security.md.`,
);
}
return names;
}
/**
* Rules that stop a session from editing tool config, for a pull request whose author
* doesn't have write access. Other package.json edits are ordinary work. The rules
* cover subdirectories too, because a hook runs in the session's current directory.
*/
export const toolConfigDenyRules = (replaced: string[]): string[] => [
...TOOL_CONFIG.map((name) =>
name === "node_modules" ? "Edit(./node_modules/**)" : `Edit(./${name})`,
),
...(replaced.includes(PACKAGE_JSON) ? ["Edit(package.json)"] : []),
];
+8
View File
@@ -8,6 +8,14 @@
import type { Octokit } from "@octokit/rest";
import type { GitHubContext } from "../context";
/** Whether two GitHub logins name the same account. Logins are case-insensitive. */
export function isSameLogin(
a: string | null | undefined,
b: string | null | undefined,
): boolean {
return !!a && !!b && a.toLowerCase() === b.toLowerCase();
}
function isAllowedBot(actor: string, allowedBots: string): boolean {
const trimmed = allowedBots.trim();
if (trimmed === "*") return true;
+74 -5
View File
@@ -1,5 +1,9 @@
import * as core from "@actions/core";
import { isWorkflowRunEvent, type GitHubContext } from "../context";
import {
isPullRequestEvent,
isWorkflowRunEvent,
type GitHubContext,
} from "../context";
import type { Octokit } from "@octokit/rest";
/**
@@ -28,19 +32,40 @@ function isAllowedBot(actor: string, allowedBots: string): boolean {
* Collect the actors whose repository access should be checked. This is
* normally just the workflow actor (GITHUB_ACTOR). For workflow_run events
* the actor that started the upstream run is checked as well when it
* differs, since that is the account the run originates from.
* differs, since that is the account the run originates from. GitHub credits a
* run to whoever caused it, so a maintainer reopening a fork's pull request
* starts a run of the fork's code; the fork's owner is checked too.
*
* Returns null when the run's origin cannot be determined.
*/
function getActorsToCheck(context: GitHubContext): string[] {
function getActorsToCheck(context: GitHubContext): string[] | null {
const actors = [context.actor];
if (isWorkflowRunEvent(context)) {
const runActor = context.payload.workflow_run?.actor?.login;
const run = context.payload.workflow_run;
const runActor = run?.actor?.login;
if (runActor && !actors.includes(runActor)) {
core.info(
`workflow_run was started by ${runActor}; checking permissions for that actor as well`,
);
actors.push(runActor);
}
const headRepository = run?.head_repository;
if (!headRepository?.full_name) {
core.warning("workflow_run does not say which repository it ran from");
return null;
}
const isFork =
headRepository.full_name.toLowerCase() !==
context.repository.full_name.toLowerCase();
const forkOwner = headRepository.full_name.split("/")[0]!;
if (isFork && !actors.includes(forkOwner)) {
core.info(
`workflow_run ran code from a fork owned by ${forkOwner}; checking permissions for that account as well`,
);
actors.push(forkOwner);
}
}
return actors;
@@ -60,7 +85,10 @@ export async function checkWritePermissions(
allowedNonWriteUsers?: string,
githubTokenProvided?: boolean,
): Promise<boolean> {
for (const actor of getActorsToCheck(context)) {
const actors = getActorsToCheck(context);
if (!actors) return false;
for (const actor of actors) {
const allowed = await checkActorWritePermissions(
octokit,
context,
@@ -70,9 +98,50 @@ export async function checkWritePermissions(
);
if (!allowed) return false;
}
return true;
}
/**
* When a bot acts on a pull request, the bot is the actor even though someone
* else wrote the pull request. Bots are not checked for repository access, so an
* allowed bot acting on an outsider's fork would otherwise start a run for them.
* Call this once a run is going to start, so that bot activity with nothing to
* do still skips quietly.
*/
export async function checkBotActorPullRequestAuthor(
octokit: Octokit,
context: GitHubContext,
allowedNonWriteUsers?: string,
githubTokenProvided?: boolean,
): Promise<boolean> {
if (!isPullRequestEvent(context) || !context.actor.endsWith("[bot]")) {
return true;
}
const author = context.payload.pull_request.user?.login;
// A bot's own pull request is left to the check that bots are allowed.
if (author === context.actor) return true;
let allowed = false;
if (author?.endsWith("[bot]")) {
allowed = isAllowedBot(author, context.inputs.allowedBots ?? "");
} else if (author) {
allowed = await checkActorWritePermissions(
octokit,
context,
author,
allowedNonWriteUsers,
githubTokenProvided,
);
}
if (!allowed) {
core.warning(
`${context.actor} acted on a pull request by ${author ?? "an unknown author"}, who is not allowed to start a run`,
);
}
return allowed;
}
async function checkActorWritePermissions(
octokit: Octokit,
context: GitHubContext,
+64 -16
View File
@@ -10,38 +10,68 @@ import {
isPullRequestReviewCommentEvent,
} from "../context";
import type { ParsedGitHubContext } from "../context";
import { isSameLogin } from "./actor";
export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
const {
inputs: { assigneeTrigger, labelTrigger, triggerPhrase, prompt },
} = context;
// If prompt is provided, always trigger
// 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.
if (
(isIssueCommentEvent(context) ||
isPullRequestReviewCommentEvent(context)) &&
(context.eventAction === "deleted" ||
!isSameLogin(context.payload.comment.user?.login, context.actor))
) {
console.log("Comment was not written by the actor, or was deleted");
return false;
}
if (
isPullRequestReviewEvent(context) &&
!isSameLogin(context.payload.review.user?.login, context.actor)
) {
console.log("Review was written by someone other than the actor");
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
// triage action on an issue would start one.
if (prompt) {
if (
isIssuesEvent(context) &&
context.eventAction === "labeled" &&
labelTrigger &&
!matchesLabelTrigger(context, labelTrigger)
) {
console.log(`Issue label is not the trigger label '${labelTrigger}'`);
return false;
}
if (
isIssuesAssignedEvent(context) &&
assigneeTrigger &&
!matchesAssigneeTrigger(context, assigneeTrigger)
) {
console.log(`Issue was not assigned to '${assigneeTrigger}'`);
return false;
}
console.log(`Prompt provided, triggering action`);
return true;
}
// Check for assignee trigger
if (isIssuesAssignedEvent(context)) {
// Remove @ symbol from assignee_trigger if present
let triggerUser = assigneeTrigger.replace(/^@/, "");
const assigneeUsername = context.payload.assignee?.login || "";
if (triggerUser && assigneeUsername === triggerUser) {
console.log(`Issue assigned to trigger user '${triggerUser}'`);
if (matchesAssigneeTrigger(context, assigneeTrigger)) {
console.log(`Issue assigned to trigger user '${assigneeTrigger}'`);
return true;
}
}
// Check for label trigger
if (isIssuesEvent(context) && context.eventAction === "labeled") {
const labelName = (context.payload as any).label?.name || "";
if (
labelTrigger &&
labelName.toLowerCase() === labelTrigger.toLowerCase()
) {
if (matchesLabelTrigger(context, labelTrigger)) {
console.log(`Issue labeled with trigger label '${labelTrigger}'`);
return true;
}
@@ -125,9 +155,7 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
isIssueCommentEvent(context) ||
isPullRequestReviewCommentEvent(context)
) {
const commentBody = isIssueCommentEvent(context)
? context.payload.comment.body
: context.payload.comment.body;
const commentBody = context.payload.comment.body;
// Check for exact match with word boundaries or punctuation
const regex = new RegExp(
`(^|\\s)${escapeRegExp(triggerPhrase)}([\\s.,!?;:]|$)`,
@@ -144,6 +172,26 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
return false;
}
function matchesLabelTrigger(
context: ParsedGitHubContext,
labelTrigger: string,
): boolean {
const labelName = (context.payload as any).label?.name || "";
return (
!!labelTrigger && labelName.toLowerCase() === labelTrigger.toLowerCase()
);
}
function matchesAssigneeTrigger(
context: ParsedGitHubContext,
assigneeTrigger: string,
): boolean {
// Remove @ symbol from assignee_trigger if present
const triggerUser = assigneeTrigger.replace(/^@/, "");
const assigneeUsername = (context.payload as any).assignee?.login || "";
return !!triggerUser && assigneeUsername === triggerUser;
}
export function escapeRegExp(string: string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
+221
View File
@@ -0,0 +1,221 @@
import * as core from "@actions/core";
import type { Octokit } from "@octokit/rest";
import {
parseAllowedTools,
stripShellComments,
} from "../../modes/agent/parse-tools";
import { retryWithBackoff } from "../../utils/retry";
import type { ParsedGitHubContext } from "../context";
/**
* Commands that commonly execute code from the checkout: package scripts, test
* files, build files and config loaded by interpreters. On a pull request from
* an author without write access that code is attacker-controlled, while the
* session holds the job's tokens. Deny rules take precedence over allow rules,
* so these stay blocked even when claude_args allows them.
*
* The list cannot cover every command, for example a repository's own scripts.
* Rules in claude_args that this list does not cover are logged as a warning.
* Every entry has the form Bash(<command>:*), which isDenied relies on.
*/
export const UNTRUSTED_PR_DISALLOWED_TOOLS = [
// JavaScript
"Bash(bun:*)",
"Bash(bunx:*)",
"Bash(deno:*)",
"Bash(jest:*)",
"Bash(node:*)",
"Bash(npm:*)",
"Bash(npx:*)",
"Bash(pnpm:*)",
"Bash(ts-node:*)",
"Bash(tsx:*)",
"Bash(vitest:*)",
"Bash(yarn:*)",
// Python
"Bash(hatch:*)",
"Bash(nox:*)",
"Bash(pip:*)",
"Bash(pip3:*)",
"Bash(pipenv:*)",
"Bash(poetry:*)",
"Bash(pytest:*)",
"Bash(python:*)",
"Bash(python3:*)",
"Bash(tox:*)",
"Bash(uv:*)",
"Bash(uvx:*)",
// Other languages and build tools
"Bash(bundle:*)",
"Bash(cargo:*)",
"Bash(cmake:*)",
"Bash(composer:*)",
"Bash(docker:*)",
"Bash(dotnet:*)",
"Bash(go:*)",
"Bash(gradle:*)",
"Bash(./gradlew:*)",
"Bash(java:*)",
"Bash(just:*)",
"Bash(make:*)",
"Bash(mvn:*)",
"Bash(./mvnw:*)",
"Bash(perl:*)",
"Bash(php:*)",
"Bash(rake:*)",
"Bash(rspec:*)",
"Bash(ruby:*)",
"Bash(task:*)",
// Shells
"Bash(bash:*)",
"Bash(dash:*)",
"Bash(sh:*)",
"Bash(zsh:*)",
// The simplest ways to point git at a program. Other git commands can still
// run programs, so a broad rule like Bash(git:*) stays unsafe and is warned about.
"Bash(git config:*)",
"Bash(git -c:*)",
];
const SKIPS_PERMISSION_CHECKS =
/--(allow-)?dangerously-skip-permissions|--permission-mode[=\s]+["']?bypassPermissions/;
function getPrAuthor(context: ParsedGitHubContext): string | undefined {
const { payload } = context;
if ("pull_request" in payload) {
return payload.pull_request.user?.login;
}
// On issue_comment events a pull request arrives as an issue, whose user is
// the pull request's author.
if ("issue" in payload) {
return payload.issue.user?.login;
}
return undefined;
}
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.
*/
function toLookupError(error: unknown): LookupError {
const { status, response } = error as {
status?: number;
response?: { headers?: Record<string, string | number | undefined> };
};
const headers = response?.headers;
const rateLimited =
status === 429 ||
(status === 403 &&
(headers?.["retry-after"] !== undefined ||
String(headers?.["x-ratelimit-remaining"]) === "0"));
return Object.assign(
new Error(status === undefined ? "no response" : `HTTP ${status}`),
{
retryable: status === undefined || status >= 500 || rateLimited,
},
);
}
/**
* Whether the pull request's author has write access to the repository. This
* is about who wrote the code, not who triggered the run, so it is deliberately
* stricter than checkWritePermissions: bots are not trusted, allowed_bots and
* allowed_non_write_users do not apply, and any failure counts as untrusted.
*/
async function isPrAuthorTrusted(
octokit: Octokit,
context: ParsedGitHubContext,
): Promise<boolean> {
const author = getPrAuthor(context);
if (!author || author.endsWith("[bot]")) {
return false;
}
try {
const response = await retryWithBackoff(
async () => {
try {
return await octokit.repos.getCollaboratorPermissionLevel({
owner: context.repository.owner,
repo: context.repository.repo,
username: author,
});
} catch (error) {
throw toLookupError(error);
}
},
{
initialDelayMs: 1000,
shouldRetry: (error) => (error as LookupError).retryable,
},
);
const { permission } = response.data;
return permission === "admin" || permission === "write";
} catch (error) {
// Only the bounded text from toLookupError reaches the log.
core.warning(
`Could not check repository access for pull request author ${author}, treating them as untrusted: ${(error as Error).message}`,
);
return false;
}
}
/** Whether a Bash allow rule only permits commands that the deny list blocks. */
function isDenied(rule: string): boolean {
const command = rule.slice("Bash(".length, -")".length);
return UNTRUSTED_PR_DISALLOWED_TOOLS.some((denied) => {
const prefix = denied.slice("Bash(".length, -":*)".length);
return (
command === prefix ||
command.startsWith(`${prefix} `) ||
command.startsWith(`${prefix}:`)
);
});
}
/**
* Returns the tools to deny when the session works on a pull request from an
* author without write access, or an empty list when no restriction applies.
* On by default: only restrict_untrusted_prs: false turns it off, so a mistyped
* value keeps the restriction.
*/
export async function getUntrustedPrDisallowedTools(
octokit: Octokit,
context: ParsedGitHubContext,
): Promise<string[]> {
const disabled =
process.env.RESTRICT_UNTRUSTED_PRS?.trim().toLowerCase() === "false";
if (disabled || !context.isPR) {
return [];
}
if (await isPrAuthorTrusted(octokit, context)) {
return [];
}
core.warning(
`The author of pull request #${context.entityNumber} is not confirmed to have write access, so commands that run code from the checkout are denied. Set restrict_untrusted_prs to "false" to turn this off.`,
);
// These warnings report a count and fixed text, not the content of claude_args,
// which is never printed to the workflow log.
const claudeArgs = process.env.CLAUDE_ARGS || "";
const uncovered = parseAllowedTools(claudeArgs).filter(
(tool) => tool === "Bash" || (tool.startsWith("Bash(") && !isDenied(tool)),
);
if (uncovered.length > 0) {
core.warning(
`${uncovered.length} Bash rule(s) in claude_args are not on the deny list and stay allowed. Check that they cannot run code from the pull request.`,
);
}
if (SKIPS_PERMISSION_CHECKS.test(stripShellComments(claudeArgs))) {
core.warning(
"claude_args turns off permission checks, so commands that are not on the deny list run without approval.",
);
}
return UNTRUSTED_PR_DISALLOWED_TOOLS;
}
+6 -3
View File
@@ -10,6 +10,7 @@ import { GITHUB_API_URL } from "../github/api/config";
import { isBinaryContent } from "./binary-detection";
import { validatePathWithinRepo } from "./path-validation";
import { updateGitReference } from "./update-git-reference";
import { encodeBranchNameForUrl } from "../github/operations/comments/common";
import {
commitFilesInputSchema,
deleteFilesInputSchema,
@@ -66,7 +67,9 @@ async function getOrCreateBranchRef(
githubToken: string,
): Promise<string> {
// Try to get the branch reference
const refUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${branch}`;
// git/ref is an exact lookup. git/refs returns an array of prefix matches when the
// branch doesn't exist, so pr-5 would find pr-50.
const refUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/ref/heads/${encodeBranchNameForUrl(branch)}`;
const refResponse = await fetch(refUrl, {
headers: {
Accept: "application/vnd.github+json",
@@ -87,7 +90,7 @@ async function getOrCreateBranchRef(
const baseBranch = process.env.BASE_BRANCH!;
// Get the SHA of the base branch
const baseRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${baseBranch}`;
const baseRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/ref/heads/${encodeBranchNameForUrl(baseBranch)}`;
const baseRefResponse = await fetch(baseRefUrl, {
headers: {
Accept: "application/vnd.github+json",
@@ -119,7 +122,7 @@ async function getOrCreateBranchRef(
const defaultBranch = repoData.default_branch;
// Try default branch
const defaultRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${defaultBranch}`;
const defaultRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/ref/heads/${encodeBranchNameForUrl(defaultBranch)}`;
const defaultRefResponse = await fetch(defaultRefUrl, {
headers: {
Accept: "application/vnd.github+json",
+1
View File
@@ -26,6 +26,7 @@ function bunServerArgs(scriptPath: string): string[] {
return [
"--no-env-file",
`--config=${actionPath}/bunfig.toml`,
`--tsconfig-override=${actionPath}/tsconfig.json`,
"run",
`${actionPath}/${scriptPath}`,
];
+2 -1
View File
@@ -1,4 +1,5 @@
import fetch, { type RequestInit, type Response } from "node-fetch";
import { encodeBranchNameForUrl } from "../github/operations/comments/common";
import { GITHUB_API_URL } from "../github/api/config";
import { retryWithBackoff, type RetryOptions } from "../utils/retry";
@@ -44,7 +45,7 @@ export async function updateGitReference({
fetchFn = fetch,
retryOptions,
}: UpdateGitReferenceOptions): Promise<void> {
const updateRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${branch}`;
const updateRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${encodeBranchNameForUrl(branch)}`;
await retryWithBackoff(
async () => {
+30 -5
View File
@@ -7,9 +7,33 @@ import {
setupSshSigning,
} from "../../github/operations/git-config";
import { checkHumanActor } from "../../github/validation/actor";
import type { GitHubContext } from "../../github/context";
import { defaultsToAutoMode } from "../permission-mode";
import { isEntityContext, type GitHubContext } from "../../github/context";
import type { Octokits } from "../../github/api/client";
/**
* Commits made through the API land on the branch of this name in this repository,
* so a run on a pull request or issue has to use its own branch. A fork's branch name
* means nothing here, and a comment event only knows the default branch. Tag mode uses
* pr-N too.
*/
function getEntityBranch(context: GitHubContext): string | undefined {
if (!isEntityContext(context)) {
return process.env.GITHUB_HEAD_REF;
}
if (!context.isPR) {
return `issue-${context.entityNumber}`;
}
const head =
"pull_request" in context.payload
? context.payload.pull_request.head
: undefined;
const isSameRepository =
head?.repo?.full_name?.toLowerCase() ===
context.repository.full_name.toLowerCase();
return isSameRepository && head ? head.ref : `pr-${context.entityNumber}`;
}
/**
* Prepares the agent mode execution context.
*
@@ -101,7 +125,7 @@ export async function prepareAgentMode({
// Detect current branch from GitHub environment
const currentBranch =
claudeBranch ||
process.env.GITHUB_HEAD_REF ||
getEntityBranch(context) ||
process.env.GITHUB_REF_NAME ||
defaultBranch;
@@ -118,14 +142,15 @@ export async function prepareAgentMode({
context,
});
// Build final claude_args with multiple --mcp-config flags
let claudeArgs = "";
// Build final claude_args with multiple --mcp-config flags. The user's come last,
// so another --permission-mode there wins.
let claudeArgs = defaultsToAutoMode() ? "--permission-mode auto" : "";
// Add our GitHub servers config if we have any
const ourConfig = JSON.parse(ourMcpConfig);
if (ourConfig.mcpServers && Object.keys(ourConfig.mcpServers).length > 0) {
const escapedOurConfig = ourMcpConfig.replace(/'/g, "'\\''");
claudeArgs = `--mcp-config '${escapedOurConfig}'`;
claudeArgs = `${claudeArgs} --mcp-config '${escapedOurConfig}'`;
}
// Append user's claude_args (which may have more --mcp-config flags)
+77 -8
View File
@@ -1,4 +1,10 @@
import { parse as parseShellArgs } from "shell-quote";
import {
ACCUMULATE_DELIMITER,
escapeShellMeta,
parseClaudeArgsToExtraArgs,
unescapeShellMeta,
} from "../../../base-action/src/parse-sdk-options";
// Flags whose values make up the allowed-tools list.
// Include both camelCase and hyphenated variants for CLI compatibility.
@@ -9,7 +15,7 @@ const ALLOWED_TOOLS_FLAGS = new Set(["allowedTools", "allowed-tools"]);
* Lines whose first non-whitespace character is `#` are removed entirely.
* Mirrors stripShellComments in base-action/src/parse-sdk-options.ts.
*/
function stripShellComments(input: string): string {
export function stripShellComments(input: string): string {
return input
.split("\n")
.filter((line) => !line.trim().startsWith("#"))
@@ -18,17 +24,17 @@ function stripShellComments(input: string): string {
/**
* Tokenize a claude_args string the same way base-action/src/parse-sdk-options.ts
* does: strip full comment lines, then run shell-quote. shell-quote returns
* unquoted glob patterns (e.g. `mcp__github__*`) as `{ op: "glob", pattern }`
* objects rather than strings, so recover their literal text; drop operator
* tokens (`|`, `>`, `;`, ...) which carry no value.
* does: strip full comment lines, escape shell metacharacters so that an unquoted
* `Bash(gh:*)` stays one token, then run shell-quote. shell-quote returns unquoted
* glob patterns (e.g. `mcp__github__*`) as `{ op: "glob", pattern }` objects rather
* than strings, so recover their literal text.
*/
function tokenize(claudeArgs: string): string[] {
return parseShellArgs(stripShellComments(claudeArgs))
return parseShellArgs(escapeShellMeta(stripShellComments(claudeArgs)))
.map((token) => {
if (typeof token === "string") return token;
if (typeof token === "string") return unescapeShellMeta(token);
if (token && typeof token === "object" && "pattern" in token) {
return (token as { pattern: string }).pattern;
return unescapeShellMeta((token as { pattern: string }).pattern);
}
return null;
})
@@ -79,3 +85,66 @@ export function parseAllowedTools(claudeArgs: string): string[] {
return tools;
}
/**
* The patterns of the `Bash(...)` deny rules in a claude_args string. It reads the
* arguments the same way as the code that passes them to the CLI, including the
* `--disallowedTools=...` form, so it sees every rule the CLI receives.
*/
export function parseDeniedBashPatterns(claudeArgs: string): string[] {
const values = Object.entries(parseClaudeArgsToExtraArgs(claudeArgs)).flatMap(
([key, value]) => {
const [flag, inlineValue] = key.split(/=(.*)/s);
return flag === "disallowedTools" || flag === "disallowed-tools"
? [inlineValue ?? "", value ?? ""]
: [];
},
);
const patterns = values.flatMap((value) => [
// Whole rules, whose own text can hold parentheses: Bash(git add "app/(auth)/*").
...value
.split(ACCUMULATE_DELIMITER)
.flatMap((part) => part.match(RULE) ?? [])
.flatMap((rule) => rule.trim().match(/^Bash\((.*)\)$/)?.[1] ?? []),
// Also whatever looks like a rule, so that one the CLI can't read still denies.
...[...value.matchAll(/Bash\(([^)]*)\)/g)].map((match) => match[1]!),
]);
return [...new Set(patterns)];
}
/**
* One rule in a list. Like the CLI, it ends at a comma or space outside parentheses,
* where any `)` ends the parentheses.
*/
const RULE = /(?:\([^)]*\)?|[^ ,(])+/g;
/**
* The deny rules a wrapper needs so a workflow's rules for the command it runs still
* apply: all of it for a rule that covers every use, otherwise each narrower form, so
* `git add -A:*` becomes `<wrapper> -A:*`.
*/
export function wrapperDenyRules(
patterns: string[],
command: string,
wrapper: string,
): string[] {
if (deniesCommand(patterns, command)) return [`Bash(${wrapper}:*)`];
return patterns
.filter((pattern) => pattern.startsWith(`${command} `))
.map((pattern) => `Bash(${wrapper}${pattern.slice(command.length)})`);
}
/**
* Whether a Bash deny pattern covers every use of a command. Narrower patterns,
* such as `git commit --amend:*`, don't count.
*/
export function deniesCommand(patterns: string[], command: string): boolean {
return patterns.some((pattern) => {
const escape = (text: string) => text.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
const toRegex = (glob: string) => glob.split("*").map(escape).join(".*");
const source = pattern.endsWith(":*")
? `${toRegex(pattern.slice(0, -2))}( .*)?`
: toRegex(pattern);
return new RegExp(`^${source}$`, "s").test(`${command} \0`);
});
}
+48
View File
@@ -0,0 +1,48 @@
type SettingsInput = {
permissions?: { defaultMode?: unknown };
env?: { ANTHROPIC_BASE_URL?: unknown };
} | null;
/**
* Whether a session starts in auto mode unless claude_args sets another mode.
*
* These runs keep their earlier default and can opt in:
* - allowed_non_write_users or allowed_bots: other people's text reaches these
* runs without a write-access check, so what no allow rule covers stays denied
* rather than left to a review.
* - A custom ANTHROPIC_BASE_URL, in the environment or the settings input: auto
* mode's safety check can depend on what an LLM gateway passes through, and a
* session that gets no verdict denies calls and can stop.
* - path_to_claude_code_executable: the action doesn't install that CLI, and one
* that predates auto mode exits on the flag before the session starts.
* - A settings input that chooses a permission mode other than auto: the default
* must not silently replace a mode the workflow chose.
* - A settings input that is a file path: a pull request can change that file, and
* config restored from the base branch comes later, so it can't decide this.
*/
export function defaultsToAutoMode(): boolean {
if (
process.env.ALLOWED_NON_WRITE_USERS?.trim() ||
process.env.ALLOWED_BOTS?.trim() ||
process.env.ANTHROPIC_BASE_URL?.trim() ||
process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE?.trim()
) {
return false;
}
const input = process.env.INPUT_SETTINGS?.trim();
if (!input) return true;
let settings: SettingsInput;
try {
settings = JSON.parse(input);
} catch {
return false;
}
const baseUrl = settings?.env?.ANTHROPIC_BASE_URL;
const mode = settings?.permissions?.defaultMode;
return (
!(typeof baseUrl === "string" && baseUrl.trim()) &&
(!mode || mode === "auto")
);
}
+76 -13
View File
@@ -1,4 +1,6 @@
import { checkHumanActor } from "../../github/validation/actor";
import { defaultsToAutoMode } from "../permission-mode";
import { pinPushBranch } from "../../github/operations/session-guard";
import { createInitialComment } from "../../github/operations/comments/create-initial";
import { setupBranch } from "../../github/operations/branch";
import {
@@ -14,10 +16,19 @@ import {
extractOriginalBody,
} from "../../github/data/fetcher";
import { createPrompt } from "../../create-prompt";
import { isEntityContext } from "../../github/context";
import {
isEntityContext,
isIssueCommentEvent,
isPullRequestReviewCommentEvent,
} from "../../github/context";
import { updateClaudeComment } from "../../github/operations/comments/update-claude-comment";
import type { GitHubContext } from "../../github/context";
import type { Octokits } from "../../github/api/client";
import { parseAllowedTools } from "../agent/parse-tools";
import {
parseAllowedTools,
parseDeniedBashPatterns,
wrapperDenyRules,
} from "../agent/parse-tools";
/**
* Prepares the tag mode execution context.
@@ -64,7 +75,30 @@ export async function prepareTagMode({
});
// Setup branch
const branchInfo = await setupBranch(octokit, githubData, context);
const editedAt =
context.eventAction === "edited" &&
(isIssueCommentEvent(context) || isPullRequestReviewCommentEvent(context))
? context.payload.comment.updated_at
: undefined;
let branchInfo;
try {
branchInfo = await setupBranch(
octokit,
githubData,
context,
editedAt || triggerTime,
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
await updateClaudeComment(octokit.rest, {
owner: context.repository.owner,
repo: context.repository.repo,
commentId,
body: message,
isPullRequestReviewComment: isPullRequestReviewCommentEvent(context),
}).catch((e) => console.error(`Failed to update tracking comment: ${e}`));
throw error;
}
// Configure git authentication
// SSH signing takes precedence if provided
@@ -125,11 +159,18 @@ export async function prepareTagMode({
tool.startsWith("mcp__github_"),
);
const sessionBranch = branchInfo.claudeBranch || branchInfo.currentBranch;
// scripts/git-push.sh refuses to update any other branch.
pinPushBranch(sessionBranch);
const gitAddWrapper = `${process.env.GITHUB_ACTION_PATH}/scripts/git-add.sh`;
const gitRmWrapper = `${process.env.GITHUB_ACTION_PATH}/scripts/git-rm.sh`;
const gitPushWrapper = `${process.env.GITHUB_ACTION_PATH}/scripts/git-push.sh`;
const gitCommitWrapper = `${process.env.GITHUB_ACTION_PATH}/scripts/git-commit.sh`;
// Build claude_args for tag mode with required tools.
// Edit/MultiEdit/Write are intentionally omitted: acceptEdits permission mode (set below)
// auto-allows file edits inside $GITHUB_WORKSPACE and denies writes outside (e.g. ~/.bashrc).
// Edit/MultiEdit/Write are intentionally omitted: the permission mode (set below) allows
// file edits inside $GITHUB_WORKSPACE and doesn't allow every write outside (e.g. ~/.bashrc).
// Listing them here would grant blanket write access to the whole runner (Asana 1213310082312048).
const tagModeTools = [
"Glob",
@@ -147,10 +188,10 @@ export async function prepareTagMode({
// SSH signing still uses git CLI, just with signing enabled
if (!useApiCommitSigning) {
tagModeTools.push(
"Bash(git add:*)",
"Bash(git commit:*)",
`Bash(${gitAddWrapper}:*)`,
`Bash(${gitCommitWrapper}:*)`,
`Bash(${gitPushWrapper}:*)`,
"Bash(git rm:*)",
`Bash(${gitRmWrapper}:*)`,
);
} else {
// When using API commit signing, use MCP file ops tools
@@ -165,7 +206,7 @@ export async function prepareTagMode({
githubToken,
owner: context.repository.owner,
repo: context.repository.repo,
branch: branchInfo.claudeBranch || branchInfo.currentBranch,
branch: sessionBranch,
baseBranch: branchInfo.baseBranch,
claudeCommentId: commentId.toString(),
allowedTools: Array.from(new Set(tagModeTools)),
@@ -181,11 +222,33 @@ export async function prepareTagMode({
claudeArgs = `--mcp-config '${escapedOurConfig}'`;
// Add required tools for tag mode.
// acceptEdits: file edits auto-allowed inside cwd ($GITHUB_WORKSPACE), denied outside.
// Headless SDK has no prompt handler, so anything that falls through to "ask" is denied.
claudeArgs += ` --permission-mode acceptEdits --allowedTools "${tagModeTools.join(",")}"`;
// auto: file edits allowed inside cwd ($GITHUB_WORKSPACE), and a safety review decides
// calls that no rule covers.
// acceptEdits: file edits allowed inside cwd, denied outside. The headless SDK has no
// prompt handler, so anything that falls through to "ask" is denied.
const permissionMode = defaultsToAutoMode() ? "auto" : "acceptEdits";
claudeArgs += ` --permission-mode ${permissionMode} --allowedTools "${tagModeTools.join(",")}"`;
// Append user's claude_args (which may have more --mcp-config flags)
// Deny rules match the command's text, so a workflow's deny of a git command
// wouldn't match the wrapper that runs it. Deny the wrappers too.
const userDeniedTools = parseDeniedBashPatterns(userClaudeArgs);
const wrappers: [string, string][] = [
["git commit", gitCommitWrapper],
["git push", gitPushWrapper],
["git add", gitAddWrapper],
["git rm", gitRmWrapper],
];
const deniedWrappers = wrappers.flatMap(([command, wrapper]) =>
wrapperDenyRules(userDeniedTools, command, wrapper),
);
if (deniedWrappers.length > 0) {
// A narrower rule can hold quotes or a $, and this string gets parsed again.
const rules = deniedWrappers.join(",").replace(/'/g, "'\\''");
claudeArgs += ` --disallowedTools '${rules}'`;
}
// Append user's claude_args (which may have more --mcp-config flags, or another
// --permission-mode, where the last one wins)
if (userClaudeArgs) {
claudeArgs += ` ${userClaudeArgs}`;
}
+56
View File
@@ -12,4 +12,60 @@ describe("action metadata", () => {
/^ conclusion:\n description: .+\n value: \$\{\{ steps\.run\.outputs\.conclusion \}\}$/m,
);
});
test("should keep restrict_untrusted_prs on by default and pass it to the run step", () => {
const metadata = readFileSync(
new URL("../action.yml", import.meta.url),
"utf8",
);
expect(metadata).toMatch(
/^ restrict_untrusted_prs:\n description: .+\n required: false\n default: "true"$/m,
);
expect(metadata).toMatch(
/^ RESTRICT_UNTRUSTED_PRS: \$\{\{ inputs\.restrict_untrusted_prs \}\}$/m,
);
});
test("should start each of the action's scripts with the same Bun options", () => {
const commands = readFileSync(
new URL("../action.yml", import.meta.url),
"utf8",
)
.replace(/\\\n\s*/g, "")
.split("\n")
.filter((line) => line.includes("${GITHUB_ACTION_PATH}/src/"));
expect(commands).toHaveLength(3);
for (const command of commands) {
expect(command).toContain(
' --no-env-file --config="${GITHUB_ACTION_PATH}/bunfig.toml"' +
' --tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json"' +
" run ${GITHUB_ACTION_PATH}/src/entrypoints/",
);
}
});
test("should not put step outputs into shell scripts", () => {
// A session can write step outputs, so an expression in a script could run
// its commands. Scripts have to read these values from the environment.
const lines = readFileSync(
new URL("../action.yml", import.meta.url),
"utf8",
).split("\n");
const inScripts: string[] = [];
let scriptIndent: number | null = null;
for (const line of lines) {
const indent = line.search(/\S/);
if (scriptIndent !== null && indent !== -1 && indent <= scriptIndent) {
scriptIndent = null;
}
if (scriptIndent !== null && line.includes("${{ steps.")) {
inScripts.push(line.trim());
}
const run = line.match(/^(\s*)run: \|/);
if (run) scriptIndent = run[1]!.length;
}
expect(inScripts).toEqual([]);
});
});
+87 -11
View File
@@ -2,6 +2,7 @@
import { describe, test, expect, beforeAll } from "bun:test";
import {
extractUserRequestFromContext,
generatePrompt,
getEventTypeAndContext,
buildAllowedToolsString,
@@ -789,8 +790,8 @@ describe("generatePrompt", () => {
// Should have git command instructions
expect(prompt).toContain("Use git commands via the Bash tool");
expect(prompt).toContain("git add");
expect(prompt).toContain("git commit");
expect(prompt).toContain("scripts/git-add.sh");
expect(prompt).toContain("scripts/git-commit.sh -m");
expect(prompt).toContain("scripts/git-push.sh origin");
// Should use the minimal comment tool
@@ -1073,7 +1074,7 @@ describe("buildAllowedToolsString", () => {
const result = buildAllowedToolsString();
// The base tools should be in the result
// Edit/MultiEdit/Write are NOT in allowedTools — acceptEdits permission mode handles them
// Edit/MultiEdit/Write are NOT in allowedTools — the permission mode handles them
expect(result).not.toContain("Edit");
expect(result).not.toContain("Write");
expect(result).toContain("Glob");
@@ -1082,8 +1083,9 @@ describe("buildAllowedToolsString", () => {
expect(result).toContain("Read");
// Default is no commit signing, so should have specific Bash git commands
expect(result).toContain("Bash(git add:*)");
expect(result).toContain("Bash(git commit:*)");
expect(result).toContain("scripts/git-add.sh:*)");
expect(result).toContain("scripts/git-commit.sh:*)");
expect(result).not.toContain("Bash(git commit:*)");
expect(result).toContain("scripts/git-push.sh:*)");
expect(result).toContain("mcp__github_comment__update_claude_comment");
@@ -1104,8 +1106,8 @@ describe("buildAllowedToolsString", () => {
expect(result).not.toContain("Write");
// Should have specific Bash git commands for non-signing mode
expect(result).toContain("Bash(git add:*)");
expect(result).toContain("Bash(git commit:*)");
expect(result).toContain("scripts/git-add.sh:*)");
expect(result).toContain("scripts/git-commit.sh:*)");
expect(result).toContain("mcp__github_comment__update_claude_comment");
// Should not have commit signing tools
@@ -1197,10 +1199,10 @@ describe("buildAllowedToolsString", () => {
expect(result).not.toContain("Write");
// Specific Bash git commands should be included
expect(result).toContain("Bash(git add:*)");
expect(result).toContain("Bash(git commit:*)");
expect(result).toContain("scripts/git-add.sh:*)");
expect(result).toContain("scripts/git-commit.sh:*)");
expect(result).toContain("scripts/git-push.sh:*)");
expect(result).toContain("Bash(git rm:*)");
expect(result).toContain("scripts/git-rm.sh:*)");
// Comment tool from minimal server should be included
expect(result).toContain("mcp__github_comment__update_claude_comment");
@@ -1216,7 +1218,7 @@ describe("buildAllowedToolsString", () => {
// Base tools should be present
expect(result).toContain("Read");
expect(result).toContain("Bash(git add:*)");
expect(result).toContain("scripts/git-add.sh:*)");
// Custom tools should be included
expect(result).toContain("CustomTool1");
@@ -1387,3 +1389,77 @@ describe("prepareContext validation errors", () => {
);
});
});
describe("extractUserRequestFromContext", () => {
const extract = (
bodyAuthor: string | null,
actor: string,
typename = "User",
) =>
extractUserRequestFromContext(
{
repository: "o/r",
triggerPhrase: "@claude",
claudeCommentId: "1",
eventData: {
eventName: "issues",
eventAction: "labeled",
issueNumber: "1",
labelTrigger: "claude",
},
githubContext: { actor },
} as any,
{
contextData: {
body: "A bug. @claude /deploy now",
author: bodyAuthor
? { __typename: typename, login: bodyAuthor }
: null,
},
} as any,
);
test("uses the body when its author is the person who triggered the run", () => {
expect(extract("maintainer", "maintainer")).toBe("/deploy now");
expect(extract("Maintainer", "maintainer")).toBe("/deploy now");
});
test("matches a bot's GraphQL login to its actor name", () => {
expect(extract("some-app", "some-app[bot]", "Bot")).toBe("/deploy now");
});
test("does not treat a person as a bot with the same name", () => {
expect(extract("some-app", "some-app[bot]", "User")).toBeNull();
});
test("ignores the body when someone else wrote it", () => {
expect(extract("outsider", "maintainer")).toBeNull();
});
test("uses a comment only when its author triggered the run", () => {
const fromComment = (commentAuthor: string, actor: string) =>
extractUserRequestFromContext(
{
repository: "o/r",
triggerPhrase: "@claude",
claudeCommentId: "1",
eventData: {
eventName: "issue_comment",
commentBody: "@claude /deploy now",
},
githubContext: {
eventName: "issue_comment",
actor,
payload: { comment: { user: { login: commentAuthor } } },
},
} as any,
{ contextData: {} } as any,
);
expect(fromComment("maintainer", "maintainer")).toBe("/deploy now");
expect(fromComment("outsider", "maintainer")).toBeNull();
});
test("ignores the body when its author is unknown", () => {
expect(extract(null, "maintainer")).toBeNull();
});
});
+52
View File
@@ -182,25 +182,72 @@ describe("resolveTriggerTimestamp", () => {
};
};
it("should match an assignment by its assigner when the actor is the assignee", async () => {
const { octokits } = createEventsOctokits([
{
event: "assigned",
actor: { login: "claude-bot" },
assignee: { login: "claude-bot" },
assigner: { login: "admin-user" },
created_at: "2024-01-15T11:50:00Z",
},
]);
const timestamp = await resolveTriggerTimestamp(
mockIssueAssignedContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T11:50:00Z");
});
it("should ignore a later matching event from someone other than the actor", async () => {
const { octokits } = createEventsOctokits([
{
event: "labeled",
actor: { login: "admin-user" },
label: { name: "claude-task" },
created_at: "2024-01-15T11:45:00Z",
},
{
event: "labeled",
actor: { login: "triage-user" },
label: { name: "claude-task" },
created_at: "2024-01-15T12:30:00Z",
},
]);
const timestamp = await resolveTriggerTimestamp(
mockIssueLabeledContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T11:45:00Z");
});
it("should use the labeled event time for issues labeled event", async () => {
const { octokits, paginate } = createEventsOctokits([
{
event: "labeled",
actor: { login: "admin-user" },
label: { name: "other-label" },
created_at: "2024-01-15T10:45:00Z",
},
{
event: "labeled",
actor: { login: "admin-user" },
label: { name: "claude-task" },
created_at: "2024-01-15T10:50:00Z",
},
{
event: "labeled",
actor: { login: "admin-user" },
label: { name: "claude-task" },
created_at: "2024-01-15T11:45:00Z",
},
{
event: "assigned",
actor: { login: "admin-user" },
assignee: { login: "claude-bot" },
created_at: "2024-01-15T11:50:00Z",
},
@@ -224,11 +271,13 @@ describe("resolveTriggerTimestamp", () => {
const { octokits } = createEventsOctokits([
{
event: "assigned",
actor: { login: "admin-user" },
assignee: { login: "someone-else" },
created_at: "2024-01-15T10:40:00Z",
},
{
event: "assigned",
actor: { login: "admin-user" },
assignee: { login: "claude-bot" },
created_at: "2024-01-15T11:05:00Z",
},
@@ -248,6 +297,7 @@ describe("resolveTriggerTimestamp", () => {
const { octokits } = createEventsOctokits([
{
event: "labeled",
actor: { login: "admin-user" },
label: { name: "claude-task" },
created_at: "2024-01-15T10:50:00Z",
},
@@ -265,6 +315,7 @@ describe("resolveTriggerTimestamp", () => {
const { octokits } = createEventsOctokits([
{
event: "labeled",
actor: { login: "admin-user" },
label: { name: "unrelated" },
created_at: "2024-01-15T10:45:00Z",
},
@@ -1003,6 +1054,7 @@ describe("fetchGitHubData integration with time filtering", () => {
paginate: jest.fn().mockResolvedValue([
{
event: "labeled",
actor: { login: "admin-user" },
label: { name: "claude-task" },
created_at: "2024-01-15T11:45:00Z",
},
+87 -3
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { execFileSync } from "child_process";
import { mkdtempSync, rmSync, statSync } from "fs";
import { mkdirSync, mkdtempSync, rmSync, statSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import {
@@ -18,6 +18,7 @@ const NOREPLY_DOMAIN =
? "users.noreply.github.com"
: `users.noreply.${SERVER.hostname}`;
const EXTRAHEADER_KEY = `http.${GITHUB_SERVER_URL}/.extraheader`;
const HELPER_KEY = `credential.https://${SERVER.host}.helper`;
// git exports these into hooks (e.g. a pre-commit hook running the test
// suite); if inherited they would point every git command below at the
@@ -142,14 +143,97 @@ describe("git-config", () => {
expect(gitConfigGetAll(EXTRAHEADER_KEY)).toBe("");
expect(remoteUrl()).toBe(
`https://${SERVER.host}/test-owner/test-repo.git`,
`https://x-access-token@${SERVER.host}/test-owner/test-repo.git`,
);
const helperPath = join(tempDir, ".git-credential-gh-token");
expect(gitConfigGetAll("credential.helper")).toBe(helperPath);
expect(gitConfigGetAll(HELPER_KEY)).toBe(`!'${helperPath}'`);
expect(statSync(helperPath).mode & 0o777).toBe(0o700);
expect(process.env.GH_TOKEN).toBe("helper-token");
});
describe("credential helper answers", () => {
const fill = (host: string, token: string) =>
execFileSync("git", ["credential", "fill"], {
cwd: repoDir,
encoding: "utf8",
input: `protocol=https\nhost=${host}\n\n`,
env: {
...process.env,
GH_TOKEN: token,
GIT_CONFIG_GLOBAL: "/dev/null",
GIT_CONFIG_NOSYSTEM: "1",
GIT_ASKPASS: "echo",
GIT_TERMINAL_PROMPT: "0",
},
});
beforeEach(() => {
process.env.ALLOWED_NON_WRITE_USERS = "someone";
});
test("gives the token to this server", async () => {
await replaceCheckoutCredentials(
"helper-token",
createMockAutomationContext(),
);
expect(fill(SERVER.host, "helper-token")).toContain(
"password=helper-token",
);
});
test("gives the token to no other host", async () => {
await replaceCheckoutCredentials(
"helper-token",
createMockAutomationContext(),
);
expect(fill("other.example.com", "helper-token")).not.toContain(
"helper-token",
);
});
test("leaves it to other credentials when there is no token", async () => {
await replaceCheckoutCredentials(
"helper-token",
createMockAutomationContext(),
);
// GIT_ASKPASS is `echo`, which prints its prompt, so a password that
// isn't empty came from the next credential source.
expect(fill(SERVER.host, "")).toMatch(/password=.+/);
});
test("runs from a path with a space", async () => {
const spaced = join(tempDir, "action dir");
mkdirSync(spaced);
process.env.GITHUB_ACTION_PATH = spaced;
await replaceCheckoutCredentials(
"helper-token",
createMockAutomationContext(),
);
expect(fill(SERVER.host, "helper-token")).toContain(
"password=helper-token",
);
});
});
test("uses a credential helper when bots are allowed", async () => {
const context = createMockAutomationContext({
inputs: {
...createMockAutomationContext().inputs,
allowedBots: "sentry-io[bot]",
},
} as any);
await replaceCheckoutCredentials("bot-token", context);
expect(remoteUrl()).toBe(
`https://x-access-token@${SERVER.host}/test-owner/test-repo.git`,
);
expect(gitConfigGetAll(HELPER_KEY)).toBe(
`!'${join(tempDir, ".git-credential-gh-token")}'`,
);
expect(process.env.GH_TOKEN).toBe("bot-token");
});
test("succeeds when there is no checkout extraheader to remove", async () => {
git(["config", "--local", "--unset-all", EXTRAHEADER_KEY]);
+493
View File
@@ -0,0 +1,493 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { spawnSync } from "child_process";
import {
chmodSync,
copyFileSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "fs";
import { tmpdir } from "os";
import { join, resolve } from "path";
const SCRIPTS = resolve(import.meta.dir, "../scripts");
// The wrappers clear GIT_CONFIG_GLOBAL, so a developer's own config needs HOME moved.
let testHome = tmpdir();
// git exports these into hooks, such as a pre-commit hook running this suite.
const env = () => {
const copy = {
...process.env,
HOME: testHome,
GIT_AUTHOR_NAME: "t",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "t",
GIT_COMMITTER_EMAIL: "[email protected]",
GIT_CONFIG_NOSYSTEM: "1",
GIT_CONFIG_GLOBAL: "/dev/null",
};
for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"]) {
delete copy[key as keyof typeof copy];
}
return copy;
};
describe("git wrappers", () => {
let dir: string;
let repo: string;
let remote: string;
const run = (cmd: string, ...args: string[]) =>
spawnSync(cmd, args, { cwd: repo, env: env(), encoding: "utf8" });
const git = (...args: string[]) => {
const result = run("git", ...args);
if (result.status !== 0) throw new Error(result.stderr);
return result.stdout.trim();
};
const commit = (...args: string[]) =>
run(join(SCRIPTS, "git-commit.sh"), ...args);
const remoteHead = () =>
spawnSync("git", ["-C", remote, "rev-parse", "main"], {
env: env(),
encoding: "utf8",
}).stdout.trim();
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "git-wrappers-"));
testHome = dir;
repo = join(dir, "repo");
remote = join(dir, "remote.git");
spawnSync("git", ["init", "-q", "--bare", "-b", "main", remote], {
env: env(),
});
spawnSync("git", ["init", "-q", "-b", "main", repo], { env: env() });
git("remote", "add", "origin", remote);
git("commit", "-q", "--allow-empty", "-m", "first");
git("push", "-q", "origin", "main");
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
describe("git-commit.sh", () => {
const literalMessages = [
["-m", "a message"],
["-m", "a", "-m", "b"],
["--message", "a message"],
["--message=a message"],
];
for (const args of literalMessages) {
test(`commits a literal message: ${args.join(" ")}`, () => {
expect(commit("--allow-empty", ...args).status).toBe(0);
});
}
test("commits staged and named paths", () => {
writeFileSync(join(repo, "a.txt"), "a\n");
writeFileSync(join(repo, "b.txt"), "b\n");
git("add", "a.txt", "b.txt");
expect(commit("-m", "two", "--", "a.txt").status).toBe(0);
expect(git("status", "--short")).toBe("A b.txt");
});
test("treats flag-like text in a message as the message", () => {
expect(commit("--allow-empty", "-m", "-F .git/config").status).toBe(0);
expect(git("log", "-1", "--format=%s")).toBe("-F .git/config");
});
const rejected = [
["-F", ".git/config"],
["-F.git/config"],
["--file", ".git/config"],
["--file=.git/config"],
["-t", ".git/config"],
["--template=.git/config"],
["-C", "HEAD"],
["-c", "HEAD"],
["--reuse-message=HEAD"],
["--reedit-message=HEAD"],
["--fixup=HEAD"],
["--pathspec-from-file=.git/config"],
["--no-verify", "-m", "x"],
["--author=x <[email protected]>", "-m", "x"],
["-amx"],
];
for (const args of rejected) {
test(`rejects ${args.join(" ")}`, () => {
const before = git("rev-parse", "HEAD");
const result = commit("--allow-empty", ...args);
expect(result.status).toBe(1);
expect(result.stderr).toContain("Error:");
expect(git("rev-parse", "HEAD")).toBe(before);
});
}
test("requires a message", () => {
expect(commit("--allow-empty").status).toBe(1);
expect(commit("-m").status).toBe(1);
});
// A pushed commit can't be amended and pushed again, because forced pushes are
// refused, so the work would be stranded on the runner.
for (const args of [
["--amend"],
["--amend", "--no-edit"],
["--amend", "-m", "new"],
]) {
test(`rejects an amend: ${args.join(" ")}`, () => {
expect(commit(...args).status).toBe(1);
});
}
test("does not read a file into the commit", () => {
const secret = readFileSync(join(repo, ".git", "config"), "utf8");
commit("--allow-empty", "-F", ".git/config");
expect(git("log", "-1", "--format=%B")).not.toContain(secret.trim());
});
});
describe("git-add.sh and git-rm.sh", () => {
const add = (...args: string[]) =>
run(join(SCRIPTS, "git-add.sh"), ...args);
const rm = (...args: string[]) => run(join(SCRIPTS, "git-rm.sh"), ...args);
test("git-add.sh stages files", () => {
writeFileSync(join(repo, "a.txt"), "a");
expect(add("a.txt").status).toBe(0);
expect(git("diff", "--cached", "--name-only")).toBe("a.txt");
});
test.each([
["-e"],
["--edit"],
["-p"],
["-i"],
["-f"],
["--force"],
["--pathspec-from-file=.git/config"],
])("git-add.sh rejects %s", (flag) => {
const result = add(flag, ".");
expect(result.status).toBe(1);
expect(result.stderr).toContain("are allowed");
});
test("git-add.sh takes a path that looks like a flag after --", () => {
writeFileSync(join(repo, "-e"), "a");
expect(add("--", "-e").status).toBe(0);
expect(git("diff", "--cached", "--name-only")).toBe("-e");
});
test("git-add.sh records the executable bit", () => {
writeFileSync(join(repo, "run.sh"), "#!/bin/sh\n");
run(join(SCRIPTS, "git-add.sh"), "--chmod=+x", "run.sh");
expect(git("ls-files", "--stage", "run.sh")).toStartWith("100755");
});
test("git-rm.sh removes files and rejects other flags", () => {
writeFileSync(join(repo, "a.txt"), "a");
git("add", "a.txt");
git("commit", "-q", "-m", "add");
expect(rm("--pathspec-from-file=.git/config").status).toBe(1);
expect(rm("a.txt").status).toBe(0);
expect(existsSync(join(repo, "a.txt"))).toBe(false);
});
});
describe("settings the wrappers ignore", () => {
const withMarker = () => {
const marker = join(dir, "marker");
const program = join(dir, "program.sh");
writeFileSync(program, `#!/bin/sh\necho ran >> "${marker}"\n`);
chmodSync(program, 0o755);
return { marker, program };
};
const inEnv = (
script: string,
args: string[],
extra: Record<string, string>,
) =>
spawnSync(join(SCRIPTS, script), args, {
cwd: repo,
env: { ...env(), ...extra },
encoding: "utf8",
});
test.each([
["git-add.sh", ["."]],
["git-commit.sh", ["--allow-empty", "-m", "x"]],
])("%s ignores program settings in GIT_CONFIG_*", (script, args) => {
const { marker, program } = withMarker();
writeFileSync(join(repo, "a.txt"), "a");
const result = inEnv(script, args, {
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: "core.fsmonitor",
GIT_CONFIG_VALUE_0: program,
});
expect(result.status).toBe(0);
expect(existsSync(marker)).toBe(false);
});
test("git-add.sh ignores XDG_CONFIG_HOME", () => {
const { marker, program } = withMarker();
mkdirSync(join(dir, "xdg/git"), { recursive: true });
writeFileSync(
join(dir, "xdg/git/config"),
`[core]\n\tfsmonitor = ${program}\n`,
);
writeFileSync(join(repo, "a.txt"), "a");
const result = inEnv("git-add.sh", ["a.txt"], {
XDG_CONFIG_HOME: join(dir, "xdg"),
});
expect(result.status).toBe(0);
expect(existsSync(marker)).toBe(false);
});
// What the action writes beside the scripts, in a copy of them.
const copyScripts = (state: Record<string, string>) => {
const scripts = join(dir, "scripts");
mkdirSync(scripts, { recursive: true });
for (const name of ["git-add.sh", "git-commit.sh", "git-env.sh"]) {
copyFileSync(join(SCRIPTS, name), join(scripts, name));
}
for (const [name, content] of Object.entries(state)) {
writeFileSync(join(scripts, name), content);
}
return scripts;
};
test("hooks stay on unless the action turned them off", () => {
const { marker, program } = withMarker();
mkdirSync(join(repo, "hooks"));
copyFileSync(program, join(repo, "hooks/pre-commit"));
git("config", "core.hooksPath", "hooks");
const commitWith = (scripts: string) =>
spawnSync(
join(scripts, "git-commit.sh"),
["--allow-empty", "-m", "x"],
{ cwd: repo, env: env(), encoding: "utf8" },
);
expect(commitWith(copyScripts({ ".no-hooks": "" })).status).toBe(0);
expect(existsSync(marker)).toBe(false);
rmSync(join(dir, "scripts/.no-hooks"));
expect(commitWith(join(dir, "scripts")).status).toBe(0);
expect(existsSync(marker)).toBe(true);
});
test("the wrappers use the recorded home", () => {
const { marker, program } = withMarker();
const fakeHome = join(dir, "fake-home");
mkdirSync(fakeHome);
writeFileSync(join(fakeHome, "attributes"), "a.txt filter=x\n");
writeFileSync(
join(fakeHome, ".gitconfig"),
`[core]\n\tattributesFile = ${join(fakeHome, "attributes")}\n[filter "x"]\n\tclean = ${program}\n`,
);
writeFileSync(join(repo, "a.txt"), "a");
const gitDir = join(repo, ".git");
const scripts = copyScripts({
".git-repo": `${gitDir}\n${repo}\n${testHome}\n`,
});
const run = (path: string) =>
spawnSync(join(path, "git-add.sh"), ["a.txt"], {
cwd: repo,
env: { ...env(), HOME: fakeHome },
encoding: "utf8",
});
expect(run(scripts).status).toBe(0);
expect(existsSync(marker)).toBe(false);
// Without the recorded home, that config is read, so the check above means something.
run(SCRIPTS);
expect(existsSync(marker)).toBe(true);
});
describe("a folder shaped like a repository", () => {
const makeFolder = () => {
const { marker, program } = withMarker();
const evil = join(repo, "evil");
mkdirSync(join(evil, "objects"), { recursive: true });
mkdirSync(join(evil, "refs"));
writeFileSync(join(evil, "HEAD"), "ref: refs/heads/main\n");
writeFileSync(join(dir, "attributes"), "* filter=x\n");
writeFileSync(
join(evil, "config"),
`[core]\n\tbare = false\n\tworktree = ..\n\tattributesFile = ${join(dir, "attributes")}\n[filter "x"]\n\tclean = ${program}\n`,
);
writeFileSync(join(repo, "a.txt"), "a");
return { marker, evil };
};
test("the wrappers stay on the recorded repository", () => {
const { marker, evil } = makeFolder();
const gitDir = join(repo, ".git");
const scripts = copyScripts({ ".git-repo": `${gitDir}\n${repo}\n` });
const result = spawnSync(join(scripts, "git-add.sh"), ["../a.txt"], {
cwd: evil,
env: env(),
encoding: "utf8",
});
expect(result.status).toBe(0);
expect(existsSync(marker)).toBe(false);
expect(git("diff", "--cached", "--name-only")).toBe("a.txt");
});
test("with nothing recorded, git refuses the folder", () => {
const { marker, evil } = makeFolder();
const result = spawnSync(join(SCRIPTS, "git-add.sh"), ["../a.txt"], {
cwd: evil,
env: env(),
encoding: "utf8",
});
expect(result.status).not.toBe(0);
expect(existsSync(marker)).toBe(false);
});
});
test("git-commit.sh ignores GIT_DIR", () => {
const before = git("rev-parse", "HEAD");
const result = inEnv("git-commit.sh", ["--allow-empty", "-m", "x"], {
GIT_DIR: join(dir, "elsewhere"),
});
expect(result.status).toBe(0);
expect(git("rev-parse", "HEAD")).not.toBe(before);
});
});
describe("git-push.sh", () => {
const SESSION_BRANCH = "claude/issue-1";
const push = (
ref: string,
branch: string | null = SESSION_BRANCH,
remoteName = "origin",
) => {
const pushEnv: Record<string, string | undefined> = { ...env() };
if (branch === null) delete pushEnv.CLAUDE_PUSH_BRANCH;
else pushEnv.CLAUDE_PUSH_BRANCH = branch;
return spawnSync(join(SCRIPTS, "git-push.sh"), [remoteName, ref], {
cwd: repo,
env: pushEnv,
encoding: "utf8",
});
};
test("the recorded branch wins over CLAUDE_PUSH_BRANCH", () => {
const scripts = join(dir, "scripts");
mkdirSync(scripts);
for (const name of ["git-push.sh", "git-env.sh"]) {
copyFileSync(join(SCRIPTS, name), join(scripts, name));
}
writeFileSync(join(scripts, ".push-branch"), SESSION_BRANCH);
git("commit", "-q", "--allow-empty", "-m", "second");
const before = remoteHead();
const result = spawnSync(
join(scripts, "git-push.sh"),
["origin", "HEAD"],
{
cwd: repo,
env: { ...env(), CLAUDE_PUSH_BRANCH: "main" },
encoding: "utf8",
},
);
expect(result.status).toBe(0);
expect(remoteHead()).toBe(before);
expect(remoteBranch(SESSION_BRANCH)).toBe(git("rev-parse", "HEAD"));
});
const remoteBranch = (branch: string) =>
spawnSync(
"git",
["-C", remote, "rev-parse", "--verify", "-q", `refs/heads/${branch}`],
{ env: env(), encoding: "utf8" },
).stdout.trim();
beforeEach(() => {
git("checkout", "-q", "-b", SESSION_BRANCH);
git("commit", "-q", "--allow-empty", "-m", "session work");
});
test.each(["HEAD", SESSION_BRANCH])(
"pushes %p to the session branch",
(ref) => {
expect(push(ref).status).toBe(0);
expect(remoteBranch(SESSION_BRANCH)).toBe(git("rev-parse", "HEAD"));
},
);
test("pushes to main when main is the session branch", () => {
git("checkout", "-q", "main");
git("commit", "-q", "--allow-empty", "-m", "second");
expect(push("main", "main").status).toBe(0);
expect(remoteHead()).toBe(git("rev-parse", "HEAD"));
});
test("doesn't push local main moved onto the session's commit", () => {
const before = remoteHead();
git("update-ref", "refs/heads/main", git("rev-parse", "HEAD"));
const result = push("main");
expect(result.status).toBe(1);
expect(result.stderr).toContain(`can only push to ${SESSION_BRANCH}`);
expect(remoteHead()).toBe(before);
});
test("HEAD moved onto main still only updates the session branch", () => {
const before = remoteHead();
git("update-ref", "refs/heads/main", git("rev-parse", "HEAD"));
git("symbolic-ref", "HEAD", "refs/heads/main");
expect(push("HEAD").status).toBe(0);
expect(remoteHead()).toBe(before);
expect(remoteBranch(SESSION_BRANCH)).toBe(git("rev-parse", "HEAD"));
});
test.each([
"main",
"other",
"refs/heads/main",
`HEAD:refs/heads/main`,
`${SESSION_BRANCH}:main`,
"HEAD:main",
":main",
`+${SESSION_BRANCH}`,
"+HEAD",
"+main",
"+",
])("rejects %p", (ref) => {
const before = remoteHead();
const result = push(ref);
expect(result.status).toBe(1);
expect(result.stderr).toContain(`can only push to ${SESSION_BRANCH}`);
expect(remoteHead()).toBe(before);
expect(remoteBranch(SESSION_BRANCH)).toBe("");
});
test("rejects flags and other remotes", () => {
expect(push("--force").stderr).toContain("flags are not allowed");
expect(push("HEAD", SESSION_BRANCH, "other").stderr).toContain(
"remote must be 'origin'",
);
});
test.each([null, ""])(
"refuses to push when no session branch is set: %p",
(branch) => {
const result = push("HEAD", branch);
expect(result.status).toBe(1);
expect(result.stderr).toContain("CLAUDE_PUSH_BRANCH is not set");
expect(remoteBranch(SESSION_BRANCH)).toBe("");
},
);
test("a non-fast-forward fails on the remote", () => {
expect(push("HEAD").status).toBe(0);
const before = remoteBranch(SESSION_BRANCH);
git("commit", "-q", "--amend", "--allow-empty", "-m", "rewritten");
expect(push("HEAD").status).not.toBe(0);
expect(remoteBranch(SESSION_BRANCH)).toBe(before);
});
});
});
+1
View File
@@ -246,6 +246,7 @@ describe("prepareMcpConfig", () => {
expect(parsed.mcpServers[name].args).toEqual([
"--no-env-file",
"--config=/test/action/path/bunfig.toml",
"--tsconfig-override=/test/action/path/tsconfig.json",
"run",
`/test/action/path/${script}`,
]);
+8 -8
View File
@@ -55,7 +55,7 @@ export const createMockContext = (
payload: {} as any,
entityNumber: 1,
isPR: false,
inputs: defaultInputs,
inputs: { ...defaultInputs },
};
const mergedInputs = overrides.inputs
@@ -65,7 +65,7 @@ export const createMockContext = (
includeCommentsByActor: overrides.inputs.includeCommentsByActor ?? "",
excludeCommentsByActor: overrides.inputs.excludeCommentsByActor ?? "",
}
: defaultInputs;
: { ...defaultInputs };
return { ...baseContext, ...overrides, inputs: mergedInputs };
};
@@ -84,7 +84,7 @@ export const createMockAutomationContext = (
repository: defaultRepository,
actor: "test-actor",
payload: {} as any,
inputs: defaultInputs,
inputs: { ...defaultInputs },
};
const mergedInputs = overrides.inputs
@@ -123,7 +123,7 @@ export const mockRepositoryDispatchContext: AutomationContext = {
login: "automation-user",
},
} as RepositoryDispatchEvent,
inputs: defaultInputs,
inputs: { ...defaultInputs },
};
export const mockIssueOpenedContext: ParsedGitHubContext = {
@@ -158,7 +158,7 @@ export const mockIssueOpenedContext: ParsedGitHubContext = {
} as IssuesEvent,
entityNumber: 42,
isPR: false,
inputs: defaultInputs,
inputs: { ...defaultInputs },
};
export const mockIssueAssignedContext: ParsedGitHubContext = {
@@ -337,7 +337,7 @@ export const mockPullRequestCommentContext: ParsedGitHubContext = {
} as IssueCommentEvent,
entityNumber: 789,
isPR: true,
inputs: defaultInputs,
inputs: { ...defaultInputs },
};
export const mockPullRequestOpenedContext: ParsedGitHubContext = {
@@ -373,7 +373,7 @@ export const mockPullRequestOpenedContext: ParsedGitHubContext = {
} as PullRequestEvent,
entityNumber: 456,
isPR: true,
inputs: defaultInputs,
inputs: { ...defaultInputs },
};
export const mockPullRequestReviewContext: ParsedGitHubContext = {
@@ -518,5 +518,5 @@ export const mockPullRequestReviewCommentContext: ParsedGitHubContext = {
} as PullRequestReviewCommentEvent,
entityNumber: 999,
isPR: true,
inputs: defaultInputs,
inputs: { ...defaultInputs },
};
+205 -2
View File
@@ -18,7 +18,16 @@ describe("Agent Mode", () => {
let configureGitAuthSpy: any;
let replaceCheckoutCredentialsSpy: any;
const savedBaseUrl = process.env.ANTHROPIC_BASE_URL;
const savedNonWriteUsers = process.env.ALLOWED_NON_WRITE_USERS;
const savedSettings = process.env.INPUT_SETTINGS;
const savedExecutable = process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE;
beforeEach(() => {
delete process.env.ANTHROPIC_BASE_URL;
delete process.env.ALLOWED_NON_WRITE_USERS;
delete process.env.INPUT_SETTINGS;
delete process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE;
exportVariableSpy = spyOn(core, "exportVariable").mockImplementation(
() => {},
);
@@ -37,6 +46,20 @@ describe("Agent Mode", () => {
});
afterEach(() => {
if (savedBaseUrl === undefined) delete process.env.ANTHROPIC_BASE_URL;
else process.env.ANTHROPIC_BASE_URL = savedBaseUrl;
if (savedNonWriteUsers === undefined) {
delete process.env.ALLOWED_NON_WRITE_USERS;
} else {
process.env.ALLOWED_NON_WRITE_USERS = savedNonWriteUsers;
}
if (savedSettings === undefined) delete process.env.INPUT_SETTINGS;
else process.env.INPUT_SETTINGS = savedSettings;
if (savedExecutable === undefined) {
delete process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE;
} else {
process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE = savedExecutable;
}
exportVariableSpy?.mockClear();
setOutputSpy?.mockClear();
configureGitAuthSpy?.mockClear();
@@ -92,7 +115,9 @@ describe("Agent Mode", () => {
});
// Verify claude_args includes user args (no MCP config in agent mode without allowed tools)
expect(result.claudeArgs).toBe("--model claude-sonnet-4 --max-turns 10");
expect(result.claudeArgs).toBe(
"--permission-mode auto --model claude-sonnet-4 --max-turns 10",
);
expect(result.claudeArgs).not.toContain("--mcp-config");
// Verify return structure - should fall back to repository.default_branch when no env vars set
@@ -104,9 +129,35 @@ describe("Agent Mode", () => {
claudeBranch: undefined,
},
mcpConfig: expect.any(String),
claudeArgs: "--model claude-sonnet-4 --max-turns 10",
claudeArgs:
"--permission-mode auto --model claude-sonnet-4 --max-turns 10",
});
// Sessions behind a gateway keep the earlier default of no flag
process.env.ANTHROPIC_BASE_URL = "https://gateway.example.com";
const behindGateway = await prepareAgentMode({
context: contextWithCustomArgs,
octokit: mockOctokit,
githubToken: "test-token",
});
expect(behindGateway.claudeArgs).toBe(
"--model claude-sonnet-4 --max-turns 10",
);
delete process.env.ANTHROPIC_BASE_URL;
// A permission mode in the settings input isn't replaced by the default
process.env.INPUT_SETTINGS = JSON.stringify({
permissions: { defaultMode: "dontAsk" },
});
const withSettingsMode = await prepareAgentMode({
context: contextWithCustomArgs,
octokit: mockOctokit,
githubToken: "test-token",
});
expect(withSettingsMode.claudeArgs).toBe(
"--model claude-sonnet-4 --max-turns 10",
);
// Clean up
delete process.env.CLAUDE_ARGS;
if (originalHeadRef !== undefined)
@@ -169,6 +220,158 @@ describe("Agent Mode", () => {
process.env.GITHUB_REF_NAME = originalRefName;
});
describe("the branch for pull request events", () => {
const originalHeadRef = process.env.GITHUB_HEAD_REF;
const originalClaudeBranch = process.env.CLAUDE_BRANCH;
beforeEach(() => {
process.env.GITHUB_HEAD_REF = "release";
delete process.env.CLAUDE_BRANCH;
});
afterEach(() => {
if (originalHeadRef === undefined) delete process.env.GITHUB_HEAD_REF;
else process.env.GITHUB_HEAD_REF = originalHeadRef;
if (originalClaudeBranch !== undefined) {
process.env.CLAUDE_BRANCH = originalClaudeBranch;
}
});
const branchFor = async (
headRepository: string | null,
overrides: Record<string, unknown> = {},
) => {
const context = {
...createMockAutomationContext({
repository: {
owner: "test-owner",
repo: "test-repo",
full_name: "test-owner/test-repo",
default_branch: "main",
},
}),
eventName: "pull_request",
entityNumber: 5,
isPR: true,
inputs: {
...createMockAutomationContext().inputs,
useCommitSigning: true,
},
payload: {
pull_request: {
number: 5,
head: headRepository
? { ref: "release", repo: { full_name: headRepository } }
: { ref: "release" },
},
},
...overrides,
} as any;
const octokit = {
rest: {
users: {
getAuthenticated: mock(() =>
Promise.resolve({
data: { login: "test-user", id: 1, type: "User" },
}),
),
getByUsername: mock(() =>
Promise.resolve({
data: { login: "test-user", id: 1, type: "User" },
}),
),
},
},
} as any;
const result = await prepareAgentMode({
context,
octokit,
githubToken: "test-token",
});
// The branch commit_files writes to through the API
return JSON.parse(result.mcpConfig).mcpServers.github_file_ops.env
.BRANCH_NAME;
};
test("uses pr-N for a fork, not the fork's branch name", async () => {
expect(await branchFor("attacker/test-repo")).toBe("pr-5");
});
test("uses pr-N when the head repository is unknown", async () => {
expect(await branchFor(null)).toBe("pr-5");
});
test("keeps the branch name for the same repository", async () => {
expect(await branchFor("Test-Owner/test-repo")).toBe("release");
});
test("uses pr-N for a fork's review event", async () => {
expect(
await branchFor("attacker/test-repo", {
eventName: "pull_request_review",
}),
).toBe("pr-5");
});
test("keeps the branch name for a review in the same repository", async () => {
delete process.env.GITHUB_HEAD_REF;
expect(
await branchFor("test-owner/test-repo", {
eventName: "pull_request_review",
}),
).toBe("release");
});
test("uses pr-N for a comment on a PR, not the default branch", async () => {
delete process.env.GITHUB_HEAD_REF;
process.env.GITHUB_REF_NAME = "main";
try {
expect(
await branchFor(null, {
eventName: "issue_comment",
payload: { issue: { number: 5, pull_request: {} } },
}),
).toBe("pr-5");
} finally {
delete process.env.GITHUB_REF_NAME;
}
});
test.each(["issue_comment", "issues"])(
"uses issue-N for %s, not the default branch",
async (eventName) => {
delete process.env.GITHUB_HEAD_REF;
process.env.GITHUB_REF_NAME = "main";
try {
expect(
await branchFor(null, {
eventName,
isPR: false,
payload: { issue: { number: 5 } },
}),
).toBe("issue-5");
} finally {
delete process.env.GITHUB_REF_NAME;
}
},
);
test("a workflow's CLAUDE_BRANCH wins over issue-N", async () => {
process.env.CLAUDE_BRANCH = "prepared";
try {
expect(
await branchFor(null, {
eventName: "issues",
isPR: false,
payload: { issue: { number: 5 } },
}),
).toBe("prepared");
} finally {
delete process.env.CLAUDE_BRANCH;
}
});
});
test("prepare rejects bot actors without allowed_bots", async () => {
const contextWithPrompts = createMockAutomationContext({
eventName: "workflow_dispatch",
+3 -3
View File
@@ -171,7 +171,7 @@ describe("detectMode with enhanced routing", () => {
eventName: "issue_comment",
payload: {
issue: { number: 1, body: "Test" },
comment: { body: "@claude help" },
comment: { body: "@claude help", user: { login: "test-user" } },
} as any,
entityNumber: 1,
isPR: false,
@@ -186,7 +186,7 @@ describe("detectMode with enhanced routing", () => {
eventName: "issue_comment",
payload: {
issue: { number: 1, body: "Test" },
comment: { body: "@claude help" },
comment: { body: "@claude help", user: { login: "test-user" } },
} as any,
entityNumber: 1,
isPR: false,
@@ -202,7 +202,7 @@ describe("detectMode with enhanced routing", () => {
eventName: "pull_request_review_comment",
payload: {
pull_request: { number: 1, body: "Test" },
comment: { body: "@claude check this" },
comment: { body: "@claude check this", user: { login: "test-user" } },
} as any,
entityNumber: 1,
isPR: true,
+100 -1
View File
@@ -1,7 +1,106 @@
import { describe, test, expect } from "bun:test";
import { parseAllowedTools } from "../../src/modes/agent/parse-tools";
import {
deniesCommand,
wrapperDenyRules,
parseAllowedTools,
parseDeniedBashPatterns,
} from "../../src/modes/agent/parse-tools";
describe("parseDeniedBashPatterns", () => {
test.each([
[`--disallowedTools "Bash(git commit:*)"`, ["git commit:*"]],
[`--disallowed-tools "Bash(git commit:*)"`, ["git commit:*"]],
[`--disallowedTools Bash(git:*)`, ["git:*"]],
[`--disallowedTools="Bash(git commit:*)"`, ["git commit:*"]],
[`--disallowedTools "Bash(a:*),WebFetch,Bash(b:*)"`, ["a:*", "b:*"]],
[`--disallowedTools "Bash(a:*) Bash(b:*)"`, ["a:*", "b:*"]],
[`--disallowedTools "Bash(a:*)" "Bash(b:*)"`, ["a:*", "b:*"]],
[`--disallowedTools Bash(a:*) --disallowedTools Bash(b:*)`, ["a:*", "b:*"]],
[`--allowedTools "Bash(git commit:*)"`, []],
[`# --disallowedTools "Bash(git commit:*)"`, []],
["", []],
])("reads %s", (args, expected) => {
expect(parseDeniedBashPatterns(args as string)).toEqual(
expected as string[],
);
});
test.each([
[`'Bash(git add "app/(auth)/*")'`, `git add "app/(auth)/*"`],
[`'Bash(a:*) Bash(git add "(x)/*"),Bash(b:*)'`, `git add "(x)/*"`],
[`'Bash(git add {a,b}/*)'`, "git add {a,b}/*"],
[`"Read(x(" "Bash(a b:*)"`, "a b:*"],
[`"Bash(a:*)\nBash(b c:*)"`, "b c:*"],
[`"Bash(a:*),\nBash(git add \\"(x)/*\\")"`, `git add "(x)/*"`],
[`"Bash(git add {a" "b}/*)"`, "git add {a\0b}/*"],
[`"Bash(a:*);Read(x)"`, "a:*"],
[`"Bash(a:*))"`, "a:*"],
])("finds the rule in %s", (rules, expected) => {
expect(parseDeniedBashPatterns(`--disallowedTools ${rules}`)).toContain(
expected,
);
});
});
describe("deniesCommand", () => {
test.each([
"git commit:*",
"git commit *",
"git commit*",
"git comm*",
"gi*",
"*git commit*",
"git:*",
"git *",
"*",
])("%p covers git commit", (pattern) => {
expect(deniesCommand([pattern], "git commit")).toBe(true);
});
test.each([
"git commit --amend:*",
"git commit x:*",
"git commit x*",
"git committed:*",
"git commit",
"git push:*",
"gi:*",
"git.commit:*",
"",
])("%p doesn't cover git commit", (pattern) => {
expect(deniesCommand([pattern], "git commit")).toBe(false);
});
});
describe("wrapperDenyRules", () => {
const rules = (...patterns: string[]) =>
wrapperDenyRules(patterns, "git add", "/a/git-add.sh");
test("denies the whole wrapper for a rule that covers every use", () => {
expect(rules("git add:*")).toEqual(["Bash(/a/git-add.sh:*)"]);
expect(rules("git:*", "git add -A:*")).toEqual(["Bash(/a/git-add.sh:*)"]);
});
test("keeps the arguments of a narrower rule", () => {
expect(rules("git add -A:*", "git add .")).toEqual([
"Bash(/a/git-add.sh -A:*)",
"Bash(/a/git-add.sh .)",
]);
});
test("ignores rules for other commands", () => {
expect(rules("git push:*", "git addendum:*", "")).toEqual([]);
});
});
describe("parseAllowedTools", () => {
test("keeps unquoted Bash rules whole", () => {
expect(parseAllowedTools("--allowedTools Bash(gh:*),Read")).toEqual([
"Bash(gh:*)",
"Read",
]);
});
test("parses unquoted tools", () => {
const args = "--allowedTools mcp__github__*,mcp__github_comment__*";
expect(parseAllowedTools(args)).toEqual([
+122
View File
@@ -0,0 +1,122 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { defaultsToAutoMode } from "../../src/modes/permission-mode";
describe("defaultsToAutoMode", () => {
const saved = process.env.ANTHROPIC_BASE_URL;
const savedNonWriteUsers = process.env.ALLOWED_NON_WRITE_USERS;
const savedSettings = process.env.INPUT_SETTINGS;
const savedBots = process.env.ALLOWED_BOTS;
const savedExecutable = process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE;
beforeEach(() => {
delete process.env.ANTHROPIC_BASE_URL;
delete process.env.ALLOWED_NON_WRITE_USERS;
delete process.env.INPUT_SETTINGS;
delete process.env.ALLOWED_BOTS;
delete process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE;
});
afterEach(() => {
if (saved === undefined) delete process.env.ANTHROPIC_BASE_URL;
else process.env.ANTHROPIC_BASE_URL = saved;
if (savedNonWriteUsers === undefined) {
delete process.env.ALLOWED_NON_WRITE_USERS;
} else {
process.env.ALLOWED_NON_WRITE_USERS = savedNonWriteUsers;
}
if (savedSettings === undefined) delete process.env.INPUT_SETTINGS;
else process.env.INPUT_SETTINGS = savedSettings;
if (savedBots === undefined) delete process.env.ALLOWED_BOTS;
else process.env.ALLOWED_BOTS = savedBots;
if (savedExecutable === undefined) {
delete process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE;
} else {
process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE = savedExecutable;
}
});
describe("settings input", () => {
const useSettings = (settings: unknown) => {
process.env.INPUT_SETTINGS = JSON.stringify(settings);
};
test("is on when settings set neither a mode nor a base URL", () => {
useSettings({ model: "x", env: { OTHER: "1" }, permissions: {} });
expect(defaultsToAutoMode()).toBe(true);
});
test("is off when settings choose another permission mode", () => {
useSettings({ permissions: { defaultMode: "dontAsk" } });
expect(defaultsToAutoMode()).toBe(false);
});
test("stays on when settings choose auto mode", () => {
useSettings({ permissions: { defaultMode: "auto" } });
expect(defaultsToAutoMode()).toBe(true);
});
test("is off when settings set a base URL", () => {
useSettings({ env: { ANTHROPIC_BASE_URL: "https://gw.example.com" } });
expect(defaultsToAutoMode()).toBe(false);
});
test("ignores a blank base URL in settings", () => {
useSettings({ env: { ANTHROPIC_BASE_URL: " " } });
expect(defaultsToAutoMode()).toBe(true);
});
test("is off for a settings file, whatever it holds", () => {
process.env.INPUT_SETTINGS = "/no/such/settings.json";
expect(defaultsToAutoMode()).toBe(false);
});
test("doesn't throw on settings JSON that isn't an object", () => {
process.env.INPUT_SETTINGS = "null";
expect(defaultsToAutoMode()).toBe(true);
});
});
test("is on with no custom base URL", () => {
expect(defaultsToAutoMode()).toBe(true);
});
test("treats the empty value action.yml passes as no base URL", () => {
process.env.ANTHROPIC_BASE_URL = " ";
expect(defaultsToAutoMode()).toBe(true);
});
test("is off when non-write users are allowed", () => {
process.env.ALLOWED_NON_WRITE_USERS = "*";
expect(defaultsToAutoMode()).toBe(false);
});
test("is off when bots are allowed", () => {
process.env.ALLOWED_BOTS = "sentry[bot]";
expect(defaultsToAutoMode()).toBe(false);
});
test("treats the empty value action.yml passes as no allowed bots", () => {
process.env.ALLOWED_BOTS = "";
expect(defaultsToAutoMode()).toBe(true);
});
test("treats the empty value action.yml passes as no allowed users", () => {
process.env.ALLOWED_NON_WRITE_USERS = "";
expect(defaultsToAutoMode()).toBe(true);
});
test("is off with a custom Claude Code executable", () => {
process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE = "/opt/claude";
expect(defaultsToAutoMode()).toBe(false);
});
test("treats the empty value action.yml passes as no custom executable", () => {
process.env.PATH_TO_CLAUDE_CODE_EXECUTABLE = "";
expect(defaultsToAutoMode()).toBe(true);
});
test("is off behind a custom base URL", () => {
process.env.ANTHROPIC_BASE_URL = "https://gateway.example.com";
expect(defaultsToAutoMode()).toBe(false);
});
});
+130
View File
@@ -1,3 +1,4 @@
import { parseDeniedBashPatterns } from "../../src/modes/agent/parse-tools";
import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
import { prepareTagMode } from "../../src/modes/tag";
import { mockIssueCommentContext } from "../mockContext";
@@ -8,6 +9,10 @@ import * as branch from "../../src/github/operations/branch";
import * as createPrompt from "../../src/create-prompt";
import * as mcp from "../../src/mcp/install-mcp-server";
import * as gitConfig from "../../src/github/operations/git-config";
import { mkdtempSync, readFileSync, rmSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import * as sessionGuard from "../../src/github/operations/session-guard";
describe("Tag Mode", () => {
test("prepareTagMode is exported as a function", () => {
@@ -76,6 +81,131 @@ describe("Tag Mode", () => {
expect(replaceCheckoutCredentialsSpy).not.toHaveBeenCalled();
});
describe("push branch", () => {
const savedPath = process.env.GITHUB_ACTION_PATH;
let actionPath: string;
const pinned = () =>
readFileSync(join(actionPath, "scripts/.push-branch"), "utf8");
beforeEach(() => {
actionPath = mkdtempSync(join(tmpdir(), "tag-action-"));
process.env.GITHUB_ACTION_PATH = actionPath;
});
afterEach(() => {
rmSync(actionPath, { recursive: true, force: true });
if (savedPath === undefined) delete process.env.GITHUB_ACTION_PATH;
else process.env.GITHUB_ACTION_PATH = savedPath;
});
test("pins the push wrapper to a new claude branch", async () => {
await prepareTagMode({
context: { ...mockIssueCommentContext },
octokit: {} as any,
githubToken: "test-token",
});
expect(pinned()).toBe("claude/test");
expect(process.env.CLAUDE_PUSH_BRANCH).toBeUndefined();
});
test("pins the push wrapper to the branch of an open PR", async () => {
spies.push(
spyOn(branch, "setupBranch").mockImplementation(
async () =>
({ baseBranch: "main", currentBranch: "feature" }) as any,
),
);
await prepareTagMode({
context: { ...mockIssueCommentContext },
octokit: {} as any,
githubToken: "test-token",
});
expect(pinned()).toBe("feature");
});
});
describe("a workflow's deny rules", () => {
const savedArgs = process.env.CLAUDE_ARGS;
const savedPath = process.env.GITHUB_ACTION_PATH;
beforeEach(() => {
process.env.GITHUB_ACTION_PATH = "/action";
spies.push(
spyOn(sessionGuard, "pinPushBranch").mockImplementation(() => {}),
);
});
afterEach(() => {
if (savedArgs === undefined) delete process.env.CLAUDE_ARGS;
else process.env.CLAUDE_ARGS = savedArgs;
if (savedPath === undefined) delete process.env.GITHUB_ACTION_PATH;
else process.env.GITHUB_ACTION_PATH = savedPath;
});
const prepare = async (userArgs: string) => {
process.env.CLAUDE_ARGS = userArgs;
const { claudeArgs } = await prepareTagMode({
context: { ...mockIssueCommentContext },
octokit: {} as any,
githubToken: "test-token",
});
return claudeArgs;
};
test.each([
["git add", "git-add.sh"],
["git rm", "git-rm.sh"],
])("a deny of %s also denies its wrapper", async (command, wrapper) => {
expect(
await prepare(`--disallowedTools "Bash(${command}:*)"`),
).toContain(`--disallowedTools 'Bash(/action/scripts/${wrapper}:*)'`);
});
test("a deny of git commit also denies the commit wrapper", async () => {
expect(
await prepare(`--disallowedTools "Bash(git commit:*)"`),
).toContain(
`--disallowedTools 'Bash(/action/scripts/git-commit.sh:*)'`,
);
});
test.each([
`--disallowedTools Bash(git:*)`,
`--disallowedTools="Bash(git commit:*)"`,
`--disallowedTools "Bash(git comm*)"`,
])("carries over %s", async (args) => {
expect(await prepare(args)).toContain(
`--disallowedTools 'Bash(/action/scripts/git-commit.sh:*)`,
);
});
test("a deny of git push also denies the push wrapper", async () => {
expect(await prepare(`--disallowedTools "Bash(git push:*)"`)).toContain(
`--disallowedTools 'Bash(/action/scripts/git-push.sh:*)'`,
);
});
test("adds no deny rule of its own otherwise", async () => {
const args = await prepare(`--disallowedTools "Bash(git add -A:*)"`);
expect(args).toContain(
`--disallowedTools 'Bash(/action/scripts/git-add.sh -A:*)'`,
);
for (const rest of [`"a b"`, "it's", "$HOME/x", `"(a)/x"`]) {
const denied = await prepare(
`--disallowedTools 'Bash(git add ${rest.replace(/'/g, "'\\''")}:*)'`,
);
expect(parseDeniedBashPatterns(denied)).toContain(
`/action/scripts/git-add.sh ${rest}:*`,
);
}
expect(await prepare(`--disallowedTools "WebFetch"`)).not.toContain(
`--disallowedTools 'Bash(`,
);
expect(await prepare("")).not.toContain("--disallowedTools");
});
});
test("still replaces the checkout credential when API commit signing is enabled", async () => {
const context = {
...mockIssueCommentContext,
+132 -2
View File
@@ -1,6 +1,9 @@
import { describe, expect, test, spyOn, beforeEach, afterEach } from "bun:test";
import * as core from "@actions/core";
import { checkWritePermissions } from "../src/github/validation/permissions";
import {
checkBotActorPullRequestAuthor,
checkWritePermissions,
} from "../src/github/validation/permissions";
import type { ParsedGitHubContext } from "../src/github/context";
import { CLAUDE_APP_BOT_ID, CLAUDE_BOT_LOGIN } from "../src/github/constants";
import { createMockAutomationContext } from "./mockContext";
@@ -457,10 +460,105 @@ describe("checkWritePermissions", () => {
});
});
describe("pull requests a bot acted on", () => {
const createBotContext = (author: string | null, allowedBots = "") => ({
...createContext(),
eventName: "pull_request" as const,
actor: "dependabot[bot]",
inputs: { ...createContext().inputs, allowedBots },
payload: {
pull_request: { number: 1, user: author ? { login: author } : null },
} as any,
});
test("should return false when the pull request's author lacks write access", async () => {
expect(
await checkBotActorPullRequestAuthor(
createMockOctokit("read"),
createBotContext("outsider", "dependabot[bot]"),
),
).toBe(false);
});
test("should return true when the pull request's author has write access", async () => {
expect(
await checkBotActorPullRequestAuthor(
createMockOctokit("write"),
createBotContext("maintainer", "dependabot[bot]"),
),
).toBe(true);
});
test("should return true for a pull request from an allowed bot", async () => {
expect(
await checkBotActorPullRequestAuthor(
createMockOctokit("none"),
createBotContext("dependabot[bot]", "dependabot[bot]"),
),
).toBe(true);
});
test("should return false for a pull request from a bot that is not allowed", async () => {
expect(
await checkBotActorPullRequestAuthor(
createMockOctokit("none"),
createBotContext("other-app[bot]", "dependabot[bot]"),
),
).toBe(false);
});
test("should leave a bot's own pull request to the allowed bots check", async () => {
expect(
await checkBotActorPullRequestAuthor(
createMockOctokit("none"),
createBotContext("dependabot[bot]"),
),
).toBe(true);
});
test("should not stop a bot activity at the first permission check", async () => {
expect(
await checkWritePermissions(
createMockOctokit("read"),
createBotContext("outsider"),
),
).toBe(true);
});
test("should return false when the author is missing", async () => {
expect(
await checkBotActorPullRequestAuthor(
createMockOctokit("write"),
createBotContext(null, "dependabot[bot]"),
),
).toBe(false);
});
test("should not check the author when a person triggered the run", async () => {
const context = {
...createBotContext("outsider"),
actor: "maintainer",
};
const levels: Record<string, string> = {
maintainer: "write",
outsider: "read",
};
const octokit = {
repos: {
getCollaboratorPermissionLevel: async (params: {
username: string;
}) => ({ data: { permission: levels[params.username] } }),
},
} as any;
expect(await checkBotActorPullRequestAuthor(octokit, context)).toBe(true);
});
});
describe("workflow_run contexts", () => {
const createWorkflowRunContext = (
actor: string,
runActor: string = actor,
headRepository: unknown = { full_name: "test-owner/test-repo" },
) =>
createMockAutomationContext({
eventName: "workflow_run",
@@ -472,7 +570,7 @@ describe("checkWritePermissions", () => {
id: 123,
event: "pull_request",
actor: { login: runActor },
head_repository: { full_name: "fork-owner/test-repo" },
head_repository: headRepository,
},
} as any,
});
@@ -488,6 +586,38 @@ describe("checkWritePermissions", () => {
},
}) as any;
test("should return false when a fork's owner lacks write access, whoever triggered the run", async () => {
const context = createWorkflowRunContext("maintainer", "maintainer", {
full_name: "fork-owner/test-repo",
});
const octokit = createMockOctokitWithLevels({
maintainer: "write",
"fork-owner": "read",
});
expect(await checkWritePermissions(octokit, context)).toBe(false);
});
test("should return true when a fork's owner has write access", async () => {
const context = createWorkflowRunContext("maintainer", "maintainer", {
full_name: "Maintainer/test-repo",
});
const octokit = createMockOctokitWithLevels({
maintainer: "write",
Maintainer: "write",
});
expect(await checkWritePermissions(octokit, context)).toBe(true);
});
test("should return false when the run's repository is unknown", async () => {
const context = createWorkflowRunContext(
"maintainer",
"maintainer",
null,
);
const octokit = createMockOctokitWithLevels({ maintainer: "write" });
expect(await checkWritePermissions(octokit, context)).toBe(false);
});
test("should return false when the run actor lacks write access", async () => {
const mockOctokit = createMockOctokit("read");
const context = createWorkflowRunContext("fork-contributor");
+29
View File
@@ -148,6 +148,35 @@ describe("restoreConfigFromBase", () => {
);
});
test("removes an AGENTS.md that only the PR has", () => {
writeRepoFile("AGENTS.md", "pr agent instructions\n");
git(["add", "AGENTS.md"]);
git(["commit", "-m", "pr adds agents file"]);
const restored = restoreConfigFromBase("main");
expect(restored).toContain("AGENTS.md");
expect(existsRepoFile("AGENTS.md")).toBe(false);
expect(readRepoFile(".claude-pr/AGENTS.md")).toBe(
"pr agent instructions\n",
);
});
test("uses the base branch's AGENTS.md, also through a CLAUDE.md link", () => {
setupSymlinkedMainBranch();
writeRepoFile("AGENTS.md", "pr agent instructions\n");
git(["commit", "-am", "pr edits agents file"]);
restoreConfigFromBase("main");
expect(readRepoFile("AGENTS.md")).toBe("shared agent instructions\n");
expect(readRepoFile("CLAUDE.md")).toBe("shared agent instructions\n");
expect(readRepoFile(".claude-pr/AGENTS.md")).toBe(
"pr agent instructions\n",
);
expect(git(["diff", "--cached", "--name-only"])).toBe("");
});
test("records dangling links as placeholders, including top-level ones", () => {
setupSymlinkedMainBranch();
+460
View File
@@ -0,0 +1,460 @@
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,
realpathSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from "fs";
import { tmpdir } from "os";
import { join } from "path";
import {
clearSessionState,
disableGitPrograms,
pinPushBranch,
prepareGitForSession,
snapshotSessionFiles,
} from "../src/github/operations/session-guard";
const KEYS = [
"GITHUB_ACTION_PATH",
"GITHUB_ENV",
"GITHUB_PATH",
"HOME",
"XDG_CONFIG_HOME",
"GIT_CONFIG_GLOBAL",
"GIT_CONFIG_COUNT",
"GIT_CONFIG_KEY_0",
"GIT_CONFIG_VALUE_0",
"GIT_CONFIG_KEY_1",
"GIT_CONFIG_VALUE_1",
"GIT_CONFIG_KEY_2",
"GIT_CONFIG_VALUE_2",
// 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",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_COMMON_DIR",
"GIT_PREFIX",
];
// A child process doesn't see deletions from process.env unless env is passed.
const git = (...args: string[]) =>
execFileSync("git", args, { encoding: "utf8", env: { ...process.env } });
describe("session guard", () => {
let dir: string;
let cwd: string;
let warningSpy: any;
let saved: Record<string, string | undefined>;
const warnings = (): string[] =>
warningSpy.mock.calls.map((call: any[]) => call[0]);
beforeEach(() => {
saved = Object.fromEntries(KEYS.map((key) => [key, process.env[key]]));
KEYS.forEach((key) => delete process.env[key]);
dir = mkdtempSync(join(tmpdir(), "session-guard-"));
cwd = process.cwd();
mkdirSync(join(dir, "home"));
mkdirSync(join(dir, "repo"));
git("init", "-q", join(dir, "repo"));
process.chdir(join(dir, "repo"));
process.env.HOME = join(dir, "home");
process.env.GITHUB_ENV = join(dir, "set_env");
process.env.GITHUB_PATH = join(dir, "add_path");
writeFileSync(process.env.GITHUB_ENV, "SET_BY_ACTION=1\n");
writeFileSync(process.env.GITHUB_PATH, "/opt/tool\n");
warningSpy = spyOn(core, "warning").mockImplementation(() => {});
});
afterEach(() => {
warningSpy.mockRestore();
process.chdir(cwd);
rmSync(dir, { recursive: true, force: true });
for (const key of KEYS) {
if (saved[key] === undefined) delete process.env[key];
else process.env[key] = saved[key];
}
});
test("leaves unchanged files alone and logs nothing", () => {
snapshotSessionFiles()();
expect(readFileSync(process.env.GITHUB_ENV!, "utf8")).toBe(
"SET_BY_ACTION=1\n",
);
expect(warnings()).toEqual([]);
});
test("undoes lines a session added to GITHUB_ENV and GITHUB_PATH", () => {
const restore = snapshotSessionFiles();
writeFileSync(process.env.GITHUB_ENV!, "SET_BY_ACTION=1\nHOME=/tmp/x\n");
writeFileSync(process.env.GITHUB_PATH!, "/opt/tool\n/tmp/shims\n");
restore();
expect(readFileSync(process.env.GITHUB_ENV!, "utf8")).toBe(
"SET_BY_ACTION=1\n",
);
expect(readFileSync(process.env.GITHUB_PATH!, "utf8")).toBe("/opt/tool\n");
expect(warnings()[0]).toContain("GITHUB_ENV, GITHUB_PATH");
});
test("undoes changes to the repository's git config", () => {
const configPath = join(dir, "repo", ".git", "config");
const before = readFileSync(configPath, "utf8");
const restore = snapshotSessionFiles();
git("config", "core.fsmonitor", "/tmp/payload");
restore();
expect(readFileSync(configPath, "utf8")).toBe(before);
expect(warnings()[0]).toContain(".git/config");
});
test("removes global git config files a session created", () => {
const xdg = join(dir, "home", ".config", "git");
const restore = snapshotSessionFiles();
writeFileSync(join(dir, "home", ".gitconfig"), "[core]\n");
mkdirSync(xdg, { recursive: true });
writeFileSync(join(xdg, "config"), "[core]\n");
restore();
expect(existsSync(join(dir, "home", ".gitconfig"))).toBe(false);
expect(existsSync(join(xdg, "config"))).toBe(false);
});
test("replaces a symlink a session swapped in, without writing through it", () => {
const outside = join(dir, "outside");
writeFileSync(outside, "untouched\n");
const restore = snapshotSessionFiles();
rmSync(process.env.GITHUB_ENV!);
symlinkSync(outside, process.env.GITHUB_ENV!);
restore();
expect(lstatSync(process.env.GITHUB_ENV!).isSymbolicLink()).toBe(false);
expect(readFileSync(process.env.GITHUB_ENV!, "utf8")).toBe(
"SET_BY_ACTION=1\n",
);
expect(readFileSync(outside, "utf8")).toBe("untouched\n");
});
test("restores a file a session deleted, with its mode", () => {
const path = process.env.GITHUB_PATH!;
execFileSync("chmod", ["640", path]);
const restore = snapshotSessionFiles();
rmSync(path);
restore();
expect(readFileSync(path, "utf8")).toBe("/opt/tool\n");
expect(statSync(path).mode & 0o777).toBe(0o640);
});
describe("a config that was already a symlink", () => {
let target: string;
let link: string;
let outside: string;
beforeEach(() => {
target = join(dir, "real-gitconfig");
writeFileSync(target, "[user]\n");
execFileSync("chmod", ["600", target]);
link = join(dir, "home", ".gitconfig");
symlinkSync(target, link);
outside = join(dir, "outside");
writeFileSync(outside, "untouched\n");
});
test("keeps the link and restores the file it points to", () => {
const restore = snapshotSessionFiles();
writeFileSync(target, "[core]\n");
restore();
expect(lstatSync(link).isSymbolicLink()).toBe(true);
expect(readFileSync(target, "utf8")).toBe("[user]\n");
expect(statSync(link).mode & 0o777).toBe(0o600);
});
test("replaces the link if a session re-pointed it", () => {
const restore = snapshotSessionFiles();
rmSync(link);
symlinkSync(outside, link);
restore();
expect(lstatSync(link).isSymbolicLink()).toBe(false);
expect(readFileSync(link, "utf8")).toBe("[user]\n");
expect(readFileSync(outside, "utf8")).toBe("untouched\n");
});
test("doesn't write through a symlink swapped in for the file it points to", () => {
const restore = snapshotSessionFiles();
rmSync(target);
symlinkSync(outside, target);
restore();
expect(lstatSync(link).isSymbolicLink()).toBe(false);
expect(readFileSync(link, "utf8")).toBe("[user]\n");
expect(readFileSync(outside, "utf8")).toBe("untouched\n");
});
test("replaces the link if a session deleted the file it points to", () => {
const restore = snapshotSessionFiles();
rmSync(target);
restore();
expect(lstatSync(link).isSymbolicLink()).toBe(false);
expect(readFileSync(link, "utf8")).toBe("[user]\n");
});
});
describe("git settings during the session", () => {
const local = (key: string) => {
try {
return git("config", "--local", key).trim();
} catch {
return "";
}
};
beforeEach(() => {
git("init", "-q", join(dir, "repo"));
process.chdir(join(dir, "repo"));
});
test("moves the action's settings from the environment to the repository", () => {
disableGitPrograms({ hooks: true });
expect(process.env.GIT_CONFIG_COUNT).toBe("2");
const restore = snapshotSessionFiles(() =>
prepareGitForSession({ hooks: true }),
);
expect(process.env.GIT_CONFIG_COUNT).toBeUndefined();
expect(process.env.GIT_CONFIG_KEY_0).toBeUndefined();
expect(process.env.GIT_CONFIG_VALUE_1).toBeUndefined();
expect(local("core.fsmonitor")).toBe("false");
expect(local("core.hooksPath")).toBe("/dev/null");
restore();
expect(local("core.fsmonitor")).toBe("");
expect(local("core.hooksPath")).toBe("");
expect(warnings()).toEqual([]);
});
const globalConfig = (key: string) => {
try {
return git("config", "--global", "--get", key).trim();
} catch {
return "";
}
};
test("refuses repositories in plain folders, and puts that back", () => {
const restore = snapshotSessionFiles(() =>
prepareGitForSession({ hooks: true }),
);
expect(globalConfig("safe.bareRepository")).toBe("explicit");
expect(globalConfig("core.hooksPath")).toBe("");
restore();
expect(globalConfig("safe.bareRepository")).toBe("");
expect(warnings()).toEqual([]);
});
test("restores a global config file named by GIT_CONFIG_GLOBAL", () => {
process.env.GIT_CONFIG_GLOBAL = join(dir, "global-config");
const restore = snapshotSessionFiles(() =>
prepareGitForSession({ hooks: false }),
);
expect(readFileSync(process.env.GIT_CONFIG_GLOBAL, "utf8")).toContain(
"explicit",
);
restore();
expect(existsSync(process.env.GIT_CONFIG_GLOBAL)).toBe(false);
});
test("outside a repository, still refuses them and records the hook setting", () => {
process.env.GITHUB_ACTION_PATH = dir;
const outside = join(dir, "outside");
mkdirSync(outside);
process.chdir(outside);
prepareGitForSession({ hooks: true });
expect(globalConfig("safe.bareRepository")).toBe("explicit");
expect(existsSync(join(dir, "scripts/.no-hooks"))).toBe(true);
expect(existsSync(join(dir, "scripts/.git-repo"))).toBe(false);
});
test("sets repository config in a bare working directory", () => {
const bare = join(dir, "bare.git");
git("init", "-q", "--bare", bare);
process.chdir(bare);
prepareGitForSession({ hooks: false });
expect(warnings()).toEqual([]);
expect(readFileSync(join(bare, "config"), "utf8")).toContain("fsmonitor");
});
test("keeps a workflow's own entries in the environment", () => {
process.env.GIT_CONFIG_COUNT = "1";
process.env.GIT_CONFIG_KEY_0 = "user.name";
process.env.GIT_CONFIG_VALUE_0 = "someone";
disableGitPrograms({ hooks: false });
prepareGitForSession({ hooks: false });
expect(process.env.GIT_CONFIG_COUNT).toBe("1");
expect(process.env.GIT_CONFIG_VALUE_0).toBe("someone");
expect(process.env.GIT_CONFIG_KEY_1).toBeUndefined();
});
test("leaves hooks on unless asked", () => {
disableGitPrograms({ hooks: false });
prepareGitForSession({ hooks: false });
expect(local("core.hooksPath")).toBe("");
expect(local("core.fsmonitor")).toBe("false");
});
test("a session's own change is still reported", () => {
const restore = snapshotSessionFiles(() =>
prepareGitForSession({ hooks: false }),
);
git("config", "--local", "core.fsmonitor", "evil");
restore();
expect(local("core.fsmonitor")).toBe("");
expect(warnings().join(" ")).toContain("restored");
});
test("records and clears what the wrappers read", () => {
process.env.GITHUB_ACTION_PATH = dir;
pinPushBranch("claude/x");
prepareGitForSession({ hooks: true });
expect(readFileSync(join(dir, "scripts/.push-branch"), "utf8")).toBe(
"claude/x",
);
expect(existsSync(join(dir, "scripts/.no-hooks"))).toBe(true);
pinPushBranch("claude/y");
expect(readFileSync(join(dir, "scripts/.push-branch"), "utf8")).toBe(
"claude/y",
);
const repoFile = join(dir, "scripts/.git-repo");
const repoRoot = realpathSync(join(dir, "repo"));
expect(readFileSync(repoFile, "utf8")).toBe(
`${repoRoot}/.git\n${repoRoot}\n${process.env.HOME}\n`,
);
clearSessionState();
expect(existsSync(join(dir, "scripts/.push-branch"))).toBe(false);
expect(existsSync(join(dir, "scripts/.no-hooks"))).toBe(false);
expect(existsSync(repoFile)).toBe(false);
});
test("clearing also removes a directory left in a file's place", () => {
process.env.GITHUB_ACTION_PATH = dir;
mkdirSync(join(dir, "scripts/.no-hooks"), { recursive: true });
expect(() => clearSessionState()).not.toThrow();
expect(existsSync(join(dir, "scripts/.no-hooks"))).toBe(false);
});
test("leaves a workflow's entries alone if nothing was added", () => {
process.env.GIT_CONFIG_COUNT = "1";
process.env.GIT_CONFIG_KEY_0 = "user.name";
process.env.GIT_CONFIG_VALUE_0 = "someone";
prepareGitForSession({ hooks: false });
expect(process.env.GIT_CONFIG_COUNT).toBe("1");
expect(process.env.GIT_CONFIG_VALUE_0).toBe("someone");
});
test("warns if it can't set the repository's config", () => {
writeFileSync(join(dir, "repo/.git/config.lock"), "");
prepareGitForSession({ hooks: false });
expect(warnings().join(" ")).toContain("Could not set core.fsmonitor");
});
});
test("replaces a directory a session put in a file's place", () => {
const path = process.env.GITHUB_ENV!;
const restore = snapshotSessionFiles();
rmSync(path);
mkdirSync(path);
restore();
expect(readFileSync(path, "utf8")).toBe("SET_BY_ACTION=1\n");
});
test("does not hang on a FIFO at a tracked path, and removes it", () => {
const fifo = join(dir, "repo", ".git", "config.worktree");
const restore = snapshotSessionFiles();
execFileSync("mkfifo", [fifo]);
writeFileSync(process.env.GITHUB_ENV!, "HOME=/tmp/x\n");
restore();
expect(existsSync(fifo)).toBe(false);
expect(readFileSync(process.env.GITHUB_ENV!, "utf8")).toBe(
"SET_BY_ACTION=1\n",
);
});
test("removes a directory planted at a path that was absent", () => {
const planted = join(dir, "home", ".gitconfig");
const restore = snapshotSessionFiles();
mkdirSync(join(planted, "nested"), { recursive: true });
restore();
expect(existsSync(planted)).toBe(false);
});
test("restores a config file pulled in through include.path", () => {
const included = join(dir, "included.cfg");
writeFileSync(included, "[user]\n\tname = x\n");
git("config", "--add", "include.path", included);
const restore = snapshotSessionFiles();
writeFileSync(included, "[core]\n\tfsmonitor = /tmp/payload\n");
restore();
expect(readFileSync(included, "utf8")).toBe("[user]\n\tname = x\n");
expect(warnings()[0]).toContain("a git config file");
expect(warnings()[0]).not.toContain(included);
});
test("leaves a file alone when it was not regular before", () => {
const path = process.env.GITHUB_PATH!;
rmSync(path);
mkdirSync(path);
const restore = snapshotSessionFiles();
rmSync(path, { recursive: true });
writeFileSync(path, "/tmp/shims\n");
restore();
expect(warnings()[0]).toContain("Could not restore GITHUB_PATH");
});
test("never logs the content of a file", () => {
const restore = snapshotSessionFiles();
writeFileSync(process.env.GITHUB_ENV!, "TOKEN=not-a-real-secret\n");
restore();
expect(warnings().join("\n")).not.toContain("not-a-real-secret");
});
test("works outside a git repository", () => {
process.chdir(dir);
expect(() => snapshotSessionFiles()()).not.toThrow();
});
test("makes git ignore fsmonitor and, when asked, hooks", () => {
disableGitPrograms({ hooks: true });
git("config", "core.fsmonitor", "/tmp/payload");
git("config", "core.hooksPath", "hooks");
const read = (key: string) => git("config", key).trim();
expect(read("core.fsmonitor")).toBe("false");
expect(read("core.hooksPath")).toBe("/dev/null");
});
test("leaves hooks alone when not asked", () => {
disableGitPrograms({ hooks: false });
expect(process.env.GIT_CONFIG_COUNT).toBe("1");
expect(process.env.GIT_CONFIG_KEY_0).toBe("core.fsmonitor");
});
test("does not add a setting twice", () => {
disableGitPrograms({ hooks: true });
disableGitPrograms({ hooks: true });
expect(process.env.GIT_CONFIG_COUNT).toBe("2");
});
test("keeps existing GIT_CONFIG entries", () => {
process.env.GIT_CONFIG_COUNT = "1";
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_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");
});
});
@@ -0,0 +1,72 @@
import { describe, expect, test } from "bun:test";
import { Glob, YAML } from "bun";
import { readFileSync } from "node:fs";
import { join } from "node:path";
const root = join(import.meta.dir, "..");
function scan(pattern: string): string[] {
return [...new Glob(pattern).scanSync({ cwd: root, dot: true })].sort();
}
function yamlFences(markdown: string): string[] {
return [...markdown.matchAll(/^```ya?ml\n([\s\S]*?)^```/gm)].map(
(match) => match[1]!,
);
}
function runScripts(node: unknown): string[] {
if (Array.isArray(node)) return node.flatMap(runScripts);
if (node === null || typeof node !== "object") return [];
return Object.entries(node).flatMap(([key, value]) =>
key === "run" && typeof value === "string" ? [value] : runScripts(value),
);
}
// GitHub puts a ${{ }} value into the script before the shell reads it, so
// Claude's answer must reach a script through env instead.
function unsafeScripts(yaml: string): string[] {
return runScripts(YAML.parse(yaml)).filter((script) =>
/\$\{\{(?:(?!\}\})[\s\S])*structured_output/i.test(script),
);
}
describe("structured_output in shell scripts", () => {
test("the check finds a value written into a script", () => {
expect(
unsafeScripts(
"steps:\n - run: |\n OUTPUT='${{ steps.x.outputs.structured_output }}'\n",
),
).toHaveLength(1);
expect(
unsafeScripts(
"steps:\n - run: echo ${{ format('{0}', steps.x.outputs.structured_output) }}\n",
),
).toHaveLength(1);
expect(
unsafeScripts(
'steps:\n - env:\n OUTPUT: ${{ steps.x.outputs.structured_output }}\n run: echo "$OUTPUT"\n',
),
).toHaveLength(0);
});
test.each([
...scan("examples/*.{yml,yaml}"),
...scan("base-action/examples/*.{yml,yaml}"),
...scan(".github/workflows/*.{yml,yaml}"),
])("%s does not write it into a script", (file) => {
expect(unsafeScripts(readFileSync(join(root, file), "utf8"))).toEqual([]);
});
test.each(["README.md", "base-action/README.md", ...scan("docs/*.md")])(
"%s does not write it into a script",
(file) => {
const fences = yamlFences(readFileSync(join(root, file), "utf8"));
expect(
fences
.filter((fence) => fence.includes("structured_output"))
.flatMap(unsafeScripts),
).toEqual([]);
},
);
});
+698
View File
@@ -0,0 +1,698 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { execFileSync } from "child_process";
import {
chmodSync,
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
readlinkSync,
rmSync,
symlinkSync,
writeFileSync,
} from "fs";
import { tmpdir } from "os";
import { dirname, join } from "path";
import {
toolConfigDenyRules,
restoreToolConfigFromBase,
} from "../src/github/operations/tool-config";
import { restoreConfigFromBase } from "../src/github/operations/restore-config";
describe("restoreToolConfigFromBase", () => {
let originalCwd: string;
let tempDir: string;
const git = (...args: string[]) =>
execFileSync("git", args, { encoding: "utf8", stdio: "pipe" }).trim();
const write = (path: string, content: string, executable = false) => {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, content);
if (executable) chmodSync(path, 0o755);
};
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");
};
beforeEach(() => {
originalCwd = process.cwd();
tempDir = mkdtempSync(join(tmpdir(), "tool-config-"));
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);
rmSync(tempDir, { recursive: true, force: true });
});
test("does nothing when the pull request has the same tool config", () => {
write(".npmrc", "base\n");
write("package.json", '{"name":"x","bin":"cli.js"}');
startPr();
write("src/index.ts", "pr\n");
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(git("status", "--porcelain")).toBe("");
expect(existsSync(".claude-pr")).toBe(false);
});
test("uses the base version of a changed file, and removes an added one", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
write("bunfig.toml", "pr\n");
write("node_modules/.bin/node", "#!/bin/sh\n", true);
commit("pr");
expect(restoreToolConfigFromBase("main").sort()).toEqual([
".npmrc",
"bunfig.toml",
"node_modules",
]);
expect(read(".npmrc")).toBe("base\n");
expect(existsSync("bunfig.toml")).toBe(false);
expect(existsSync("node_modules")).toBe(false);
expect(read(".claude-pr/.npmrc")).toBe("pr\n");
// Nothing is staged, so the pull request's versions are still what git has.
expect(git("diff", "--cached", "--name-only")).toBe("");
});
test("brings back a file the pull request deleted", () => {
write(".npmrc", "base\n");
write("node_modules/.bin/tool", "base\n", true);
startPr();
rmSync(".npmrc");
rmSync("node_modules", { recursive: true });
commit("pr");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
expect(read("node_modules/.bin/tool")).toBe("base\n");
expect(lstatSync("node_modules/.bin/tool").mode & 0o111).not.toBe(0);
});
test("leaves untracked files that an earlier step created", () => {
write("bunfig.toml", "base\n");
startPr();
rmSync("bunfig.toml");
write(".npmrc.example", "pr\n");
commit("pr");
write("bunfig.toml", "from a step\n");
write(".npmrc", "from a step\n");
write("node_modules/.bin/tool", "installed\n", true);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("bunfig.toml")).toBe("from a step\n");
expect(read(".npmrc")).toBe("from a step\n");
expect(read("node_modules/.bin/tool")).toBe("installed\n");
});
test("keeps a step's change to a file the pull request leaves alone", () => {
write(".npmrc", "base\n");
startPr();
write("src/index.ts", "pr\n");
commit("pr");
write(".npmrc", "base\nfrom a step\n");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read(".npmrc")).toBe("base\nfrom a step\n");
});
test("keeps a file deleted by an earlier step deleted", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
rmSync(".npmrc");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(existsSync(".npmrc")).toBe(false);
});
test("leaves a directory an earlier step put in a tracked link's place", () => {
startPr();
symlinkSync("elsewhere", "node_modules");
commit("pr");
rmSync("node_modules");
write("node_modules/tool/a", "installed\n");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("node_modules/tool/a")).toBe("installed\n");
});
test("leaves files that a sparse checkout leaves out", () => {
write("node_modules/tool/a", "base\n");
startPr();
write("node_modules/tool/a", "pr\n");
commit("pr");
git("sparse-checkout", "set", "src");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(existsSync("node_modules/tool/a")).toBe(false);
});
test("replaces links without following them", () => {
write("node_modules/.bin/tool", "base\n", true);
startPr();
const outside = join(tempDir, "outside");
write(join(outside, ".bin/tool"), "outside\n");
rmSync("node_modules", { recursive: true });
symlinkSync(outside, "node_modules");
symlinkSync(join(outside, ".bin/tool"), ".npmrc");
commit("pr");
restoreToolConfigFromBase("main");
expect(lstatSync("node_modules").isDirectory()).toBe(true);
expect(read("node_modules/.bin/tool")).toBe("base\n");
expect(existsSync(".npmrc")).toBe(false);
expect(read(join(outside, ".bin/tool"))).toBe("outside\n");
});
test("writes and removes nothing through a link an earlier step added", () => {
write("node_modules/a/b", "base\n");
write("node_modules/c/d", "base\n");
startPr();
write("node_modules/a/b", "pr\n");
rmSync("node_modules/c", { recursive: true });
commit("pr");
const outside = join(tempDir, "outside");
write(join(outside, "a/b"), "outside\n");
rmSync("node_modules", { recursive: true });
symlinkSync(outside, "node_modules");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read(join(outside, "a/b"))).toBe("outside\n");
expect(existsSync(join(outside, "c"))).toBe(false);
});
test("brings back a link the base branch has", () => {
write("node_modules/tool/cli.js", "base\n");
mkdirSync("node_modules/.bin");
symlinkSync("../tool/cli.js", "node_modules/.bin/tool");
startPr();
rmSync("node_modules/.bin/tool");
write("node_modules/.bin/tool", "pr\n", true);
commit("pr");
restoreToolConfigFromBase("main");
expect(readlinkSync("node_modules/.bin/tool")).toBe("../tool/cli.js");
});
test("replaces a directory the pull request puts in a file's place", () => {
write(".npmrc", "base\n");
startPr();
rmSync(".npmrc");
write(".npmrc/keep", "pr\n");
commit("pr");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
});
test("replaces a directory that holds a package.json too", () => {
write(".npmrc", "base\n");
startPr();
rmSync(".npmrc");
write(".npmrc/package.json", "{}");
commit("pr");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
});
test("rewrites an unchanged file that .gitattributes re-encodes", () => {
write(".npmrc", "ignore-scripts=true\n");
startPr();
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
git("add", ".gitattributes");
git("commit", "-qm", "pr");
expect(git("rev-parse", "HEAD:.npmrc")).toBe(
git("rev-parse", "main:.npmrc"),
);
rmSync(".npmrc");
git("checkout", "--", ".npmrc");
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
});
test("sees re-encoding when .gitattributes is re-encoded too", () => {
write(".npmrc", "ignore-scripts=true\n");
startPr();
const encoding = "working-tree-encoding=UTF-16LE-BOM";
write(".gitattributes", `.npmrc ${encoding}\n.gitattributes ${encoding}\n`);
const oid = git("hash-object", "-w", "--no-filters", ".gitattributes");
git("update-index", "--add", "--cacheinfo", `100644,${oid},.gitattributes`);
git("commit", "-qm", "pr");
rmSync(".npmrc");
rmSync(".gitattributes");
git("checkout", "--", ".");
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
expect(read(".gitattributes")).not.toContain(encoding);
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
});
test("sees re-encoding by a .gitattributes that is only on disk", () => {
write(".npmrc", "ignore-scripts=true\n");
startPr();
write("f.txt", "pr\n");
commit("pr");
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
rmSync(".npmrc");
git("checkout", "--", ".npmrc");
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
});
test("matches names without regard to case", () => {
write(".npmrc", "base\n");
startPr();
write("BUNFIG.toml", "pr\n");
write("Node_Modules/.bin/node", "pr\n");
commit("pr");
restoreToolConfigFromBase("main");
expect(existsSync("BUNFIG.toml")).toBe(false);
expect(existsSync("Node_Modules/.bin/node")).toBe(false);
});
test("writes the base version as it is, whatever .gitattributes says", () => {
write(".npmrc", "ignore-scripts=true\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
});
test("keeps binary and empty content intact", () => {
const content = Buffer.from([0, 10, 255, 10, 13, 0]);
mkdirSync("node_modules");
writeFileSync("node_modules/a", content);
writeFileSync("node_modules/b", "");
writeFileSync("node_modules/c", "no newline");
startPr();
for (const name of ["a", "b", "c"]) write(`node_modules/${name}`, "pr");
commit("pr");
restoreToolConfigFromBase("main");
expect(readFileSync("node_modules/a").equals(content)).toBe(true);
expect(read("node_modules/b")).toBe("");
expect(read("node_modules/c")).toBe("no newline");
});
test("reports names from a fixed list, not the pull request's file names", () => {
startPr();
write("node_modules/a\n::stop-commands::x", "pr\n");
commit("pr");
const names = restoreToolConfigFromBase("main");
expect(names).toEqual(["node_modules"]);
expect(existsSync("node_modules")).toBe(false);
});
test("handles names that are not valid UTF-8", () => {
startPr();
const name = Buffer.from([...Buffer.from("node_modules/"), 0xff]);
mkdirSync("node_modules");
try {
writeFileSync(name, "pr\n");
} catch {
return; // This file system refuses such names.
}
commit("pr");
restoreToolConfigFromBase("main");
expect(existsSync(name)).toBe(false);
});
test("is not misled by a local branch with the base's name", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
git("branch", "origin/main");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
});
test("works in a checkout with no remote-tracking branch for the base", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
git("fetch", "-q", "origin", "main");
git("update-ref", "-d", "refs/remotes/origin/main");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
});
test("stops edits to tool config, and to package.json only if replaced", () => {
const rules = [
"Edit(./.npmrc)",
"Edit(./bunfig.toml)",
"Edit(./node_modules/**)",
];
expect(toolConfigDenyRules([])).toEqual(rules);
expect(toolConfigDenyRules(["package.json"])).toEqual([
...rules,
"Edit(package.json)",
]);
});
test("matches names a file system can treat as the same", () => {
startPr();
write("node_module\u017F/.bin/node", "pr\n");
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual(["node_modules"]);
});
test("fails without naming a file if the base version can't be read", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
const oid = git("rev-parse", "main:.npmrc");
rmSync(join(".git/objects", oid.slice(0, 2), oid.slice(2)));
expect(() => restoreToolConfigFromBase("main")).toThrow(
/^Could not use the base branch's version/,
);
expect(existsSync(".npmrc")).toBe(false);
});
describe("package.json", () => {
const baseJson = { name: "x", bin: { x: "x.js" }, version: "1.0.0" };
const start = (pr: unknown) => {
write("package.json", JSON.stringify(baseJson));
startPr();
write("package.json", typeof pr === "string" ? pr : JSON.stringify(pr));
commit("pr");
};
test("keeps the pull request's version when only other fields change", () => {
const pr = { ...baseJson, version: "2.0.0", dependencies: { a: "1" } };
start(pr);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(JSON.parse(read("package.json"))).toEqual(pr);
});
test("keeps the pull request's version when it removes the commands", () => {
start({ name: "x" });
expect(restoreToolConfigFromBase("main")).toEqual([]);
});
test.each([
["bin", { bin: { "tool@latest": "a.js" } }],
["directories", { directories: { bin: "bin" } }],
["name", { name: "tool" }],
["workspaces", { workspaces: ["pkgs/*"] }],
])("uses only the base's commands when %s changes", (_, change) => {
const pr = { ...baseJson, ...change, dependencies: { a: "1" } };
start(pr);
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("package.json"))).toEqual({
...baseJson,
dependencies: { a: "1" },
});
expect(JSON.parse(read(".claude-pr/package.json"))).toEqual(pr);
});
describe("that .gitattributes converts", () => {
const commitRaw = (attributes: string, stored: string) => {
write(".gitattributes", `package.json ${attributes}\n`);
write("package.json", stored);
const oid = git("hash-object", "-w", "--no-filters", "package.json");
git("add", ".gitattributes");
git("update-index", "--cacheinfo", `100644,${oid},package.json`);
git("commit", "-qm", "pr");
rmSync("package.json");
git("checkout", "--", "package.json");
};
const startFromBase = () => {
write("package.json", JSON.stringify(baseJson));
startPr();
};
test("replaces commands that are only on disk", () => {
startFromBase();
commitRaw(
"ident",
'{"name":"x","a":"$Id:","b":{"c":"$","bin":{"x":"pr.js"},"d":"$Id:"},"e":"$"}',
);
expect(JSON.parse(read("package.json")).bin).toEqual({ x: "pr.js" });
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("package.json")).bin).toEqual(baseJson.bin);
});
test("replaces one that can't be understood", () => {
startFromBase();
commitRaw(
"working-tree-encoding=UTF-16LE-BOM",
JSON.stringify(baseJson),
);
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("package.json"))).toEqual(baseJson);
});
test("replaces commands that aren't on disk", () => {
startFromBase();
commitRaw(
"ident",
'{"name":"x","a":"$Id: ","bin":{"x":"pr.js"},"b":" $"}',
);
expect(JSON.parse(read("package.json")).bin).toBeUndefined();
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
});
test("keeps a step's change to one that the pull request leaves alone", () => {
write(".gitattributes", "* ident\n");
startFromBase();
write("f.txt", "pr\n");
commit("pr");
const changed = JSON.stringify({ ...baseJson, name: "@scope/x" });
write("package.json", changed);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("package.json")).toBe(changed);
});
test("keeps one whose encoding is no conversion", () => {
startFromBase();
const pr = JSON.stringify({ ...baseJson, version: "2.0.0" });
commitRaw("working-tree-encoding=UTF-8", pr);
expect(restoreToolConfigFromBase("main")).toEqual([]);
});
test("keeps what a step changed in one that is not converted", () => {
startFromBase();
write(
"package.json",
JSON.stringify({ ...baseJson, version: "2.0.0" }),
);
commit("pr");
const changed = JSON.stringify({ ...baseJson, name: "@scope/x" });
write("package.json", changed);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("package.json")).toBe(changed);
});
test("keeps one with the same commands", () => {
startFromBase();
const pr = JSON.stringify({ ...baseJson, version: "2.0.0" });
commitRaw("ident", pr);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("package.json")).toBe(pr);
});
});
test("keeps a new name if directories holds no commands", () => {
const directories = { test: "test" };
write("package.json", JSON.stringify({ name: "x", directories }));
startPr();
const pr = JSON.stringify({ name: "y", directories: { test: "t" } });
write("package.json", pr);
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("package.json")).toBe(pr);
});
test.each([[null], ["bin"], [["bin"]], [1]])(
"copes with directories being %p",
(directories) => {
start({ name: "y", directories });
expect(restoreToolConfigFromBase("main")).toEqual([]);
},
);
test("uses the base version when it can't be understood", () => {
start("{");
restoreToolConfigFromBase("main");
expect(JSON.parse(read("package.json"))).toEqual(baseJson);
});
test("understands a byte order mark", () => {
start(`\uFEFF${JSON.stringify({ ...baseJson, version: "2.0.0" })}`);
expect(restoreToolConfigFromBase("main")).toEqual([]);
});
test("looks in subdirectories only if the base branch has workspaces", () => {
const tool = JSON.stringify({ name: "tool", bin: "x.js", version: "1" });
startPr();
write("pkgs/p/package.json", tool);
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual([]);
git("checkout", "-q", "main");
write("package.json", '{"name":"x","workspaces":["pkgs/*"]}');
commit("base 2");
git("push", "-q", "origin", "main");
git("checkout", "-q", "-b", "pr2");
write("pkgs/p/package.json", tool);
commit("pr2");
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("pkgs/p/package.json"))).toEqual({
name: "tool",
version: "1",
});
expect(JSON.parse(read(".claude-pr/pkgs/p/package.json")).name).toBe(
"tool",
);
});
test("leaves what the base branch's .claude and .husky hold", () => {
const base = '{"name":"hooks","bin":"a.js","scripts":{"check":"base"}}';
write("package.json", '{"name":"x","workspaces":["pkgs/*"]}');
write(".claude/hooks/package.json", base);
write(".husky/package.json", base);
startPr();
for (const dir of [".claude/hooks", ".husky"]) {
write(`${dir}/package.json`, '{"bin":"b.js","scripts":{"check":"pr"}}');
}
commit("pr");
restoreConfigFromBase("main");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read(".claude/hooks/package.json")).toBe(base);
expect(read(".husky/package.json")).toBe(base);
});
test("counts another spelling of a restored directory only if it is that one", () => {
const tool = '{"name":"tool","bin":"x.js"}';
write("package.json", '{"name":"x","workspaces":["*"]}');
write(".husky/package.json", tool);
startPr();
write(".Husky/package.json", tool);
write("claude.md/package.json", tool);
commit("pr");
restoreConfigFromBase("main");
const ownDirectories = readdirSync(".").filter((name) =>
[".Husky", "claude.md"].includes(name),
);
expect(restoreToolConfigFromBase("main")).toEqual(
ownDirectories.length > 0 ? ["package.json"] : [],
);
expect(read(".husky/package.json")).toBe(tool);
for (const dir of ownDirectories) {
expect(JSON.parse(read(`${dir}/package.json`))).toEqual({
name: "tool",
});
}
});
test("reports a restored directory's other spelling that it removes", () => {
write("package.json", '{"name":"x","workspaces":["*"]}');
startPr();
write("claude.md/package.json", "{");
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(existsSync("claude.md")).toBe(false);
});
test("takes the commands out of a new package.json", () => {
startPr();
write("package.json", '{"name":"x"}');
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual([]);
write("package.json", '{"name":"x","version":"1","bin":{"t":"a.js"}}');
commit("pr 2");
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("package.json"))).toEqual({
name: "x",
version: "1",
});
});
});
});
+137
View File
@@ -488,3 +488,140 @@ describe("escapeRegExp", () => {
expect(escapeRegExp("test[123]")).toBe("test\\[123\\]");
});
});
describe("checkContainsTrigger with a prompt on issue events", () => {
const issueEvent = (
payloadExtra: object,
eventAction: string,
inputs: object,
): ParsedGitHubContext =>
createMockContext({
eventName: "issues",
eventAction,
inputs: {
prompt: "Triage this issue",
labelTrigger: "claude-task",
assigneeTrigger: "",
...inputs,
} as any,
payload: { action: eventAction, issue: { number: 1 }, ...payloadExtra },
} as any);
it("does not start on a label other than the trigger label", () => {
expect(
checkContainsTrigger(
issueEvent({ label: { name: "bug" } }, "labeled", {}),
),
).toBe(false);
});
it("starts on the trigger label, ignoring case", () => {
expect(
checkContainsTrigger(
issueEvent({ label: { name: "Claude-Task" } }, "labeled", {}),
),
).toBe(true);
});
it("does not start on an assignment to someone else", () => {
expect(
checkContainsTrigger(
issueEvent({ assignee: { login: "teammate" } }, "assigned", {
assigneeTrigger: "claude-bot",
}),
),
).toBe(false);
});
it("starts on any assignment when no assignee trigger is set", () => {
expect(
checkContainsTrigger(
issueEvent({ assignee: { login: "teammate" } }, "assigned", {}),
),
).toBe(true);
});
it("still starts on other issue events", () => {
expect(checkContainsTrigger(issueEvent({}, "opened", {}))).toBe(true);
});
});
describe("checkContainsTrigger when the text is someone else's", () => {
const commentEvent = (eventAction: string, author: string, actor: string) =>
({
...mockIssueCommentContext,
eventAction,
actor,
payload: {
...mockIssueCommentContext.payload,
action: eventAction,
comment: {
...(mockIssueCommentContext.payload as any).comment,
body: "@claude do this",
user: { login: author },
},
},
}) as ParsedGitHubContext;
it("starts on a person's own new comment", () => {
const context = commentEvent("created", "maintainer", "maintainer");
expect(
checkContainsTrigger({
...context,
inputs: { ...context.inputs, triggerPhrase: "@claude" },
}),
).toBe(true);
});
it("does not start when a maintainer edits an outsider's comment", () => {
const context = commentEvent("edited", "outsider", "maintainer");
expect(
checkContainsTrigger({
...context,
inputs: { ...context.inputs, triggerPhrase: "@claude" },
}),
).toBe(false);
});
it("does not start on someone else's edited comment even with a prompt", () => {
const context = commentEvent("edited", "outsider", "maintainer");
expect(
checkContainsTrigger({
...context,
inputs: { ...context.inputs, prompt: "Triage this" },
}),
).toBe(false);
});
it("does not start on a deleted comment, even the actor's own", () => {
const context = commentEvent("deleted", "maintainer", "maintainer");
expect(
checkContainsTrigger({
...context,
inputs: { ...context.inputs, triggerPhrase: "@claude" },
}),
).toBe(false);
});
it("does not start when a review was written by someone else", () => {
const base = mockPullRequestReviewContext;
const payload = base.payload as any;
expect(
checkContainsTrigger({
...base,
actor: "maintainer",
eventAction: "edited",
inputs: { ...base.inputs, triggerPhrase: "@claude" },
payload: {
...payload,
action: "edited",
review: {
...payload.review,
body: "@claude do this",
user: { login: "outsider" },
},
},
} as ParsedGitHubContext),
).toBe(false);
});
});
+401
View File
@@ -0,0 +1,401 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import * as core from "@actions/core";
import { parseSdkOptions } from "../base-action/src/parse-sdk-options";
import type { ParsedGitHubContext } from "../src/github/context";
import {
getUntrustedPrDisallowedTools,
UNTRUSTED_PR_DISALLOWED_TOOLS,
} from "../src/github/validation/untrusted-pr";
import {
mockIssueCommentContext,
mockPullRequestCommentContext,
mockPullRequestOpenedContext,
mockPullRequestReviewCommentContext,
mockPullRequestReviewContext,
} from "./mockContext";
function octokitWithPermission(permission: string) {
const calls: string[] = [];
const octokit = {
repos: {
getCollaboratorPermissionLevel: async ({
username,
}: {
username: string;
}) => {
calls.push(username);
return { data: { permission } };
},
},
} as any;
return { octokit, calls };
}
function httpError(status: number) {
return Object.assign(new Error(`HTTP ${status}`), { status });
}
function withPrAuthor(
context: ParsedGitHubContext,
login: string,
): ParsedGitHubContext {
const payload = context.payload as any;
const key = "pull_request" in payload ? "pull_request" : "issue";
return {
...context,
payload: {
...payload,
[key]: { ...payload[key], user: { ...payload[key].user, login } },
},
};
}
describe("getUntrustedPrDisallowedTools", () => {
let warningSpy: any;
let logSpy: any;
let errorSpy: any;
const savedSetting = process.env.RESTRICT_UNTRUSTED_PRS;
const savedArgs = process.env.CLAUDE_ARGS;
const warnings = (): string[] =>
warningSpy.mock.calls.map((call: any[]) => call[0]);
const uncoveredWarning = () =>
warnings().find((w) => w.includes("Bash rule(s)"));
beforeEach(() => {
warningSpy = spyOn(core, "warning").mockImplementation(() => {});
logSpy = spyOn(console, "log").mockImplementation(() => {});
errorSpy = spyOn(console, "error").mockImplementation(() => {});
delete process.env.RESTRICT_UNTRUSTED_PRS;
delete process.env.CLAUDE_ARGS;
});
afterEach(() => {
warningSpy.mockRestore();
logSpy.mockRestore();
errorSpy.mockRestore();
if (savedSetting === undefined) delete process.env.RESTRICT_UNTRUSTED_PRS;
else process.env.RESTRICT_UNTRUSTED_PRS = savedSetting;
if (savedArgs === undefined) delete process.env.CLAUDE_ARGS;
else process.env.CLAUDE_ARGS = savedArgs;
});
test("does not restrict issues or look anything up for them", async () => {
const { octokit, calls } = octokitWithPermission("read");
expect(
await getUntrustedPrDisallowedTools(octokit, mockIssueCommentContext),
).toEqual([]);
expect(calls).toEqual([]);
});
test.each(["admin", "write"])(
"does not restrict a PR whose author has %s access",
async (permission) => {
const { octokit } = octokitWithPermission(permission);
expect(
await getUntrustedPrDisallowedTools(
octokit,
mockPullRequestOpenedContext,
),
).toEqual([]);
},
);
test.each(["read", "triage", "none"])(
"restricts a PR whose author has %s access",
async (permission) => {
const { octokit } = octokitWithPermission(permission);
expect(
await getUntrustedPrDisallowedTools(
octokit,
mockPullRequestOpenedContext,
),
).toEqual(UNTRUSTED_PR_DISALLOWED_TOOLS);
},
);
test.each([
[mockPullRequestCommentContext, "issue_comment"],
[mockPullRequestReviewContext, "pull_request_review"],
[mockPullRequestReviewCommentContext, "pull_request_review_comment"],
] as [ParsedGitHubContext, string][])(
"checks the PR author, not the actor, on %#: %s events",
async (context) => {
const { octokit, calls } = octokitWithPermission("write");
await getUntrustedPrDisallowedTools(
octokit,
withPrAuthor(context, "the-pr-author"),
);
expect(calls).toEqual(["the-pr-author"]);
},
);
test("treats a failed lookup as untrusted, without retrying a 404", async () => {
let attempts = 0;
const octokit = {
repos: {
getCollaboratorPermissionLevel: async () => {
attempts++;
throw httpError(404);
},
},
} as any;
expect(
await getUntrustedPrDisallowedTools(
octokit,
mockPullRequestOpenedContext,
),
).toEqual(UNTRUSTED_PR_DISALLOWED_TOOLS);
expect(attempts).toBe(1);
});
test.each([[{ "retry-after": "1" }], [{ "x-ratelimit-remaining": "0" }]])(
"retries a rate-limited 403 (%j)",
async (headers) => {
let attempts = 0;
const octokit = {
repos: {
getCollaboratorPermissionLevel: async () => {
attempts++;
if (attempts === 1) {
throw Object.assign(httpError(403), { response: { headers } });
}
return { data: { permission: "write" } };
},
},
} as any;
expect(
await getUntrustedPrDisallowedTools(
octokit,
mockPullRequestOpenedContext,
),
).toEqual([]);
expect(attempts).toBe(2);
},
);
test("does not retry a plain 403", async () => {
let attempts = 0;
const octokit = {
repos: {
getCollaboratorPermissionLevel: async () => {
attempts++;
throw Object.assign(httpError(403), {
response: { headers: { "x-ratelimit-remaining": "42" } },
});
},
},
} as any;
expect(
await getUntrustedPrDisallowedTools(
octokit,
mockPullRequestOpenedContext,
),
).toEqual(UNTRUSTED_PR_DISALLOWED_TOOLS);
expect(attempts).toBe(1);
});
test("retries a transient failure before deciding", async () => {
let attempts = 0;
const octokit = {
repos: {
getCollaboratorPermissionLevel: async () => {
attempts++;
if (attempts === 1) throw httpError(503);
return { data: { permission: "write" } };
},
},
} as any;
expect(
await getUntrustedPrDisallowedTools(
octokit,
mockPullRequestOpenedContext,
),
).toEqual([]);
expect(attempts).toBe(2);
});
test("treats a missing author as untrusted without a lookup", async () => {
const payload = mockPullRequestOpenedContext.payload as any;
const context = {
...mockPullRequestOpenedContext,
payload: {
...payload,
pull_request: { ...payload.pull_request, user: null },
},
} as ParsedGitHubContext;
const { octokit, calls } = octokitWithPermission("admin");
expect(await getUntrustedPrDisallowedTools(octokit, context)).toEqual(
UNTRUSTED_PR_DISALLOWED_TOOLS,
);
expect(calls).toEqual([]);
});
test("treats bot authors as untrusted without a lookup", async () => {
const { octokit, calls } = octokitWithPermission("admin");
expect(
await getUntrustedPrDisallowedTools(
octokit,
withPrAuthor(mockPullRequestOpenedContext, "dependabot[bot]"),
),
).toEqual(UNTRUSTED_PR_DISALLOWED_TOOLS);
expect(calls).toEqual([]);
});
test.each(["false", "False", "FALSE", " false "])(
"is turned off by %p",
async (value) => {
process.env.RESTRICT_UNTRUSTED_PRS = value;
const { octokit, calls } = octokitWithPermission("none");
expect(
await getUntrustedPrDisallowedTools(
octokit,
mockPullRequestOpenedContext,
),
).toEqual([]);
expect(calls).toEqual([]);
},
);
test.each([undefined, "", "true", "True", "flase", "no"])(
"stays on for %p",
async (value) => {
if (value === undefined) delete process.env.RESTRICT_UNTRUSTED_PRS;
else process.env.RESTRICT_UNTRUSTED_PRS = value;
const { octokit } = octokitWithPermission("none");
expect(
await getUntrustedPrDisallowedTools(
octokit,
mockPullRequestOpenedContext,
),
).toEqual(UNTRUSTED_PR_DISALLOWED_TOOLS);
},
);
test("counts allowed Bash rules the list does not cover", async () => {
process.env.CLAUDE_ARGS = `--allowedTools "Read,Bash(bun:*),Bash(./scripts/test.sh),Bash(git:*),Bash(gh pr view:*)"`;
const { octokit } = octokitWithPermission("none");
await getUntrustedPrDisallowedTools(octokit, mockPullRequestOpenedContext);
expect(uncoveredWarning()).toStartWith("3 Bash rule(s)");
});
test("counts a bare Bash rule", async () => {
process.env.CLAUDE_ARGS = `--allowedTools "Read,Bash"`;
const { octokit } = octokitWithPermission("none");
await getUntrustedPrDisallowedTools(octokit, mockPullRequestOpenedContext);
expect(uncoveredWarning()).toStartWith("1 Bash rule(s)");
});
test("does not count rules the list denies", async () => {
process.env.CLAUDE_ARGS = `--allowedTools "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(npm),Bash(git config user.name:*)"`;
const { octokit } = octokitWithPermission("none");
await getUntrustedPrDisallowedTools(octokit, mockPullRequestOpenedContext);
expect(uncoveredWarning()).toBeUndefined();
});
test("does not mistake a longer command for a denied one", async () => {
process.env.CLAUDE_ARGS = `--allowedTools "Bash(gofmt:*)"`;
const { octokit } = octokitWithPermission("none");
await getUntrustedPrDisallowedTools(octokit, mockPullRequestOpenedContext);
expect(uncoveredWarning()).toStartWith("1 Bash rule(s)");
});
test("handles unquoted rules the same as quoted ones", async () => {
process.env.CLAUDE_ARGS = `--allowedTools Bash(bun:*),Bash(npm:*)`;
const { octokit } = octokitWithPermission("none");
await getUntrustedPrDisallowedTools(octokit, mockPullRequestOpenedContext);
expect(uncoveredWarning()).toBeUndefined();
});
test("never prints the content of claude_args or a raw error", async () => {
const secret = "not-a-real-secret-value";
process.env.CLAUDE_ARGS = `--allowedTools "Bash(curl -H ${secret}:*)"`;
const octokit = {
repos: {
getCollaboratorPermissionLevel: async () => {
throw Object.assign(new Error(`failed with ${secret}`), {
status: 404,
});
},
},
} as any;
await getUntrustedPrDisallowedTools(octokit, mockPullRequestOpenedContext);
const logged = [
...warnings(),
...logSpy.mock.calls.flat(),
...errorSpy.mock.calls.flat(),
].join("\n");
expect(logged).toContain("HTTP 404");
expect(logged).toContain("1 Bash rule(s)");
expect(logged).not.toContain(secret);
});
test.each([
"--dangerously-skip-permissions",
"--allow-dangerously-skip-permissions",
"--permission-mode bypassPermissions",
"--permission-mode=bypassPermissions",
`--permission-mode "bypassPermissions"`,
])("warns when claude_args has %s", async (flag) => {
process.env.CLAUDE_ARGS = flag;
const { octokit } = octokitWithPermission("none");
await getUntrustedPrDisallowedTools(octokit, mockPullRequestOpenedContext);
expect(warnings().some((w) => w.includes("permission checks"))).toBe(true);
});
test.each([
"--permission-mode auto",
"--permission-mode auto\n# --permission-mode bypassPermissions",
])("does not warn about permission checks for %j", async (claudeArgs) => {
process.env.CLAUDE_ARGS = claudeArgs;
const { octokit } = octokitWithPermission("none");
await getUntrustedPrDisallowedTools(octokit, mockPullRequestOpenedContext);
expect(warnings().some((w) => w.includes("permission checks"))).toBe(false);
});
test("keeps a synchronous client failure out of the log", async () => {
const secret = "not-a-real-secret-value";
const octokit = {
repos: {
getCollaboratorPermissionLevel: () => {
throw new Error(`failed with ${secret}`);
},
},
} as any;
expect(
await getUntrustedPrDisallowedTools(
octokit,
mockPullRequestOpenedContext,
),
).toEqual(UNTRUSTED_PR_DISALLOWED_TOOLS);
const logged = [
...warnings(),
...logSpy.mock.calls.flat(),
...errorSpy.mock.calls.flat(),
].join("\n");
expect(logged).toContain("no response");
expect(logged).not.toContain(secret);
});
test.each([
["a trailing comment line", `--model x\n# a note`],
["a trailing inline comment", `--model x # a note`],
["other deny rules", `--disallowedTools "WebFetch"`],
])("reaches the SDK alongside claude_args with %s", (_, claudeArgs) => {
const { sdkOptions } = parseSdkOptions({
claudeArgs,
disallowedTools: UNTRUSTED_PR_DISALLOWED_TOOLS.join(","),
});
expect(sdkOptions.disallowedTools).toEqual(
expect.arrayContaining([...UNTRUSTED_PR_DISALLOWED_TOOLS]),
);
});
test("adds no deny rules to the SDK when there are none", () => {
const { sdkOptions } = parseSdkOptions({
claudeArgs: "--model x",
disallowedTools: [].join(","),
});
expect(sdkOptions.disallowedTools).toBeUndefined();
});
});
+22
View File
@@ -87,4 +87,26 @@ describe("updateGitReference", () => {
expect(attempts).toBe(2);
});
it.each([
["main#pwn", "main%23pwn"],
["main?x=1", "main%3Fx%3D1"],
["feature/fix-1", "feature/fix-1"],
])("encodes %s in the request URL", async (branch, encoded) => {
let requested = "";
await updateGitReference({
owner: "o",
repo: "r",
branch,
sha: "abc",
githubToken: "t",
fetchFn: async (url) => {
requested = String(url);
return response(200);
},
});
expect(requested).toBe(
`${GITHUB_API_URL}/repos/o/r/git/refs/heads/${encoded}`,
);
});
});