mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-11-25 06:53:01 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a461cbbb7 | ||
|
|
b5e37652b7 | ||
|
|
423df53bc5 | ||
|
|
acfe799285 | ||
|
|
3c38c04401 |
+9
-12
@@ -45,9 +45,9 @@ inputs:
|
||||
required: false
|
||||
default: ""
|
||||
allow_fork_prs:
|
||||
description: "Whether to run on pull requests from forks, and on workflow_run events for a fork's run. With any value other than 'true', the action skips them, whoever opened them, before it checks anything out. See docs/security.md."
|
||||
description: "Set to 'true' to run on pull requests from forks, and on workflow_run events for a fork's run. By default, and with any other value, the action skips them, whoever opened them, before it checks anything out. Where the event has credentials, a run that the actor checks refuse fails instead. See docs/security.md."
|
||||
required: false
|
||||
default: "true"
|
||||
default: "false"
|
||||
restrict_untrusted_prs:
|
||||
description: "On pull requests whose author does not have write access, deny commands that commonly run code from the checkout (package managers, test runners, interpreters, shells), even if claude_args allows them. Set to 'false' to turn this off. See docs/security.md."
|
||||
required: false
|
||||
@@ -289,16 +289,13 @@ runs:
|
||||
# takes its settings from the action's directory. Bun before 1.4.3 logs
|
||||
# "directory mismatch" for --tsconfig-override (oven-sh/bun#25730).
|
||||
#
|
||||
# Bash reads this script as it runs. The braces and exit make it read the
|
||||
# rest first and stop there. With exec instead, cancelling the run would
|
||||
# interrupt Bun at once, before it can clean up.
|
||||
{
|
||||
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
|
||||
exit
|
||||
}
|
||||
# Bash reads this script as it runs, so exec also keeps it from running what a
|
||||
# session adds. When the run is cancelled, the runner signals only this step's
|
||||
# own process, and Bun has to get that signal to stop the session.
|
||||
exec 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:
|
||||
# Turns off Bun's cache of transpiled files, which is outside the action's
|
||||
# directory. Set it wherever the action runs its own scripts.
|
||||
|
||||
@@ -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.329"
|
||||
CLAUDE_CODE_VERSION="2.1.331"
|
||||
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||
for attempt in 1 2 3; do
|
||||
echo "Installation attempt $attempt..."
|
||||
@@ -183,13 +183,10 @@ runs:
|
||||
echo "Changing directory to CLAUDE_WORKING_DIR: $CLAUDE_WORKING_DIR"
|
||||
cd "$CLAUDE_WORKING_DIR"
|
||||
fi
|
||||
# Bash reads this script as it runs. The braces and exit make it read the
|
||||
# rest first and stop there. With exec instead, cancelling the run would
|
||||
# interrupt Bun at once, before it can clean up.
|
||||
{
|
||||
bun run ${GITHUB_ACTION_PATH}/src/index.ts
|
||||
exit
|
||||
}
|
||||
# Bash reads this script as it runs, so exec also keeps it from running what a
|
||||
# session adds. When the run is cancelled, the runner signals only this step's
|
||||
# own process, and Bun has to get that signal to stop the session.
|
||||
exec bun run ${GITHUB_ACTION_PATH}/src/index.ts
|
||||
env:
|
||||
# Turns off Bun's cache of transpiled files, which is outside the action's
|
||||
# directory
|
||||
|
||||
+10
-10
@@ -6,7 +6,7 @@
|
||||
"name": "@anthropic-ai/claude-code-base-action",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.329",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
|
||||
"shell-quote": "^1.8.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -27,23 +27,23 @@
|
||||
|
||||
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]29", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.329", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.329", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.329", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.329", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.329", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.329", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.329", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.329" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-aKVIgPBmgNHBoNXUFG5eVJXudDd+amObxT6QH9b6R2yGKf4eisPZ3Ij5RSpkFHDvJvaZy8m1AJeEkbKSusTU/Q=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]31", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.331" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-ml/MPqgO95tG5zcApBFxEyoDk57d9htP09R8AtPbKPUCHpsobf84IjkN4zhGvQgk8zsA9dXoeMGrQcCc8gQE/w=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]29", "", { "os": "darwin", "cpu": "arm64" }, "sha512-SaVFEDYHofgKftJGX8Uf5oa1wG9d2E9QAQqEpSCtiJrt7Ih82Ekn9b4ir0GufgwoOKx5IOv/CnMsXIWRl9vWrg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PQrn7YTiSV5Bg+ueF2hNvswc+wI7YKC2c32XNedvs6vfMCUUnIlq93VEbZiRY23b+JIVkEm8gb1VhkJTjsYISQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]29", "", { "os": "darwin", "cpu": "x64" }, "sha512-nYtGrz5oe/SK8jMKr/JArzrjEBtTqLWlRBlGu6QLXBoXd4PB5Fdj+Nh7Idnf+LD8OwWz1fqXj8zt0HTIUMSvYA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]31", "", { "os": "darwin", "cpu": "x64" }, "sha512-dc3iB+CY3jDpKpDpmvYc4V+UKSkudY29iJ62p0s5TK3h+b7Wqa2Hv0bPow0LUs4ZzDUXxEtCEHzk9X29VfLovw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]29", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-QvIfyMfjiYU2wkMfQ+tXTSwK76pXh/xSgdAFuqcPOiM3qgfi1kImcCIy/0wUnm9HGn0GZLXu7x0/lBu/PNHxVg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-xiRxBxoM8Qa5fnjCFk5iFheL5GUroLuHPJ7UnD4v2Sv1tWxGoSL67AYnMZ6OdjMguZK09X4WlgOn1nL1m6NEOA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]29", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-aOf1nA8roGApMzfL/aoEMBDGi11ZKtNV7mvp6OmaU0pgC24qECBeSUdsUuQBu9Z97kf5PDCh12JhkeHVDK+4JA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KdIClOdBUIpvf4PTFe2qedtPCOM3tC/jbsjh8U6WXF0QS8VjYkP0QR9i2AXG1PSAnI24T5xTxQb1scPAgRTIUQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]29", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-TKHcN+kOwG1Q6meOhKu9ZCJPUsXRL4dgx07R1BPgm0vREPpsSxaET5w7LuCs4pLIQgATJdqj6hjWtejDhVszNA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-nfHSiLJdkpsVAFsXTriyW3r64gS1sp5zxvaoF2dmNqKixR4rf9ISDDi81gF9L1uk/bAEcBGRx34U6Itw+NYIEg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]29", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-0j1Pu/egb7tbZk570MOd9vUVSlHvxnoA9ccDMdrAFqFGq3qb20IdHf4AvXuo9sbksKFXTx9oeEsvD4iFrL+wlA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-CSeT1JF++Vckf6TSXjQeuSjQ/sJnoTVL/XX44v4jHNAtU5i22nI9b27E6wkzudYVxoRoLWIU00V05dXhYYCvlg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]29", "", { "os": "win32", "cpu": "arm64" }, "sha512-lv4VKGQnTWIVToeWNrpekWIzYeTAQtOzDGXsU7krUizvJl3X0J/KiqEUB1Yi/F9VcYs3Aiu81RWtKdATLM5nkA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "win32", "cpu": "arm64" }, "sha512-FsPHWUpgHBFgSZESwM53JsbEoQiWPnigSCyjSfHDyiWnH66e0NsuksuJ/Nu9qI8UVgBDh/y1NOnnd4eGrB3eFQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]29", "", { "os": "win32", "cpu": "x64" }, "sha512-Pyn2sQciPirZk9OVh6EshSra84OBk11kJyTXgDv/v5PbHU2n2I+BbBYWkTeHpWeLlfRI61LWkFHtqs9cYOLOkg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]31", "", { "os": "win32", "cpu": "x64" }, "sha512-AsLur4ov9MGTQTrnZ49ZDPasQ35U3X/rZDdF/rPhytN3h1F3w/0IkC6esW3OzldvPlci60QvggOLVGnFlUzdxw=="],
|
||||
|
||||
"@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=="],
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.329",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
|
||||
"shell-quote": "^1.8.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { spawnSync } from "child_process";
|
||||
import { readdirSync, readFileSync } from "fs";
|
||||
|
||||
// The runner sends SIGINT, SIGTERM after 7.5 seconds, and kills the step 2.5 seconds
|
||||
// later, so a cancel that starts with SIGTERM has to fit into that.
|
||||
const GRACE_MS = 1000;
|
||||
const PAUSE_MS = 500;
|
||||
const POLL_MS = 50;
|
||||
|
||||
type Process = { pid: number; parent: number };
|
||||
|
||||
function listProcesses(): Process[] {
|
||||
if (process.platform === "linux") {
|
||||
return readdirSync("/proc")
|
||||
.filter((name) => /^\d+$/.test(name))
|
||||
.flatMap((name) => {
|
||||
try {
|
||||
const stat = readFileSync(`/proc/${name}/stat`, "utf8");
|
||||
// The command's name comes before these fields and can hold anything.
|
||||
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
||||
const threads = Number(fields[17]);
|
||||
// This process can't reap its children while it waits for them. One whose
|
||||
// first thread has ended, but not its others, is a zombie here too.
|
||||
if (fields[0] === "Z" && threads <= 1) return [];
|
||||
return [{ pid: Number(name), parent: Number(fields[1]) }];
|
||||
} catch {
|
||||
return []; // It has ended
|
||||
}
|
||||
});
|
||||
}
|
||||
if (process.platform === "win32") return []; // The runner's Ctrl+C reaches these
|
||||
// By path, because a session may be able to write to a directory in PATH
|
||||
const ps = spawnSync("/bin/ps", ["-A", "-o", "pid=,ppid=,state="], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (ps.error) throw ps.error;
|
||||
if (ps.status !== 0) throw new Error("ps failed");
|
||||
return ps.stdout.split("\n").flatMap((line) => {
|
||||
const [pid, parent, state] = line.trim().split(/\s+/);
|
||||
if (!pid || Number(pid) === ps.pid || state!.startsWith("Z")) return [];
|
||||
return [{ pid: Number(pid), parent: Number(parent) }];
|
||||
});
|
||||
}
|
||||
|
||||
/** What these processes have started, and they themselves, if still running. */
|
||||
function listTree(roots: Iterable<number>): Set<number> {
|
||||
const processes = listProcesses();
|
||||
const running = new Set(processes.map(({ pid }) => pid));
|
||||
const children = new Map<number, number[]>();
|
||||
for (const { pid, parent } of processes) {
|
||||
children.set(parent, [...(children.get(parent) ?? []), pid]);
|
||||
}
|
||||
const tree = new Set([...roots].filter((pid) => running.has(pid)));
|
||||
// A set's iterator also visits what is added meanwhile.
|
||||
for (const pid of tree)
|
||||
children.get(pid)?.forEach((child) => tree.add(child));
|
||||
tree.delete(process.pid);
|
||||
return tree;
|
||||
}
|
||||
|
||||
const cannotSignal = new Set<number>();
|
||||
|
||||
function signal(pids: Iterable<number>, name: NodeJS.Signals): void {
|
||||
for (const pid of pids) {
|
||||
try {
|
||||
process.kill(pid, name);
|
||||
} catch (error) {
|
||||
if ((error as { code?: string }).code === "EPERM") cannotSignal.add(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops everything this process started that is still in its process tree. Programs
|
||||
* first get to clean up after themselves, as git does with its lock files. They are
|
||||
* paused before each signal, because what a process starts while it is being stopped
|
||||
* would leave the tree.
|
||||
*/
|
||||
export function stopDescendants(): void {
|
||||
const known = new Set<number>();
|
||||
// What one of these started stays known once that one has ended.
|
||||
const update = () => {
|
||||
const running = listTree([process.pid, ...known]);
|
||||
known.clear();
|
||||
running.forEach((pid) => known.add(pid));
|
||||
return known;
|
||||
};
|
||||
const pause = () => {
|
||||
const paused = new Set<number>();
|
||||
for (const end = Date.now() + PAUSE_MS; Date.now() < end; ) {
|
||||
const added = [...update()].filter((pid) => !paused.has(pid));
|
||||
if (added.length === 0) return;
|
||||
signal(added, "SIGSTOP");
|
||||
added.forEach((pid) => paused.add(pid));
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
pause();
|
||||
signal(known, "SIGTERM");
|
||||
signal(known, "SIGCONT");
|
||||
for (const end = Date.now() + GRACE_MS; Date.now() < end; ) {
|
||||
if (update().size === 0) return;
|
||||
Bun.sleepSync(POLL_MS);
|
||||
}
|
||||
pause();
|
||||
} finally {
|
||||
// Also when the processes can't be listed, so that none stays paused.
|
||||
signal(known, "SIGKILL");
|
||||
const left = [...known].filter((pid) => cannotSignal.has(pid));
|
||||
if (left.length > 0) {
|
||||
console.log(
|
||||
`::warning::Processes of another user could not be stopped: ${left.join(", ")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the session, cleans up and exits when the run is cancelled or times out. The
|
||||
* steps are synchronous, and each runs whether or not the ones before it failed. Once
|
||||
* isFinishing returns true, only the runner's second signal does this.
|
||||
*/
|
||||
export function onCancel(
|
||||
steps: (() => void)[],
|
||||
isFinishing: () => boolean = () => false,
|
||||
): void {
|
||||
let cancelled = false;
|
||||
const cancel = (name: NodeJS.Signals) => {
|
||||
if (cancelled || (name === "SIGINT" && isFinishing())) return;
|
||||
cancelled = true;
|
||||
for (const step of [stopDescendants, ...steps]) {
|
||||
try {
|
||||
step();
|
||||
} catch (error) {
|
||||
// A message could hold anything, such as a value that was being written.
|
||||
const { code, name } = error as { code?: string; name?: string };
|
||||
console.error(`Error cleaning up the cancelled run (${code ?? name})`);
|
||||
}
|
||||
}
|
||||
process.exit(130);
|
||||
};
|
||||
process.on("SIGINT", cancel);
|
||||
process.on("SIGTERM", cancel);
|
||||
process.on("SIGBREAK", cancel); // The runner's second signal on Windows
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { runClaude } from "./run-claude";
|
||||
import { setupClaudeCodeSettings } from "./setup-claude-code-settings";
|
||||
import { validateEnvironmentVariables } from "./validate-env";
|
||||
import { installPlugins } from "./install-plugins";
|
||||
import { onCancel } from "./cancel";
|
||||
import { setExecutionFileOutputIfPresent } from "./execution-file";
|
||||
import { setupWorkloadIdentity } from "./workload-identity";
|
||||
import type { WorkloadIdentityHandle } from "./workload-identity";
|
||||
@@ -15,6 +16,14 @@ async function run() {
|
||||
delete process.env.BUN_RUNTIME_TRANSPILER_CACHE_PATH;
|
||||
|
||||
let workloadIdentity: WorkloadIdentityHandle | undefined;
|
||||
let isFinishing = false;
|
||||
onCancel(
|
||||
[
|
||||
() => workloadIdentity?.stop(),
|
||||
() => isFinishing || core.setOutput("conclusion", "failure"),
|
||||
],
|
||||
() => isFinishing,
|
||||
);
|
||||
try {
|
||||
// When workload identity federation is configured, fetch the GitHub OIDC
|
||||
// identity token and expose it to the CLI before validating auth env vars.
|
||||
@@ -62,6 +71,7 @@ async function run() {
|
||||
});
|
||||
|
||||
// Set outputs for the standalone base-action
|
||||
isFinishing = true;
|
||||
core.setOutput("conclusion", result.conclusion);
|
||||
if (result.executionFile) {
|
||||
core.setOutput("execution_file", result.executionFile);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.329",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
@@ -37,23 +37,23 @@
|
||||
|
||||
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]29", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.329", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.329", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.329", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.329", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.329", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.329", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.329", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.329" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-aKVIgPBmgNHBoNXUFG5eVJXudDd+amObxT6QH9b6R2yGKf4eisPZ3Ij5RSpkFHDvJvaZy8m1AJeEkbKSusTU/Q=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]31", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.331" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-ml/MPqgO95tG5zcApBFxEyoDk57d9htP09R8AtPbKPUCHpsobf84IjkN4zhGvQgk8zsA9dXoeMGrQcCc8gQE/w=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]29", "", { "os": "darwin", "cpu": "arm64" }, "sha512-SaVFEDYHofgKftJGX8Uf5oa1wG9d2E9QAQqEpSCtiJrt7Ih82Ekn9b4ir0GufgwoOKx5IOv/CnMsXIWRl9vWrg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PQrn7YTiSV5Bg+ueF2hNvswc+wI7YKC2c32XNedvs6vfMCUUnIlq93VEbZiRY23b+JIVkEm8gb1VhkJTjsYISQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]29", "", { "os": "darwin", "cpu": "x64" }, "sha512-nYtGrz5oe/SK8jMKr/JArzrjEBtTqLWlRBlGu6QLXBoXd4PB5Fdj+Nh7Idnf+LD8OwWz1fqXj8zt0HTIUMSvYA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]31", "", { "os": "darwin", "cpu": "x64" }, "sha512-dc3iB+CY3jDpKpDpmvYc4V+UKSkudY29iJ62p0s5TK3h+b7Wqa2Hv0bPow0LUs4ZzDUXxEtCEHzk9X29VfLovw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]29", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-QvIfyMfjiYU2wkMfQ+tXTSwK76pXh/xSgdAFuqcPOiM3qgfi1kImcCIy/0wUnm9HGn0GZLXu7x0/lBu/PNHxVg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-xiRxBxoM8Qa5fnjCFk5iFheL5GUroLuHPJ7UnD4v2Sv1tWxGoSL67AYnMZ6OdjMguZK09X4WlgOn1nL1m6NEOA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]29", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-aOf1nA8roGApMzfL/aoEMBDGi11ZKtNV7mvp6OmaU0pgC24qECBeSUdsUuQBu9Z97kf5PDCh12JhkeHVDK+4JA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KdIClOdBUIpvf4PTFe2qedtPCOM3tC/jbsjh8U6WXF0QS8VjYkP0QR9i2AXG1PSAnI24T5xTxQb1scPAgRTIUQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]29", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-TKHcN+kOwG1Q6meOhKu9ZCJPUsXRL4dgx07R1BPgm0vREPpsSxaET5w7LuCs4pLIQgATJdqj6hjWtejDhVszNA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-nfHSiLJdkpsVAFsXTriyW3r64gS1sp5zxvaoF2dmNqKixR4rf9ISDDi81gF9L1uk/bAEcBGRx34U6Itw+NYIEg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]29", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-0j1Pu/egb7tbZk570MOd9vUVSlHvxnoA9ccDMdrAFqFGq3qb20IdHf4AvXuo9sbksKFXTx9oeEsvD4iFrL+wlA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-CSeT1JF++Vckf6TSXjQeuSjQ/sJnoTVL/XX44v4jHNAtU5i22nI9b27E6wkzudYVxoRoLWIU00V05dXhYYCvlg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]29", "", { "os": "win32", "cpu": "arm64" }, "sha512-lv4VKGQnTWIVToeWNrpekWIzYeTAQtOzDGXsU7krUizvJl3X0J/KiqEUB1Yi/F9VcYs3Aiu81RWtKdATLM5nkA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "win32", "cpu": "arm64" }, "sha512-FsPHWUpgHBFgSZESwM53JsbEoQiWPnigSCyjSfHDyiWnH66e0NsuksuJ/Nu9qI8UVgBDh/y1NOnnd4eGrB3eFQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]29", "", { "os": "win32", "cpu": "x64" }, "sha512-Pyn2sQciPirZk9OVh6EshSra84OBk11kJyTXgDv/v5PbHU2n2I+BbBYWkTeHpWeLlfRI61LWkFHtqs9cYOLOkg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]31", "", { "os": "win32", "cpu": "x64" }, "sha512-AsLur4ov9MGTQTrnZ49ZDPasQ35U3X/rZDdF/rPhytN3h1F3w/0IkC6esW3OzldvPlci60QvggOLVGnFlUzdxw=="],
|
||||
|
||||
"@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=="],
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ The action doesn't give Claude tools for these. In [auto mode](./usage.md#permis
|
||||
|
||||
- **Submit PR Reviews**: Claude cannot submit formal GitHub PR reviews
|
||||
- **Approve PRs**: For security reasons, Claude cannot approve pull requests
|
||||
- **Push to Other Branches**: By default, Claude can only push to the branch it was set up on: a new branch for an issue or closed PR, or the branch of an open PR. For a PR from a fork, that is a `pr-N` branch in your repository, and the fork's branch is not updated. [Keep that branch out of CI that holds secrets](./security.md#running-code-from-pull-requests)
|
||||
- **Push to Other Branches**: By default, Claude can only push to the branch it was set up on: a new branch for an issue or closed PR, or the branch of an open PR. For a PR from a fork, which needs [`allow_fork_prs`](./security.md#pull-requests-from-forks) set to `true`, that is a `pr-N` branch in your repository, and the fork's branch is not updated. [Keep that branch out of CI that holds secrets](./security.md#running-code-from-pull-requests)
|
||||
- **Post Multiple Comments**: Claude only acts by updating its initial comment
|
||||
- **Execute Commands Outside Its Context**: Claude only has access to the repository and PR/issue context it's triggered in
|
||||
- **Run Bash Commands Unchecked**: A Bash command runs only if an allow rule covers it or the safety review passes it
|
||||
|
||||
@@ -69,6 +69,8 @@ jobs:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
```
|
||||
|
||||
The action skips pull requests from forks unless [`allow_fork_prs`](./security.md#pull-requests-from-forks) is `true`.
|
||||
|
||||
Perfect for automatically reviewing PRs from new team members, external contributors, or specific developers who need extra guidance. The action automatically runs in agent mode when a `prompt` is provided.
|
||||
|
||||
## Custom Prompt Templates
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ Yes! Claude can access GitHub Actions workflow runs, job logs, and test results
|
||||
actions: read
|
||||
```
|
||||
|
||||
Claude will then be able to analyze CI failures and help debug workflow issues. For running tests locally before commits, you can still instruct Claude to do so in your request, except on pull requests whose author does not have write access. For pull requests from forks, see [Security](./security.md#running-code-from-pull-requests) for another way to get test results.
|
||||
Claude will then be able to analyze CI failures and help debug workflow issues. For running tests locally before commits, you can still instruct Claude to do so in your request, except on pull requests whose author does not have write access. For pull requests from forks, which need `allow_fork_prs: "true"`, see [Security](./security.md#running-code-from-pull-requests) for another way to get test results.
|
||||
|
||||
### Why does Claude only update one comment instead of creating new ones?
|
||||
|
||||
|
||||
+19
-11
@@ -26,7 +26,7 @@
|
||||
|
||||
## Using this action with `pull_request_target` or `workflow_run`
|
||||
|
||||
For `workflow_run` events, the action checks the repository access of the actor that started the upstream run (for example, the author of the fork pull request that triggered your CI workflow) in addition to the workflow actor. When the run came from a fork, it also checks the fork's owner, because GitHub credits a run to whoever caused it, such as a maintainer reopening the pull request. If any of these accounts does not have write access, the action stops before running Claude. To run on `workflow_run` events downstream of pull requests from contributors without write access, add those users to `allowed_non_write_users` and pass `github_token: ${{ secrets.GITHUB_TOKEN }}` — see the notes on that input above and keep the workflow's permissions minimal.
|
||||
For `workflow_run` events, the action checks the repository access of the actor that started the upstream run (for example, the author of the fork pull request that triggered your CI workflow) in addition to the workflow actor. When the run came from a fork, it also checks the fork's owner, because GitHub credits a run to whoever caused it, such as a maintainer reopening the pull request. If any of these accounts does not have write access, the action stops before running Claude. The action skips a run from a fork unless [`allow_fork_prs`](#pull-requests-from-forks) is `true`. To run on `workflow_run` events downstream of pull requests from contributors without write access, also add those users to `allowed_non_write_users` and pass `github_token: ${{ secrets.GITHUB_TOKEN }}` — see the notes on that input above and keep the workflow's permissions minimal.
|
||||
|
||||
`pull_request_target` and `workflow_run` execute with the **base repository's secrets**. If your workflow checks out the PR head (`ref: ${{ github.event.pull_request.head.sha }}` for `pull_request_target`, `ref: ${{ github.event.workflow_run.head_sha }}` for `workflow_run`) into `$GITHUB_WORKSPACE` before this action, the action and Claude run with that checkout as the working directory.
|
||||
|
||||
@@ -65,23 +65,29 @@ Everything else in the working tree — including `package.json`, lockfiles, `Ma
|
||||
|
||||
On pull requests from authors without write access, the action also replaces what npm and Bun read from the repository root with the base branch's version, wherever the two differ: `.npmrc`, `bunfig.toml` and tracked files in `node_modules/`. In a `package.json` whose `name`, `bin`, `directories.bin` or `workspaces` change the commands it provides, only `name`, `bin`, `directories` and `workspaces` are replaced, or the whole file if it can't be understood, including in other directories if the base branch uses workspaces. The pull request's versions are kept under `.claude-pr/` for reading, except for `node_modules/`. Claude can't edit `.npmrc`, `bunfig.toml`, `node_modules/` or, where one was replaced, `package.json` on these pull requests, in any directory. Its Bash commands start in the repository root there, because a hook runs in the session's current directory and only the root's files are replaced. The replaced files stay in the working tree for later steps in the job, and if Claude stages everything, its commit can include them, as with the paths above. `restrict_untrusted_prs: false` turns this off.
|
||||
|
||||
On these pull requests, files and directories in the checkout that your workflow's inputs name also come from the base branch where the pull request changes them or a `.gitattributes` that applies to them: `settings`, `plugin_marketplaces`, and in `claude_args` `--settings`, `--mcp-config`, `--plugin-dir`, `--plugin-dir-no-mcp`, `--agents`, `--project-config-root`, `--system-prompt-file`, `--append-system-prompt-file` and `--append-subagent-system-prompt-file`. The pull request's versions are kept under `.claude-pr/` for reading, and Claude can't edit what these inputs name, apart from the paths listed above. The replaced files stay in the working tree here too. A file that only the pull request has is removed. The run stops if an input names the whole repository as a plugin or marketplace, except that a marketplace at the root works if all its plugins are in subdirectories, if it names a path with `..` after another directory, or if it names files in a submodule that the pull request has at another commit. What symbolic links lead to, files that other config names, for example in a `settings.json`, and executables are not covered. Git LFS files are written as pointers.
|
||||
|
||||
This doesn't cover other package managers, the `.env` files and `tsconfig.json` that Bun loads, other files that a hook's own command reads, or a git command that resets the working tree during the session, so keep hooks self-contained as described above. Files that git doesn't track, such as packages an earlier step installed, stay as they are. A file that is the same link on both branches is left as a link.
|
||||
|
||||
Note that the runtime executing the tool also reads project config. `bunx <tool>` runs the tool's script under `node` when `node` is on `PATH` (as it is on GitHub-hosted runners); when only Bun is available, Bun executes the script itself and reads `bunfig.toml` from the checkout — including `preload` entries — which comes from the PR head. On such runners, make sure `node` is on `PATH` for the hook, and treat `bunfig.toml` and `.npmrc` in the checkout as PR-controlled runtime config on pull requests from authors with write access.
|
||||
|
||||
### Refusing pull requests from forks
|
||||
<a id="refusing-pull-requests-from-forks"></a>
|
||||
|
||||
By default, someone with write access can have the action work on a pull request from a fork. If you don't need that, turn it off, so that the action itself never checks out a fork's code:
|
||||
### Pull requests from forks
|
||||
|
||||
By default, the action skips pull requests from forks, so that it never checks out a fork's code itself. To let someone with write access have it work on them, read [Running code from pull requests](#running-code-from-pull-requests), then opt in:
|
||||
|
||||
```yaml
|
||||
- uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
allow_fork_prs: "false"
|
||||
allow_fork_prs: "true"
|
||||
```
|
||||
|
||||
The action then skips a pull request whose branch is in another repository, or in a fork that was deleted. It does so for every event, including comments on the conversation, whoever opened the pull request and whether it is open or closed. It also skips `workflow_run` events for a fork's run. It logs a warning, checks nothing out and doesn't start Claude, and the step succeeds without Claude's outputs, so a required check that only runs the action passes. Any value other than `true` turns forks off, including an empty one.
|
||||
Without that, the action skips a pull request whose branch is in another repository, or in a fork that was deleted. It does so for every event that names the pull request, including comments on the conversation, whoever opened the pull request and whether it is open or closed. It also skips `workflow_run` events for a fork's run. It logs a warning, checks nothing out and doesn't start Claude, and the step succeeds without Claude's outputs, so a required check that only runs the action passes without a review. A later step that needs the action's outputs has to handle empty ones. Any value other than `true` turns forks off, including an empty one.
|
||||
|
||||
For a comment on the conversation, the action asks GitHub where the branch is, after it has checked the commenter's write access. The token needs `pull-requests: read` for that. If the answer can't be read, the run fails before anything is checked out.
|
||||
Where a fork's event comes with credentials, the action first checks write access and, for a bot, `allowed_bots`, and a run that those checks refuse fails instead of being skipped. This covers comments on the conversation, `pull_request_target` and `workflow_run`, and in a private repository other events that get a token or the Anthropic secrets.
|
||||
|
||||
For a comment on the conversation that triggers it, the action asks GitHub where the branch is, after it has checked the commenter's write access. It does so for pull requests from your own repository too, so the token needs `pull-requests: read`. If the answer can't be read, the run fails before anything is checked out.
|
||||
|
||||
This covers what the action does with the event that started it. It doesn't cover:
|
||||
|
||||
@@ -91,6 +97,8 @@ This covers what the action does with the event that started it. It doesn't cove
|
||||
- **Commits already in your repository**, such as a `pr-N` branch from an earlier run, or a fork's commits that someone pushed to a branch of yours.
|
||||
- **Text.** Issues and comments from outside contributors still reach Claude.
|
||||
|
||||
**Upgrading:** `allow_fork_prs` used to default to `true`. Workflows that use a floating tag or branch such as `@v1` or `@main` get the new default without changing anything. If yours relied on Claude working on pull requests from forks, including your team's own forks, or on `workflow_run` events for a fork's run, set `allow_fork_prs: "true"`. This is needed with `allowed_non_write_users` too. Otherwise, a required check on those pull requests can now pass without Claude having run. If you already set it to `"false"`, runs with credentials that the write and bot checks refuse now fail where they used to be skipped. If it runs on comments on pull requests with a token of its own, check that the token has `pull-requests: read`.
|
||||
|
||||
### Running code from pull requests
|
||||
|
||||
A command that runs repository code (`npm install`, `bun test`, `make`) runs whatever the checkout contains, in a job that holds your workflow's tokens. Tag mode checks out the pull request's head, so on a pull request from an outside contributor that code is theirs, even when a maintainer triggered the run.
|
||||
@@ -103,13 +111,13 @@ By default, when the pull request's author does not have write access, the actio
|
||||
- **Text can still steer Claude.** On an issue or a trusted author's pull request these commands stay allowed, so text from an outside contributor could try to get Claude to edit a file and then run it. Keep the rules you grant in `claude_args` as narrow as you can.
|
||||
- **Other broad rules weaken the protections.** `Write` lets Claude write outside the workspace, and `Bash(git:*)` can still run programs through forms this list does not deny, such as `git rebase --exec`. Avoid them in workflows that handle outside contributions.
|
||||
|
||||
**Pushes on pull requests from forks:** in tag mode on an open pull request from a fork, Claude pushes to `pr-N` in your repository. That branch holds the fork's commits as well as Claude's, and GitHub's limits on runs from forks don't apply to it. A workflow or other CI that builds it runs the contributor's code and can have your secrets.
|
||||
**Pushes on pull requests from forks:** with `allow_fork_prs: "true"`, in tag mode on an open pull request from a fork, Claude pushes to `pr-N` in your repository. That branch holds the fork's commits as well as Claude's, and GitHub's limits on runs from forks don't apply to it. A workflow or other CI that builds it runs the contributor's code and can have your secrets.
|
||||
|
||||
- Keep `pr-*` out of CI that holds secrets, for example with `branches-ignore: ["pr-*"]` on `push` triggers, and check CI outside GitHub too.
|
||||
- Don't deploy or release from `pr-N`. Review the fork's commits before you merge the branch or open a pull request from it, and delete it when you are done.
|
||||
- To stop Claude's pushes in a workflow, on all pull requests and issues, add `--disallowedTools "Bash(git push:*)"` to `claude_args`. With `use_commit_signing`, also deny `mcp__github_file_ops`.
|
||||
|
||||
**Getting test results:** on pull requests from forks, run the tests in a separate `pull_request` workflow that needs no secrets, and let Claude read the outcome. The pull request's code then runs outside the job that holds Claude's tokens, which is not the case with `restrict_untrusted_prs: false`.
|
||||
**Getting test results:** if you [allow pull requests from forks](#pull-requests-from-forks), run their tests in a separate `pull_request` workflow that needs no secrets, and let Claude read the outcome. The pull request's code then runs outside the job that holds Claude's tokens, which is not the case with `restrict_untrusted_prs: false`.
|
||||
|
||||
1. In the test workflow, set `permissions: contents: read`. GitHub also limits the token to read access and withholds secrets on pull requests from forks of a public repository. That limit is the real protection, because a pull request can edit the workflow file.
|
||||
2. Set your repository to require approval for all external contributors. Review the changes, including workflow files, and then approve the runs. GitHub doesn't ask for approval on pull requests from members of your organization.
|
||||
@@ -128,7 +136,7 @@ Bots often open pull requests from branches in your own repository. Runs there u
|
||||
|
||||
Steps that run after Claude, including post steps such as `actions/checkout`'s cleanup, trust `GITHUB_ENV`, `GITHUB_PATH` and git's config files. When the session ends, the action restores those files, including config pulled in through `include.path`, to how they were before it started, and logs a warning naming any it changed. A session therefore can't pass environment variables to later steps through `GITHUB_ENV`, and `git config` changes it made, such as the upstream that `git push -u` records, don't last. Use `GITHUB_OUTPUT` or `--json-schema` to pass results on. What a session writes to `GITHUB_OUTPUT` and `GITHUB_STEP_SUMMARY` is kept, unless it replaced the file with a link or something else that isn't a file.
|
||||
|
||||
While Claude runs, and for the action's own git commands afterwards, git ignores `core.fsmonitor`. Git hooks are off for the action's own commits after the session, and from before the checkout on pull requests that `restrict_untrusted_prs` applies to. During the session these are set in the repository's git config and by the wrapper scripts. Global git config also sets `safe.bareRepository=explicit` for the session, so git won't use a repository it finds in a folder that has no `.git`. A workflow that has Claude work in a bare repository needs to pass `--git-dir`. If a run is cancelled before it restores this, the setting stays in the global config of a self-hosted runner that keeps its home directory. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
|
||||
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 killed before it restores this, the setting stays in the global config of a self-hosted runner that keeps its home directory. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
|
||||
|
||||
The action's own git commands use `safe.bareRepository=explicit` too. If the action starts in a bare repository, it doesn't set this before the session, unless `restrict_untrusted_prs` applies. On pull requests that `restrict_untrusted_prs` applies to, the action also checks out the pull request with `GIT_LFS_SKIP_SMUDGE=1`, so files that Git LFS hasn't downloaded yet stay as pointer files. The variable is set for that checkout only.
|
||||
|
||||
@@ -137,7 +145,7 @@ Claude's wrapper scripts for `git add`, `git rm`, `git commit` and `git push` al
|
||||
This has limits:
|
||||
|
||||
- It is not a sandbox. Code running on the runner, for example through an allowed `npm test`, can stop the action before it restores anything, or change the files later steps run, including the code of this and other actions. An allow rule for `Write` can reach those files too, so treat it like allowing code to run.
|
||||
- A run that is cancelled or times out during the session does not restore anything, and later `always()` and post steps still run.
|
||||
- When a run is cancelled or times out during the session, the action stops Claude and what it started, restores these files and has the app token revoked. It also drops what the session wrote to `GITHUB_OUTPUT`. Later `always()` and post steps still run, and the tracking comment isn't updated. Processes that run as another user or no longer belong to one that Claude started keep running, and on Windows Claude itself can too. Nothing is restored or revoked when the action doesn't get the runner's signal, as in a job with `container:`, or can't react before the runner kills it, as during a long `git fetch`.
|
||||
- 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.
|
||||
|
||||
@@ -150,7 +158,7 @@ This has limits:
|
||||
In its default configuration, **Claude does not create pull requests automatically** when responding to `@claude` mentions. Instead:
|
||||
|
||||
- Claude commits code changes to a new branch, or to the pull request's branch, through wrapper scripts in the action. A deny rule for `git add`, `git rm`, `git commit` or `git push` in `claude_args` also covers those scripts, including a narrower rule such as `git add -A:*`. A deny rule in a settings file doesn't, so pass it in `claude_args`
|
||||
- Claude's push command can't update any other branch. For a pull request from a fork, its branch is `pr-N` in your repository, which also holds the [fork's commits](#running-code-from-pull-requests), and the fork's branch is not updated
|
||||
- Claude's push command can't update any other branch. For a pull request from a fork, with `allow_fork_prs: "true"`, its branch is `pr-N` in your repository, which also holds the [fork's commits](#running-code-from-pull-requests), and the fork's branch is not updated
|
||||
- Branch protection on your default branch is still worth having: a workflow can allow other push commands, and a pull request opened from the default branch has that branch as its own
|
||||
- Claude provides a **link to the GitHub PR creation page** in its response
|
||||
- **The user must click the link and create the PR themselves**, ensuring human oversight before any code is proposed for merging
|
||||
|
||||
@@ -17,6 +17,8 @@ This guide provides complete, ready-to-use solutions for common automation scena
|
||||
|
||||
## Automatic PR Code Review
|
||||
|
||||
> The action skips pull requests from forks unless [`allow_fork_prs`](./security.md#pull-requests-from-forks) is `true`.
|
||||
|
||||
**When to use:** Automatically review every PR opened or updated in your repository.
|
||||
|
||||
### Basic Example (No Tracking)
|
||||
@@ -194,6 +196,8 @@ jobs:
|
||||
|
||||
**When to use:** Apply stricter review criteria for external or new contributors.
|
||||
|
||||
> As written, this doesn't run Claude on pull requests from forks, which is where first-time contributors' pull requests come from. See [Security](./security.md#pull-requests-from-forks) before you allow them.
|
||||
|
||||
**Complete Example:**
|
||||
|
||||
```yaml
|
||||
|
||||
+5
-5
@@ -84,7 +84,7 @@ jobs:
|
||||
| `include_comments_by_actor` | Comma-separated list of actor usernames to INCLUDE in comments. Supports the `*[bot]` wildcard to match all bot accounts. Empty (default) includes all actors | No | "" |
|
||||
| `exclude_comments_by_actor` | Comma-separated list of actor usernames to EXCLUDE from comments. Supports the `*[bot]` wildcard to match all bot accounts. If an actor matches both lists, exclusion takes priority | No | "" |
|
||||
| `allowed_bots` | Comma-separated list of allowed bot usernames, or '\*' to allow all bots. Empty string (default) allows no bots. **⚠️ On public repos with `'*'`, external Apps may be able to invoke this action.** See [Security](./security.md) | No | "" |
|
||||
| `allow_fork_prs` | Whether to run on pull requests from forks, and on `workflow_run` events for a fork's run. With any value other than `true`, the action skips them. See [Security](./security.md#refusing-pull-requests-from-forks). | No | `true` |
|
||||
| `allow_fork_prs` | Set to `true` to run on pull requests from forks, and on `workflow_run` events for a fork's run. By default, and with any other value, the action skips them. See [Security](./security.md#pull-requests-from-forks). | No | `false` |
|
||||
| `restrict_untrusted_prs` | On pull requests whose author does not have write access, deny commands that commonly run code from the checkout, even if `claude_args` allows them. See [Security](./security.md#running-code-from-pull-requests). | No | `true` |
|
||||
| `allowed_non_write_users` | **⚠️ RISKY**: Comma-separated list of usernames to allow without write permissions, or '\*' for all users. Only works with `github_token` input. See [Security](./security.md) | No | "" |
|
||||
| `path_to_claude_code_executable` | Optional path to a custom Claude Code executable. Skips automatic installation. Useful for Nix, custom containers, or specialized environments | No | "" |
|
||||
@@ -255,7 +255,7 @@ Get validated JSON results from Claude that automatically become GitHub Action o
|
||||
--json-schema '{"type":"object","properties":{"is_flaky":{"type":"boolean"},"confidence":{"type":"number"},"summary":{"type":"string"}},"required":["is_flaky"]}'
|
||||
|
||||
- name: Retry if flaky
|
||||
if: fromJSON(steps.analyze.outputs.structured_output).is_flaky == true
|
||||
if: fromJSON(steps.analyze.outputs.structured_output || '{}').is_flaky == true
|
||||
run: gh workflow run CI
|
||||
```
|
||||
|
||||
@@ -268,14 +268,14 @@ Get validated JSON results from Claude that automatically become GitHub Action o
|
||||
|
||||
### Accessing Structured Outputs
|
||||
|
||||
All structured output fields are available in the `structured_output` output as a JSON string:
|
||||
All structured output fields are available in the `structured_output` output as a JSON string. It is empty when the action skips the run, which is why these expressions fall back to `'{}'`. Test fields against `true`, because a missing field also equals `false`:
|
||||
|
||||
**In GitHub Actions expressions:**
|
||||
|
||||
```yaml
|
||||
if: |
|
||||
fromJSON(steps.analyze.outputs.structured_output).is_flaky == true &&
|
||||
fromJSON(steps.analyze.outputs.structured_output).confidence >= 0.7
|
||||
fromJSON(steps.analyze.outputs.structured_output || '{}').is_flaky == true &&
|
||||
fromJSON(steps.analyze.outputs.structured_output || '{}').confidence >= 0.7
|
||||
run: ./retry-tests.sh
|
||||
```
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ on:
|
||||
|
||||
jobs:
|
||||
review-by-author:
|
||||
# Only run for PRs from specific authors
|
||||
# Only run for PRs from specific authors. The action skips PRs from forks by
|
||||
# default: see docs/security.md.
|
||||
if: |
|
||||
github.event.pull_request.user.login == 'developer1' ||
|
||||
github.event.pull_request.user.login == 'developer2' ||
|
||||
|
||||
@@ -17,7 +17,10 @@ permissions:
|
||||
jobs:
|
||||
detect-flaky:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
|
||||
# The action skips a fork's run by default, so skip it here too
|
||||
if: >-
|
||||
github.event.workflow_run.conclusion == 'failure' &&
|
||||
github.event.workflow_run.head_repository.id == github.event.repository.id
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.329",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
|
||||
@@ -6,7 +6,7 @@ export function collectActionInputsPresence(): string {
|
||||
base_branch: "",
|
||||
branch_prefix: "claude/",
|
||||
allowed_bots: "",
|
||||
allow_fork_prs: "true",
|
||||
allow_fork_prs: "false",
|
||||
restrict_untrusted_prs: "true",
|
||||
mode: "tag",
|
||||
model: "",
|
||||
|
||||
+75
-14
@@ -16,6 +16,7 @@ import {
|
||||
checkBotActorPullRequestAuthor,
|
||||
checkWritePermissions,
|
||||
} from "../github/validation/permissions";
|
||||
import { checkHumanActor } from "../github/validation/actor";
|
||||
import {
|
||||
isCommentOnRefusedForkPr,
|
||||
isRefusedForkEvent,
|
||||
@@ -56,6 +57,10 @@ import {
|
||||
restoreToolConfigFromBase,
|
||||
toolConfigDenyRules,
|
||||
} from "../github/operations/tool-config";
|
||||
import {
|
||||
namedConfigPaths,
|
||||
restoreConfigPathsFromBase,
|
||||
} from "../github/operations/config-paths";
|
||||
import { validateBranchName } from "../github/operations/branch";
|
||||
import type { BranchInfo } from "../github/operations/branch";
|
||||
import { collectActionInputsPresence } from "./collect-inputs";
|
||||
@@ -70,6 +75,7 @@ import { validateEnvironmentVariables } from "../../base-action/src/validate-env
|
||||
import { setupClaudeCodeSettings } from "../../base-action/src/setup-claude-code-settings";
|
||||
import { installPlugins } from "../../base-action/src/install-plugins";
|
||||
import { preparePrompt } from "../../base-action/src/prepare-prompt";
|
||||
import { onCancel } from "../../base-action/src/cancel";
|
||||
import { runClaude } from "../../base-action/src/run-claude";
|
||||
import type { ClaudeRunResult } from "../../base-action/src/run-claude-sdk";
|
||||
import { setExecutionFileOutputIfPresent } from "../../base-action/src/execution-file";
|
||||
@@ -105,7 +111,7 @@ async function installClaudeCode(): Promise<string> {
|
||||
return customExecutable;
|
||||
}
|
||||
|
||||
const claudeCodeVersion = "2.1.329";
|
||||
const claudeCodeVersion = "2.1.331";
|
||||
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
|
||||
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
@@ -176,7 +182,7 @@ async function writeStepSummary(executionFile: string): Promise<void> {
|
||||
}
|
||||
|
||||
const FORK_REFUSED =
|
||||
"Skipped, because allow_fork_prs is not true and this pull request or workflow run is from a fork.";
|
||||
"Skipped, because allow_fork_prs is not true and this pull request or workflow run is from a fork. To allow forks, read 'Pull requests from forks' in docs/security.md in anthropics/claude-code-action, then set allow_fork_prs: \"true\".";
|
||||
|
||||
async function run() {
|
||||
// Bun has read this by now, and it's only for the action's own scripts
|
||||
@@ -198,13 +204,52 @@ async function run() {
|
||||
let restoredConfigPaths: string[] = [];
|
||||
// Track whether we've completed prepare phase, so we can attribute errors correctly
|
||||
let prepareCompleted = false;
|
||||
// Set while a session could be running
|
||||
let restoreSessionFiles: ReturnType<typeof snapshotSessionFiles> | undefined;
|
||||
let isFinishing = false;
|
||||
|
||||
// Revoking the app token depends on this output, and a session can write it.
|
||||
const keepRevocationOn = () =>
|
||||
core.setOutput("skipped_due_to_workflow_validation_mismatch", "false");
|
||||
|
||||
onCancel(
|
||||
[
|
||||
() => restoreSessionFiles?.({ cancelled: true }),
|
||||
() => restoreSessionFiles && keepRevocationOn(),
|
||||
// The step that revokes the app token reads it from here.
|
||||
() => githubToken && core.setOutput("github_token", githubToken),
|
||||
() => core.setOutput("branch_name", claudeBranch),
|
||||
// A session can write this one too.
|
||||
() => core.setOutput("conclusion", claudeSuccess ? "success" : "failure"),
|
||||
clearSessionState,
|
||||
() => workloadIdentity?.stop(),
|
||||
],
|
||||
() => isFinishing,
|
||||
);
|
||||
|
||||
try {
|
||||
// Phase 1: Prepare
|
||||
const actionInputsPresent = collectActionInputsPresence();
|
||||
context = parseGitHubContext();
|
||||
|
||||
// Before a token, which GitHub doesn't give to some of these events
|
||||
if (isRefusedForkEvent(context)) {
|
||||
// A fork's event with no credentials is skipped before a token is needed. One that
|
||||
// has them goes through the actor checks first: a run those refuse must fail, as
|
||||
// later steps in the job could use the credentials. pull_request_target and
|
||||
// workflow_run always have them. Other events from forks can have them only in a
|
||||
// private repository, depending on its settings.
|
||||
const isRefusedFork = isRefusedForkEvent(context);
|
||||
const hasRepositoryCredentials =
|
||||
isWorkflowRunEvent(context) ||
|
||||
process.env.GITHUB_EVENT_NAME === "pull_request_target" ||
|
||||
((context.payload.repository as { private?: boolean } | undefined)
|
||||
?.private === true &&
|
||||
!!(
|
||||
process.env.OVERRIDE_GITHUB_TOKEN ||
|
||||
process.env.ACTIONS_ID_TOKEN_REQUEST_URL ||
|
||||
process.env.ANTHROPIC_API_KEY ||
|
||||
process.env.CLAUDE_CODE_OAUTH_TOKEN
|
||||
));
|
||||
if (isRefusedFork && !hasRepositoryCredentials) {
|
||||
core.warning(FORK_REFUSED);
|
||||
return;
|
||||
}
|
||||
@@ -264,12 +309,6 @@ async function run() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Before the action checks anything out
|
||||
if (await isCommentOnRefusedForkPr(octokit.rest, context)) {
|
||||
core.warning(FORK_REFUSED);
|
||||
return;
|
||||
}
|
||||
|
||||
const botActorAllowed = await checkBotActorPullRequestAuthor(
|
||||
octokit.rest,
|
||||
context,
|
||||
@@ -282,6 +321,17 @@ async function run() {
|
||||
);
|
||||
}
|
||||
|
||||
// Before the action checks anything out
|
||||
if (
|
||||
isRefusedFork ||
|
||||
(await isCommentOnRefusedForkPr(octokit.rest, context))
|
||||
) {
|
||||
// Prepare would have refused a bot that isn't allowed
|
||||
await checkHumanActor(octokit.rest, context);
|
||||
core.warning(FORK_REFUSED);
|
||||
return;
|
||||
}
|
||||
|
||||
// Run prepare
|
||||
// Commands that run checkout code are denied on PRs from authors without write
|
||||
// access. Hooks go off here, before the action checks out such a PR's head, and
|
||||
@@ -332,6 +382,7 @@ async function run() {
|
||||
const isUntrustedCheckout =
|
||||
checkedOutPrHead && untrustedPrDisallowedTools.length > 0;
|
||||
let restoredToolConfig: string[] = [];
|
||||
let configPathDenyRules: string[] = [];
|
||||
|
||||
// On PRs, .claude/ and .mcp.json in the checkout are attacker-controlled.
|
||||
// Restore them from a trusted branch before the CLI reads them.
|
||||
@@ -373,7 +424,15 @@ async function run() {
|
||||
// Before plugins are installed, which can already start package managers here.
|
||||
if (isUntrustedCheckout) {
|
||||
restoredToolConfig = restoreToolConfigFromBase(configBranch);
|
||||
restoredConfigPaths.push(...restoredToolConfig);
|
||||
const configPaths = restoreConfigPathsFromBase(
|
||||
configBranch,
|
||||
namedConfigPaths(prepareResult.claudeArgs),
|
||||
);
|
||||
configPathDenyRules = configPaths.denyRules;
|
||||
restoredConfigPaths.push(
|
||||
...restoredToolConfig,
|
||||
...configPaths.replaced,
|
||||
);
|
||||
}
|
||||
if (isOtherBranch) {
|
||||
// A branch from the base has none of the pull request's version of them.
|
||||
@@ -407,6 +466,7 @@ async function run() {
|
||||
? [
|
||||
...untrustedPrDisallowedTools,
|
||||
...toolConfigDenyRules(restoredToolConfig),
|
||||
...configPathDenyRules,
|
||||
]
|
||||
: [];
|
||||
|
||||
@@ -416,7 +476,7 @@ async function run() {
|
||||
process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR = "1";
|
||||
}
|
||||
|
||||
const restoreSessionFiles = snapshotSessionFiles(() =>
|
||||
restoreSessionFiles = snapshotSessionFiles(() =>
|
||||
prepareGitForSession({ hooks: hooksOff }),
|
||||
);
|
||||
|
||||
@@ -437,8 +497,8 @@ async function run() {
|
||||
// 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");
|
||||
keepRevocationOn();
|
||||
restoreSessionFiles = undefined;
|
||||
}
|
||||
|
||||
claudeSuccess = claudeResult.conclusion === "success";
|
||||
@@ -466,6 +526,7 @@ async function run() {
|
||||
core.setFailed(`Action failed with error: ${redactSecrets(errorMessage)}`);
|
||||
} finally {
|
||||
// Phase 4: Cleanup (always runs)
|
||||
isFinishing = true;
|
||||
clearSessionState();
|
||||
|
||||
// Stop refreshing the workload identity token file and delete the token
|
||||
|
||||
@@ -37,7 +37,7 @@ export async function checkAndCommitOrDeleteBranch(
|
||||
// .claude/settings.json. Excluding those there would silently drop the work.
|
||||
const pathspecArgs =
|
||||
restoredConfigPaths.length > 0
|
||||
? ["--", ".", ...restoredConfigPaths.map((p) => `:(exclude)${p}`)]
|
||||
? ["--", ".", ...restoredConfigPaths.map((p) => `:(exclude,literal)${p}`)]
|
||||
: [];
|
||||
|
||||
if (pathspecArgs.length > 0) {
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
import * as core from "@actions/core";
|
||||
import { mkdirSync, symlinkSync, writeFileSync } from "fs";
|
||||
import { isAbsolute, posix, relative, resolve, sep } from "path";
|
||||
import {
|
||||
ACCUMULATE_DELIMITER,
|
||||
parseClaudeArgsToExtraArgs,
|
||||
} from "../../../base-action/src/parse-sdk-options";
|
||||
import { SENSITIVE_PATHS } from "./restore-config";
|
||||
import {
|
||||
fold,
|
||||
fsPath,
|
||||
git,
|
||||
hasRealParents,
|
||||
isFile,
|
||||
isLink,
|
||||
isSubmodule,
|
||||
onDisk,
|
||||
readBlobs,
|
||||
remove,
|
||||
snapshotForReview,
|
||||
} from "./tool-config";
|
||||
import type { Entry } from "./tool-config";
|
||||
|
||||
// The arguments that name config in files.
|
||||
const FILE_FLAGS = new Set([
|
||||
"agents",
|
||||
"append-subagent-system-prompt-file",
|
||||
"append-system-prompt-file",
|
||||
"mcp-config",
|
||||
"plugin-dir",
|
||||
"plugin-dir-no-mcp",
|
||||
"settings",
|
||||
"system-prompt-file",
|
||||
]);
|
||||
// Only the project's config in this directory.
|
||||
const PROJECT_FLAG = "project-config-root";
|
||||
const MARKETPLACE_FILE = ".claude-plugin/marketplace.json";
|
||||
|
||||
// Git's entries by path, relative to the working directory. As in tool-config.ts,
|
||||
// Latin-1 characters stand for bytes.
|
||||
type Entries = Map<string, Entry>;
|
||||
|
||||
const toBytes = (path: string): string => Buffer.from(path).toString("latin1");
|
||||
const toText = (path: string): string => fsPath(path).toString();
|
||||
const isSameOrInside = (path: string, parent: string): boolean =>
|
||||
path === parent || path.startsWith(`${parent}/`);
|
||||
const isSensitive = (path: string): boolean =>
|
||||
SENSITIVE_PATHS.some((sensitive) => isSameOrInside(path, sensitive));
|
||||
|
||||
// Each is "<mode> <other fields>\t<path>".
|
||||
function parseEntries(listing: Buffer, oidField: number): Entries {
|
||||
const entries: Entries = new Map();
|
||||
for (const line of listing.toString("latin1").split("\0")) {
|
||||
const [info, path] = line.split(/\t(.*)/s);
|
||||
if (!info || !path) continue;
|
||||
const fields = info.split(" ");
|
||||
entries.set(path, { mode: fields[0]!, oid: fields[oidField]! });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* A path as it is relative to the checkout, or undefined if it's outside. Links are not
|
||||
* followed, because the pull request can change them. The workspace can have another
|
||||
* name than the working directory, which is free of links.
|
||||
*/
|
||||
function inCheckout(path: string): string | undefined {
|
||||
const roots = [process.cwd(), process.env.GITHUB_WORKSPACE || process.cwd()];
|
||||
for (const root of roots) {
|
||||
const inRoot = relative(root, resolve(path));
|
||||
if (!isAbsolute(inRoot) && inRoot.split(sep)[0] !== "..") {
|
||||
return toBytes(inRoot.split(sep).join("/"));
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isJson(value: string): boolean {
|
||||
if (!value.startsWith("{")) return false;
|
||||
try {
|
||||
JSON.parse(value);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const WHOLE_REPOSITORY =
|
||||
"The workflow takes a plugin from the whole repository, which can't come from a trusted branch on a pull request from an author without write access. Put the plugin in a subdirectory, or set restrict_untrusted_prs to false.";
|
||||
const UNCLEAR_PATH =
|
||||
'A path in the workflow\'s inputs has ".." after another name, so it can\'t come from a trusted branch on a pull request from an author without write access. Write it without "..", or set restrict_untrusted_prs to false.';
|
||||
|
||||
const OTHER_SUBMODULE =
|
||||
"The pull request and the trusted branch have different commits of a submodule that the workflow's inputs name, so that branch's version can't be used. Bring the pull request up to date, put the files in the repository, or set restrict_untrusted_prs to false.";
|
||||
|
||||
class PathError extends Error {}
|
||||
|
||||
/**
|
||||
* Whether a path has ".." after a name in the checkout, which the pull request could
|
||||
* make a link.
|
||||
*/
|
||||
function goesBack(path: string): boolean {
|
||||
const parts = path.split(/[\\/]/);
|
||||
return parts.some(
|
||||
(part, index) =>
|
||||
part === ".." && !!inCheckout(parts.slice(0, index).join("/") || "/"),
|
||||
);
|
||||
}
|
||||
|
||||
type NamedPaths = { paths: string[]; marketplaces: string[] };
|
||||
|
||||
/** The paths in this checkout that the workflow's inputs name as config. */
|
||||
export function namedConfigPaths(claudeArgs: string): NamedPaths {
|
||||
const args = Object.entries(parseClaudeArgsToExtraArgs(claudeArgs)).flatMap(
|
||||
([key, value]) => {
|
||||
const [flag, inlineValue] = key.split(/=(.*)/s);
|
||||
return [...(value?.split(ACCUMULATE_DELIMITER) ?? []), inlineValue ?? ""]
|
||||
.map((path) => path.trim())
|
||||
.flatMap((path) => (path ? [{ flag: flag!, path }] : []));
|
||||
},
|
||||
);
|
||||
const fromArgs = args.flatMap(({ flag, path }) =>
|
||||
flag === PROJECT_FLAG
|
||||
? SENSITIVE_PATHS.map((name) => `${path}/${name}`)
|
||||
: FILE_FLAGS.has(flag)
|
||||
? [path]
|
||||
: [],
|
||||
);
|
||||
const toPaths = (values: string[]): string[] =>
|
||||
values
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => value && !isJson(value))
|
||||
.flatMap((value) => {
|
||||
if (goesBack(value)) throw new PathError(UNCLEAR_PATH);
|
||||
const path = inCheckout(value);
|
||||
return path === undefined ? [] : [path];
|
||||
});
|
||||
return {
|
||||
paths: toPaths([process.env.INPUT_SETTINGS ?? "", ...fromArgs]),
|
||||
marketplaces: toPaths(
|
||||
(process.env.INPUT_PLUGIN_MARKETPLACES ?? "")
|
||||
.split("\n")
|
||||
.filter((entry) => /^\s*((\.\.?)?\/|[a-z]:[\\/])/i.test(entry)),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
type RestoredPaths = { replaced: string[]; denyRules: string[] };
|
||||
|
||||
/**
|
||||
* On a pull request from an author without write access, takes the files that the
|
||||
* workflow's inputs name from the base branch. Links are restored but not followed. Only
|
||||
* files that the pull request changes, or whose .gitattributes it changes, are replaced,
|
||||
* so what an earlier step created or changed stays. restoreConfigFromBase must run
|
||||
* first, because it fetches the base branch. Like it, this changes the working tree and
|
||||
* not the index.
|
||||
*
|
||||
* @returns The paths that were replaced, all named by the base branch or the workflow,
|
||||
* and rules that stop a session from editing these and the rest of that config.
|
||||
* @throws If the base branch's version can't be put in place.
|
||||
*/
|
||||
export function restoreConfigPathsFromBase(
|
||||
baseBranch: string,
|
||||
named: NamedPaths,
|
||||
): RestoredPaths {
|
||||
if (named.paths.length + named.marketplaces.length === 0) {
|
||||
return { replaced: [], denyRules: [] };
|
||||
}
|
||||
let restored: RestoredPaths;
|
||||
try {
|
||||
restored = restoreConfigPaths(`refs/remotes/origin/${baseBranch}`, named);
|
||||
} catch (error) {
|
||||
if (error instanceof PathError) throw error;
|
||||
const { code, status } = error as { code?: string; status?: number };
|
||||
core.warning(
|
||||
`Could not replace config files (${code ?? `exit code ${status ?? "unknown"}`})`,
|
||||
);
|
||||
throw new Error(
|
||||
"Could not use the trusted branch's version of the files that the workflow's inputs name",
|
||||
);
|
||||
}
|
||||
if (restored.replaced.length > 0) {
|
||||
core.warning(
|
||||
`The pull request and ${baseBranch} differ in files that the workflow's inputs name (${restored.replaced.join(", ")}), so that branch's version is used and Claude can't edit it. See docs/security.md.`,
|
||||
);
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
|
||||
function restoreConfigPaths(ref: string, named: NamedPaths): RestoredPaths {
|
||||
const base = parseEntries(git(["ls-tree", "-r", "-z", ref]), 2);
|
||||
const pr = parseEntries(git(["ls-files", "--stage", "-z"]), 1);
|
||||
|
||||
// The rest of Claude's config has been restored already.
|
||||
const targets = [
|
||||
...named.paths,
|
||||
...named.marketplaces.flatMap((path) => marketplacePaths(path, base)),
|
||||
]
|
||||
.map((path) => posix.join(path || ".").replace(/\/$/, ""))
|
||||
.filter((path) => !isSameOrInside(path, "..") && !isSensitive(path));
|
||||
if (targets.includes(".")) throw new PathError(WHOLE_REPOSITORY);
|
||||
|
||||
const replaced = replaceFiles([...new Set(targets)], base, pr).map(toText);
|
||||
return {
|
||||
replaced,
|
||||
denyRules: [...new Set([...targets.map(toText), ...replaced])]
|
||||
.map((path) => path.replace(/[\\*?[\]]/g, "\\$&"))
|
||||
.flatMap((path) => [`Edit(./${path})`, `Edit(./${path}/**)`]),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a local marketplace is made of. One at the root of the repository has only its
|
||||
* own plugins in other directories.
|
||||
*/
|
||||
function marketplacePaths(path: string, base: Entries): string[] {
|
||||
const isManifest = path.endsWith(".json");
|
||||
// The CLI takes the directory above the manifest's as the marketplace's root.
|
||||
if (isManifest && !path.includes("/")) return [path];
|
||||
const root = isManifest
|
||||
? posix.join(posix.dirname(path), "..")
|
||||
: path === ""
|
||||
? "."
|
||||
: path;
|
||||
if (root !== ".") return [root];
|
||||
|
||||
const manifest = isManifest ? path : MARKETPLACE_FILE;
|
||||
const own = isManifest ? path : posix.dirname(MARKETPLACE_FILE);
|
||||
const entry = base.get(manifest);
|
||||
// Without one that the base branch has, there is nothing to take plugins from.
|
||||
if (!entry || !isFile(entry)) return [own];
|
||||
const { plugins, metadata } = JSON.parse(
|
||||
readBlobs([entry])
|
||||
.get(entry.oid)!
|
||||
.toString()
|
||||
.replace(/^\uFEFF/, ""),
|
||||
) as {
|
||||
plugins?: ({ source?: unknown } | null)[];
|
||||
metadata?: { pluginRoot?: unknown };
|
||||
};
|
||||
const pluginRoot =
|
||||
typeof metadata?.pluginRoot === "string" ? metadata.pluginRoot : "";
|
||||
const sources = (plugins ?? []).flatMap((plugin) =>
|
||||
typeof plugin?.source === "string" ? [plugin.source] : [],
|
||||
);
|
||||
return [
|
||||
own,
|
||||
...sources.flatMap((source) =>
|
||||
// A bare name can be in the marketplace's plugin root.
|
||||
[source, ...(pluginRoot ? [posix.join(pluginRoot, source)] : [])].map(
|
||||
(dir) => toBytes(posix.join(".", dir)),
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a path that differs from a target at most in case, or in how a character is
|
||||
* encoded, is in it or above it on this file system.
|
||||
*/
|
||||
function namesSameFile(name: string, target: string): boolean {
|
||||
const names = name.split("/");
|
||||
const targets = target.split("/");
|
||||
const spelled = [
|
||||
...targets.slice(0, names.length),
|
||||
...names.slice(targets.length),
|
||||
].join("/");
|
||||
if (name === spelled) return true;
|
||||
const [stats, other] = [onDisk(name), onDisk(spelled)];
|
||||
return !!stats && !!other && stats.ino === other.ino;
|
||||
}
|
||||
|
||||
/** The directories whose .gitattributes the pull request changes, ignoring case. */
|
||||
function changedAttributes(base: Entries, pr: Entries): string[] {
|
||||
const names = new Set([...base.keys(), ...pr.keys()]);
|
||||
return [...names].flatMap((name) =>
|
||||
fold(posix.basename(name)) === ".gitattributes" &&
|
||||
base.get(name)?.oid !== pr.get(name)?.oid
|
||||
? [fold(posix.dirname(name))]
|
||||
: [],
|
||||
);
|
||||
}
|
||||
|
||||
const isInside = (name: string, foldedDir: string): boolean =>
|
||||
foldedDir === "." || fold(name).startsWith(`${foldedDir}/`);
|
||||
|
||||
/** Puts the base branch's version of these paths in place. Returns those that differed. */
|
||||
function replaceFiles(targets: string[], base: Entries, pr: Entries): string[] {
|
||||
const foldedPr = [...pr.keys()].map((name) => [name, fold(name)] as const);
|
||||
const namesByTarget = new Map(
|
||||
targets.map((target) => {
|
||||
const folded = fold(target);
|
||||
const names = [
|
||||
...[...base.keys()].filter(
|
||||
(name) =>
|
||||
isSameOrInside(name, target) || isSameOrInside(target, name),
|
||||
),
|
||||
// A pull request can also have a file or link where the base branch has a
|
||||
// directory.
|
||||
...foldedPr.flatMap(([name, other]) =>
|
||||
(isSameOrInside(other, folded) || isSameOrInside(folded, other)) &&
|
||||
namesSameFile(name, target)
|
||||
? [name]
|
||||
: [],
|
||||
),
|
||||
];
|
||||
return [target, [...new Set(names)]] as const;
|
||||
}),
|
||||
);
|
||||
const attributes = changedAttributes(base, pr);
|
||||
const differs = (name: string): boolean => {
|
||||
const [ours, theirs] = [base.get(name), pr.get(name)];
|
||||
return (
|
||||
ours?.oid !== theirs?.oid ||
|
||||
ours?.mode !== theirs?.mode ||
|
||||
// Git can write even an unchanged file differently then.
|
||||
(isFile(theirs!) && attributes.some((dir) => isInside(name, dir)))
|
||||
);
|
||||
};
|
||||
const differing = [...namesByTarget].flatMap(([target, names]) => {
|
||||
// Names that differ only in case can be the same file.
|
||||
const folded = new Set(names.filter(differs).map(fold));
|
||||
const changed = names.filter((name) => folded.has(fold(name)));
|
||||
return changed.length > 0 ? [[target, changed] as const] : [];
|
||||
});
|
||||
const changed = [...new Set(differing.flatMap(([, names]) => names))];
|
||||
// Claude Code goes on without a plugin that is missing.
|
||||
if (changed.some((name) => base.has(name) && isSubmodule(base.get(name)!))) {
|
||||
throw new PathError(OTHER_SUBMODULE);
|
||||
}
|
||||
|
||||
// All of these go before anything is written. A directory where the pull request has
|
||||
// a file or link came from an earlier step.
|
||||
const removed = new Set(
|
||||
changed.filter((name) => {
|
||||
const entry = pr.get(name);
|
||||
const stats = entry && onDisk(name);
|
||||
return (
|
||||
stats &&
|
||||
(!stats.isDirectory() || isSubmodule(entry)) &&
|
||||
hasRealParents(name)
|
||||
);
|
||||
}),
|
||||
);
|
||||
for (const name of removed) {
|
||||
const entry = pr.get(name)!;
|
||||
if (entry.oid !== base.get(name)?.oid) snapshotForReview(name, entry);
|
||||
remove(name);
|
||||
}
|
||||
|
||||
// One that the pull request has but is not on disk was left out or deleted by the
|
||||
// workflow. What is on disk now came from an earlier step.
|
||||
const toWrite = changed.flatMap((name) => {
|
||||
const entry = base.get(name);
|
||||
const wanted = pr.has(name) ? removed.has(name) : true;
|
||||
return entry && !isSubmodule(entry) && wanted && !onDisk(name)
|
||||
? [{ name, entry }]
|
||||
: [];
|
||||
});
|
||||
const blobs = readBlobs(toWrite.map(({ entry }) => entry));
|
||||
for (const { name, entry } of toWrite) {
|
||||
if (!hasRealParents(name)) continue;
|
||||
const content = blobs.get(entry.oid);
|
||||
if (!content) throw new Error("missing object");
|
||||
mkdirSync(fsPath(posix.dirname(name)), { recursive: true });
|
||||
if (isLink(entry)) symlinkSync(content, fsPath(name));
|
||||
else {
|
||||
const mode = entry.mode === "100755" ? 0o755 : 0o644;
|
||||
writeFileSync(fsPath(name), content, { mode, flag: "wx" });
|
||||
}
|
||||
}
|
||||
// Where the pull request has a file above a target, that is gone too.
|
||||
return [
|
||||
...new Set(
|
||||
differing.flatMap(([target, names]) => [
|
||||
target,
|
||||
...names.filter((name) => target.startsWith(`${name}/`)),
|
||||
]),
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -216,28 +216,35 @@ function isItsOwnFile(before: FileSnapshot): boolean {
|
||||
/**
|
||||
* 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.
|
||||
* action runs git again. If the session was cancelled, that also drops the outputs it
|
||||
* wrote, because a half-written one would take the action's own with it. 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 {
|
||||
export function snapshotSessionFiles(
|
||||
beforeSession?: () => void,
|
||||
): (options?: { cancelled: boolean }) => 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 () => {
|
||||
return ({ cancelled } = { cancelled: false }) => {
|
||||
const restored: string[] = [];
|
||||
for (const [index, before] of snapshots.entries()) {
|
||||
try {
|
||||
const now = readSnapshot(before);
|
||||
if (before.keepsWrites && isItsOwnFile(before)) continue;
|
||||
const dropsWrites = cancelled && before.label === "GITHUB_OUTPUT";
|
||||
const ownFile = before.keepsWrites && isItsOwnFile(before);
|
||||
if (ownFile && !dropsWrites) continue;
|
||||
// The file it leads to can have the same content so far.
|
||||
const leadsElsewhere = before.keepsWrites && now.state === "file";
|
||||
const leadsElsewhere =
|
||||
before.keepsWrites && !ownFile && now.state === "file";
|
||||
if (!leadsElsewhere && isUnchanged(before, now)) continue;
|
||||
const changedBySession =
|
||||
leadsElsewhere || !isUnchanged(atStart[index]!, now);
|
||||
@@ -329,7 +336,9 @@ export function pinPushBranch(branch: string): void {
|
||||
export function pinRestoredPaths(paths: string[]): void {
|
||||
const pathspecs = paths.map((path) =>
|
||||
// Its commands are replaced in subdirectories too.
|
||||
path === "package.json" ? ":(top,glob)**/package.json" : `:(top)${path}`,
|
||||
path === "package.json"
|
||||
? ":(top,glob)**/package.json"
|
||||
: `:(top,literal)${path}`,
|
||||
);
|
||||
try {
|
||||
writeSessionFile(".restored-paths", `${pathspecs.join("\n")}\n`);
|
||||
|
||||
@@ -32,14 +32,14 @@ const ENCODING = "working-tree-encoding";
|
||||
const MAX_OUTPUT_BYTES = 1024 ** 3;
|
||||
const MAX_PACKAGE_JSON_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
type Entry = { mode: string; oid: string };
|
||||
export type Entry = { mode: string; oid: string };
|
||||
type Replacement = { path: string; entry: Entry; content?: Buffer };
|
||||
|
||||
// File names can be any bytes. Latin-1 keeps each one intact.
|
||||
const fsPath = (path: string): Buffer => Buffer.from(path, "latin1");
|
||||
const isFile = (entry: Entry): boolean => entry.mode.startsWith("100");
|
||||
const isLink = (entry: Entry): boolean => entry.mode === "120000";
|
||||
const isSubmodule = (entry: Entry): boolean => entry.mode === "160000";
|
||||
export const fsPath = (path: string): Buffer => Buffer.from(path, "latin1");
|
||||
export const isFile = (entry: Entry): boolean => entry.mode.startsWith("100");
|
||||
export const isLink = (entry: Entry): boolean => entry.mode === "120000";
|
||||
export const isSubmodule = (entry: Entry): boolean => entry.mode === "160000";
|
||||
|
||||
// No file name or content, which the pull request controls, reaches the log.
|
||||
function warn(what: string, error: unknown): void {
|
||||
@@ -47,7 +47,7 @@ function warn(what: string, error: unknown): void {
|
||||
core.warning(`${what} (${code ?? `exit code ${status ?? "unknown"}`})`);
|
||||
}
|
||||
|
||||
function git(args: string[], input: string | Buffer = ""): Buffer {
|
||||
export function git(args: string[], input: string | Buffer = ""): Buffer {
|
||||
return execFileSync("git", args, {
|
||||
stdio: ["pipe", "pipe", "ignore"],
|
||||
input,
|
||||
@@ -57,7 +57,7 @@ function git(args: string[], input: string | Buffer = ""): Buffer {
|
||||
}
|
||||
|
||||
// A parent that is a file or a looping link means there is nothing there.
|
||||
function onDisk(path: string) {
|
||||
export function onDisk(path: string) {
|
||||
try {
|
||||
return lstatSync(fsPath(path));
|
||||
} catch {
|
||||
@@ -66,7 +66,7 @@ function onDisk(path: string) {
|
||||
}
|
||||
|
||||
// File systems can ignore case, and some the way a character is encoded.
|
||||
const fold = (path: string): string =>
|
||||
export const fold = (path: string): string =>
|
||||
fsPath(path).toString().normalize("NFKC").toLowerCase();
|
||||
|
||||
/**
|
||||
@@ -97,14 +97,14 @@ function rootName(path: string): string | undefined {
|
||||
}
|
||||
|
||||
/** Whether no parent of a path is a link, which could lead out of the checkout. */
|
||||
function hasRealParents(path: string): boolean {
|
||||
export function hasRealParents(path: string): boolean {
|
||||
for (let dir = dirname(path); dir !== "."; dir = dirname(dir)) {
|
||||
if (onDisk(dir)?.isSymbolicLink()) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function remove(path: string): void {
|
||||
export function remove(path: string): void {
|
||||
rmSync(fsPath(path), { recursive: true, force: true });
|
||||
// An empty directory would stand in the way of a file of that name.
|
||||
try {
|
||||
@@ -150,7 +150,7 @@ function baseEntries(baseBranch: string): Map<string, Entry> {
|
||||
}
|
||||
|
||||
/** The stored content of each entry, which no .gitattributes has been applied to. */
|
||||
function readBlobs(entries: Entry[]): Map<string, Buffer> {
|
||||
export function readBlobs(entries: Entry[]): Map<string, Buffer> {
|
||||
const blobs = new Map<string, Buffer>();
|
||||
const oids = [...new Set(entries.map(({ oid }) => oid))];
|
||||
if (oids.length === 0) return blobs;
|
||||
@@ -282,7 +282,7 @@ function withBaseCommands(
|
||||
}
|
||||
|
||||
/** Keeps the pull request's version readable, as for the other restored config. */
|
||||
function snapshotForReview(path: string, entry: Entry): void {
|
||||
export function snapshotForReview(path: string, entry: Entry): void {
|
||||
if (!isFile(entry) || rootName(path) === "node_modules") return;
|
||||
try {
|
||||
const content = git(["cat-file", "blob", entry.oid]);
|
||||
|
||||
@@ -15,7 +15,7 @@ const isSameRepository = (head: Repository, base: Repository): boolean =>
|
||||
|
||||
// Only "true" allows forks, so a mistyped or empty value refuses them.
|
||||
export const forksAllowed = (): boolean =>
|
||||
(process.env.ALLOW_FORK_PRS ?? "true").trim().toLowerCase() === "true";
|
||||
process.env.ALLOW_FORK_PRS?.trim().toLowerCase() === "true";
|
||||
|
||||
/**
|
||||
* Whether allow_fork_prs is off and the event says that it is about a fork's pull
|
||||
|
||||
@@ -68,11 +68,11 @@ describe("action metadata", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("should allow fork pull requests by default and pass the input to the run step", () => {
|
||||
test("should refuse fork pull requests by default and pass the input to the run step", () => {
|
||||
const metadata = readMetadata("action.yml");
|
||||
|
||||
expect(metadata).toMatch(
|
||||
/^ allow_fork_prs:\n description: .+\n required: false\n default: "true"$/m,
|
||||
/^ allow_fork_prs:\n description: .+\n required: false\n default: "false"$/m,
|
||||
);
|
||||
expect(metadata).toMatch(
|
||||
/^ ALLOW_FORK_PRS: \$\{\{ inputs\.allow_fork_prs \}\}$/m,
|
||||
@@ -120,15 +120,15 @@ describe("action metadata", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test("should let Bun finish when the shell is interrupted", async () => {
|
||||
test("should let Bun clean up when the step is interrupted", async () => {
|
||||
const { output, exitCode } = await runStep(
|
||||
path,
|
||||
`exec "${process.execPath}" -e 'console.log("started"); setTimeout(() => console.log("finished"), 500)'`,
|
||||
`exec "${process.execPath}" -e 'process.once("SIGINT", () => { console.log("cleaned up"); process.exit(130) }); setTimeout(() => {}, 5000); console.log("started")'`,
|
||||
true,
|
||||
);
|
||||
|
||||
expect(output).toBe("started\nfinished\n");
|
||||
expect(exitCode).toBe(0);
|
||||
expect(output).toBe("started\ncleaned up\n");
|
||||
expect(exitCode).toBe(130);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { join } from "path";
|
||||
|
||||
const isRunning = (pid: number) => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
// A process that has ended but that nobody waited for still has an entry.
|
||||
return !/^\S+ \(.*\) Z/s.test(readFileSync(`/proc/${pid}/stat`, "utf8"));
|
||||
} catch (error) {
|
||||
return (error as { code?: string }).code === "ENOENT"
|
||||
? process.platform !== "linux"
|
||||
: false;
|
||||
}
|
||||
};
|
||||
|
||||
async function until(condition: () => boolean, what: string) {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
if (condition()) return;
|
||||
await Bun.sleep(50);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${what}`);
|
||||
}
|
||||
|
||||
// Like a session. Its child is in its own process group, and both ignore SIGTERM. A
|
||||
// third process takes SIGTERM as git does, which removes its lock files.
|
||||
const SESSION = `#!/bin/bash
|
||||
trap '' TERM INT
|
||||
perl -e 'use POSIX; POSIX::setsid(); sleep 300' &
|
||||
child=$!
|
||||
perl -e '$SIG{TERM} = sub { unlink "$ENV{TEST_DIR}/lock"; exit }; open(F, ">$ENV{TEST_DIR}/lock"); sleep 300' &
|
||||
git_like=$!
|
||||
echo "$$ $child $git_like" > "$TEST_DIR/pids"
|
||||
until [ -e "$TEST_DIR/lock" ]; do sleep 0.05; done
|
||||
echo 'ADDED=1' >> "$GITHUB_ENV"
|
||||
printf '%s\\n' skipped_due_to_workflow_validation_mismatch=true conclusion=success >> "$GITHUB_OUTPUT"
|
||||
eval "$IN_SESSION"
|
||||
touch "$TEST_DIR/started"
|
||||
while :; do sleep 1; done
|
||||
`;
|
||||
|
||||
const stepScript = (metadata: string) =>
|
||||
metadata
|
||||
.split(/^ - name: /m)
|
||||
.find((step) => step.includes("${GITHUB_ACTION_PATH}/src/"))!
|
||||
.match(/^ run: \|\n((?: {8}.*\n|\n)+)/m)![1]!
|
||||
.replace(/^ {8}/gm, "");
|
||||
|
||||
const parseOutputs = (file: string) =>
|
||||
Object.fromEntries(
|
||||
[
|
||||
...readFileSync(file, "utf8").matchAll(
|
||||
/^([^=\n]+?)(?:=|<<(\S+)\n)(.*)$(?:\n\2$)?/gm,
|
||||
),
|
||||
].map(([, name, , value]) => [name, value]),
|
||||
);
|
||||
|
||||
/** Runs an action's step, as the runner does, and cancels it during the session. */
|
||||
async function cancelStep(
|
||||
actionDir: string,
|
||||
{ signals = ["SIGINT"] as NodeJS.Signals[], inSession = ":" } = {},
|
||||
) {
|
||||
const source = join(import.meta.dir, "..", actionDir);
|
||||
const dir = mkdtempSync(join(tmpdir(), "cancel-"));
|
||||
const path = (file: string) => join(dir, file);
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
hostname: "127.0.0.1",
|
||||
fetch: () =>
|
||||
Response.json({ login: "writer", type: "User", value: "identity" }),
|
||||
});
|
||||
const pids = () =>
|
||||
existsSync(path("pids"))
|
||||
? [...readFileSync(path("pids"), "utf8").matchAll(/\d+/g)].map(Number)
|
||||
: [];
|
||||
let step: Bun.Subprocess | undefined;
|
||||
try {
|
||||
// The action keeps files for the session in its own directory.
|
||||
for (const name of ["repo", "bin", "outputs", "action", "action/scripts"]) {
|
||||
mkdirSync(path(name));
|
||||
}
|
||||
for (const name of readdirSync(source)) {
|
||||
if (name === "scripts") continue;
|
||||
symlinkSync(join(source, name), path(join("action", name)));
|
||||
}
|
||||
execFileSync("git", ["init", "-q", path("repo")]);
|
||||
for (const file of ["outputs/output", "env", "path"]) {
|
||||
writeFileSync(path(file), "");
|
||||
}
|
||||
writeFileSync(path("event.json"), JSON.stringify({ inputs: {} }));
|
||||
writeFileSync(path("prompt.txt"), "x");
|
||||
writeFileSync(path("claude"), SESSION, { mode: 0o755 });
|
||||
writeFileSync(
|
||||
path("step.sh"),
|
||||
stepScript(readFileSync(join(source, "action.yml"), "utf8")),
|
||||
);
|
||||
writeFileSync(
|
||||
path("bin/bun"),
|
||||
`#!/bin/bash\nexec "${process.execPath}" "$@"\n`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
|
||||
const running = Bun.spawn(
|
||||
[
|
||||
"bash",
|
||||
"--noprofile",
|
||||
"--norc",
|
||||
"-e",
|
||||
"-o",
|
||||
"pipefail",
|
||||
path("step.sh"),
|
||||
],
|
||||
{
|
||||
cwd: path("repo"),
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
env: {
|
||||
PATH: `${path("bin")}:${process.env.PATH}`,
|
||||
HOME: dir,
|
||||
RUNNER_TEMP: dir,
|
||||
TEST_DIR: dir,
|
||||
IN_SESSION: inSession,
|
||||
GITHUB_ACTION_PATH: path("action"),
|
||||
GITHUB_API_URL: `http://127.0.0.1:${server.port}`,
|
||||
GITHUB_EVENT_NAME: "workflow_dispatch",
|
||||
GITHUB_EVENT_PATH: path("event.json"),
|
||||
GITHUB_REPOSITORY: "o/r",
|
||||
GITHUB_ACTOR: "writer",
|
||||
GITHUB_RUN_ID: "1",
|
||||
GITHUB_OUTPUT: path("outputs/output"),
|
||||
GITHUB_ENV: path("env"),
|
||||
GITHUB_PATH: path("path"),
|
||||
OVERRIDE_GITHUB_TOKEN: "the-token",
|
||||
ANTHROPIC_FEDERATION_RULE_ID: "rule",
|
||||
ANTHROPIC_ORGANIZATION_ID: "org",
|
||||
ACTIONS_ID_TOKEN_REQUEST_URL: `http://127.0.0.1:${server.port}/?`,
|
||||
ACTIONS_ID_TOKEN_REQUEST_TOKEN: "unused",
|
||||
PROMPT: "x",
|
||||
INPUT_PROMPT_FILE: path("prompt.txt"),
|
||||
PATH_TO_CLAUDE_CODE_EXECUTABLE: path("claude"),
|
||||
INPUT_PATH_TO_CLAUDE_CODE_EXECUTABLE: path("claude"),
|
||||
},
|
||||
},
|
||||
);
|
||||
step = running;
|
||||
await until(() => existsSync(path("started")), "the session");
|
||||
expect(pids().slice(0, 3).map(isRunning)).toEqual([true, true, true]);
|
||||
const identity = path("claude-workload-identity");
|
||||
expect(existsSync(identity)).toBe(true);
|
||||
|
||||
// The runner signals the step's own process and nothing else.
|
||||
for (const name of signals) running.kill(name);
|
||||
const exitCode = await running.exited;
|
||||
// What was killed can take a moment to be gone.
|
||||
await until(() => !pids().some(isRunning), "the session to end");
|
||||
|
||||
return {
|
||||
exitCode,
|
||||
outputs: parseOutputs(path("outputs/output")),
|
||||
env: readFileSync(path("env"), "utf8"),
|
||||
leftBehind: [path("lock"), identity]
|
||||
.filter(existsSync)
|
||||
.concat(readdirSync(path("action/scripts"))),
|
||||
};
|
||||
} finally {
|
||||
step?.kill("SIGKILL");
|
||||
chmodSync(path("outputs"), 0o755);
|
||||
for (const pid of pids().filter(isRunning)) process.kill(pid, "SIGKILL");
|
||||
server.stop(true);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform === "win32")("a cancelled run", () => {
|
||||
test.each([
|
||||
[["SIGINT"]],
|
||||
[["SIGTERM"]],
|
||||
[["SIGINT", "SIGINT", "SIGTERM"]],
|
||||
] as [NodeJS.Signals[]][])(
|
||||
"stops the session and has the app token revoked (%p)",
|
||||
async (signals) => {
|
||||
const result = await cancelStep("", { signals });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 130,
|
||||
leftBehind: [],
|
||||
outputs: {
|
||||
github_token: "the-token",
|
||||
// A session can't have the revocation skipped, or report success.
|
||||
skipped_due_to_workflow_validation_mismatch: "false",
|
||||
conclusion: "failure",
|
||||
},
|
||||
});
|
||||
expect(result.env).not.toContain("ADDED");
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
test("stops every process a session keeps starting", async () => {
|
||||
const result = await cancelStep("", {
|
||||
inSession:
|
||||
'bash -c "while :; do sleep 30.25 & echo \\$! >> \\"$TEST_DIR/pids\\"; sleep 0.005; done" & until [ $(wc -l < "$TEST_DIR/pids") -gt 9 ]; do sleep 0.05; done',
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ exitCode: 130, leftBehind: [] });
|
||||
}, 20_000);
|
||||
|
||||
test("writes its outputs when the session was in the middle of one", async () => {
|
||||
const result = await cancelStep("", {
|
||||
inSession: `echo 'report<<END' >> "$GITHUB_OUTPUT"`,
|
||||
});
|
||||
|
||||
expect(result.outputs).toEqual({
|
||||
skipped_due_to_workflow_validation_mismatch: "false",
|
||||
github_token: "the-token",
|
||||
branch_name: "",
|
||||
conclusion: "failure",
|
||||
});
|
||||
}, 20_000);
|
||||
|
||||
test("stops the session in the base action", async () => {
|
||||
const result = await cancelStep("base-action");
|
||||
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 130,
|
||||
leftBehind: [],
|
||||
outputs: { conclusion: "failure" },
|
||||
});
|
||||
}, 20_000);
|
||||
|
||||
test.skipIf(process.getuid?.() === 0)(
|
||||
"cleans up what it can when outputs can't be written",
|
||||
async () => {
|
||||
const result = await cancelStep("", {
|
||||
inSession: 'chmod a-w "$GITHUB_OUTPUT" "$(dirname "$GITHUB_OUTPUT")"',
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ exitCode: 130, leftBehind: [] });
|
||||
expect(result.env).not.toContain("ADDED");
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
});
|
||||
|
||||
describe("onCancel", () => {
|
||||
// Prints once it is ready, and finishes by itself after a second.
|
||||
const finishing = (...signals: NodeJS.Signals[]) => {
|
||||
const source = join(import.meta.dir, "../base-action/src/cancel.ts");
|
||||
const child = Bun.spawn(
|
||||
[
|
||||
process.execPath,
|
||||
"-e",
|
||||
`import { onCancel } from ${JSON.stringify(source)};
|
||||
onCancel([() => console.log("stopped")], () => true);
|
||||
setTimeout(() => { console.log("finished"); process.exit(0); }, 1000);
|
||||
console.log("ready");`,
|
||||
],
|
||||
{ stdout: "pipe" },
|
||||
);
|
||||
return (async () => {
|
||||
let output = "";
|
||||
for await (const chunk of child.stdout) {
|
||||
output += new TextDecoder().decode(chunk);
|
||||
if (output === "ready\n") signals.forEach((name) => child.kill(name));
|
||||
}
|
||||
return { output, exitCode: await child.exited };
|
||||
})();
|
||||
};
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"lets a run whose session has ended finish until the second signal",
|
||||
async () => {
|
||||
expect(await finishing("SIGINT")).toEqual({
|
||||
output: "ready\nfinished\n",
|
||||
exitCode: 0,
|
||||
});
|
||||
expect(await finishing("SIGINT", "SIGTERM")).toEqual({
|
||||
output: "ready\nstopped\n",
|
||||
exitCode: 130,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -140,6 +140,7 @@ describe("in a shallow checkout of the default branch", () => {
|
||||
let originalCwd: string;
|
||||
let dir: string;
|
||||
let head: string;
|
||||
const allowForkPrs = process.env.ALLOW_FORK_PRS;
|
||||
const git = (cwd: string, ...args: string[]) =>
|
||||
execFileSync(
|
||||
"git",
|
||||
@@ -173,9 +174,12 @@ describe("in a shallow checkout of the default branch", () => {
|
||||
git(checkout, "fetch", "--depth=1", "origin", "trunk");
|
||||
git(checkout, "checkout", "-B", "trunk", "origin/trunk");
|
||||
process.chdir(checkout);
|
||||
process.env.ALLOW_FORK_PRS = "true";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (allowForkPrs === undefined) delete process.env.ALLOW_FORK_PRS;
|
||||
else process.env.ALLOW_FORK_PRS = allowForkPrs;
|
||||
process.chdir(originalCwd);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
@@ -313,7 +317,7 @@ describe("in a shallow checkout whose history contains the config branch", () =>
|
||||
);
|
||||
});
|
||||
|
||||
test("run.ts restores both kinds of config from the chosen branch", () => {
|
||||
test("run.ts restores every kind of config from the chosen branch", () => {
|
||||
const source = readFileSync(
|
||||
join(import.meta.dir, "../src/entrypoints/run.ts"),
|
||||
"utf8",
|
||||
@@ -327,5 +331,8 @@ test("run.ts restores both kinds of config from the chosen branch", () => {
|
||||
expect(source).toContain("restoreHeadHistory?.();");
|
||||
expect(source).toContain("pinRestoredPaths(restoredConfigPaths)");
|
||||
expect(source).toContain("restoreToolConfigFromBase(configBranch)");
|
||||
expect(source.replace(/\s+/g, " ")).toContain(
|
||||
"restoreConfigPathsFromBase( configBranch, namedConfigPaths(prepareResult.claudeArgs), )",
|
||||
);
|
||||
expect(source).toContain("fetchBranch(restoreBase)");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
|
||||
import * as core from "@actions/core";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readlinkSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { dirname, join } from "path";
|
||||
import {
|
||||
namedConfigPaths,
|
||||
restoreConfigPathsFromBase,
|
||||
} from "../src/github/operations/config-paths";
|
||||
import { restoreConfigFromBase } from "../src/github/operations/restore-config";
|
||||
|
||||
const INPUTS = [
|
||||
"INPUT_SETTINGS",
|
||||
"INPUT_PLUGIN_MARKETPLACES",
|
||||
"GITHUB_WORKSPACE",
|
||||
];
|
||||
|
||||
let originalCwd: string;
|
||||
let tempDir: string;
|
||||
let saved: Record<string, string | undefined>;
|
||||
let warningSpy: any;
|
||||
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync("git", args, { encoding: "utf8", stdio: "pipe" }).trim();
|
||||
const write = (path: string, content: string) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
rmSync(path, { recursive: true, force: true });
|
||||
writeFileSync(path, content);
|
||||
};
|
||||
const link = (path: string, target: string) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
rmSync(path, { recursive: true, force: true });
|
||||
symlinkSync(target, path);
|
||||
};
|
||||
const read = (path: string) => readFileSync(path, "utf8");
|
||||
const commit = (message: string) => {
|
||||
git("add", "-A", "-f");
|
||||
git("commit", "-qm", message);
|
||||
};
|
||||
|
||||
// Commits the base branch, pushes it and starts the pull request's branch from it.
|
||||
const startPr = () => {
|
||||
commit("base");
|
||||
git("push", "-q", "origin", "main");
|
||||
git("checkout", "-qb", "pr");
|
||||
};
|
||||
|
||||
const restoreAll = (named = { paths: [], marketplaces: [] } as any) => {
|
||||
restoreConfigFromBase("main");
|
||||
return restoreConfigPathsFromBase("main", named);
|
||||
};
|
||||
const named = (...paths: string[]) => ({ paths, marketplaces: [] as string[] });
|
||||
const restore = (named?: any) => restoreAll(named).replaced;
|
||||
|
||||
beforeEach(() => {
|
||||
originalCwd = process.cwd();
|
||||
saved = Object.fromEntries(INPUTS.map((key) => [key, process.env[key]]));
|
||||
INPUTS.forEach((key) => delete process.env[key]);
|
||||
warningSpy = spyOn(core, "warning").mockImplementation(() => {});
|
||||
tempDir = mkdtempSync(join(tmpdir(), "config-paths-"));
|
||||
const remote = join(tempDir, "origin.git");
|
||||
const repo = join(tempDir, "repo");
|
||||
execFileSync("git", ["init", "-q", "--bare", remote]);
|
||||
execFileSync("git", ["init", "-q", "-b", "main", repo]);
|
||||
process.chdir(repo);
|
||||
git("config", "user.email", "[email protected]");
|
||||
git("config", "user.name", "Test User");
|
||||
git("remote", "add", "origin", remote);
|
||||
write("src/index.ts", "base\n");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
warningSpy.mockRestore();
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
for (const key of INPUTS) {
|
||||
if (saved[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = saved[key];
|
||||
}
|
||||
});
|
||||
|
||||
describe("a named directory", () => {
|
||||
const inputs = () => namedConfigPaths("--plugin-dir ci/plugin");
|
||||
beforeEach(() => write("ci/plugin/a.json", "base\n"));
|
||||
|
||||
test("is left alone if the pull request doesn't change it", () => {
|
||||
startPr();
|
||||
write("src/index.ts", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(inputs())).toEqual([]);
|
||||
expect(git("status", "--porcelain")).toBe("");
|
||||
expect(warningSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("comes from the base branch, without what the pull request adds", () => {
|
||||
startPr();
|
||||
write("ci/plugin/a.json", "pr\n");
|
||||
write("ci/plugin/b.json", "pr\n");
|
||||
write("src/index.ts", "pr\n");
|
||||
commit("pr");
|
||||
write("ci/plugin/generated.json", "by an earlier step\n");
|
||||
|
||||
expect(restore(inputs())).toEqual(["ci/plugin"]);
|
||||
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
expect(existsSync("ci/plugin/b.json")).toBe(false);
|
||||
expect(read("ci/plugin/generated.json")).toBe("by an earlier step\n");
|
||||
expect(read("src/index.ts")).toBe("pr\n");
|
||||
expect(read(".claude-pr/ci/plugin/a.json")).toBe("pr\n");
|
||||
// Nothing is staged, so a commit doesn't include it.
|
||||
expect(git("diff", "--cached", "--name-only")).toBe("");
|
||||
expect(warningSpy.mock.calls[0][0]).toContain("ci/plugin");
|
||||
});
|
||||
|
||||
test.each(["ci", "ci/plugin", "ci/plugin/a.json"])(
|
||||
"is put back if the pull request has a link at %s",
|
||||
(path) => {
|
||||
startPr();
|
||||
write(join(tempDir, "outside", "keep"), "untouched\n");
|
||||
rmSync(path, { recursive: true });
|
||||
link(path, join(tempDir, "outside"));
|
||||
commit("pr");
|
||||
|
||||
expect(restore(inputs()).sort()).toEqual(
|
||||
path === "ci" ? ["ci", "ci/plugin"] : ["ci/plugin"],
|
||||
);
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
expect(read(join(tempDir, "outside", "keep"))).toBe("untouched\n");
|
||||
},
|
||||
);
|
||||
|
||||
test("is put back if the pull request has a file in its parent's place", () => {
|
||||
startPr();
|
||||
rmSync("ci", { recursive: true });
|
||||
write("ci", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(inputs()).sort()).toEqual(["ci", "ci/plugin"]);
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("is put back if the pull request makes its parent a submodule", () => {
|
||||
startPr();
|
||||
git("rm", "-rq", "ci");
|
||||
git(
|
||||
"update-index",
|
||||
"--add",
|
||||
"--cacheinfo",
|
||||
`160000,${git("rev-parse", "HEAD")},ci`,
|
||||
);
|
||||
git("commit", "-qm", "pr");
|
||||
mkdirSync("ci");
|
||||
|
||||
expect(restore(inputs()).sort()).toEqual(["ci", "ci/plugin"]);
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("keeps its own links, and loses the pull request's", () => {
|
||||
link("ci/plugin/hooks", "../hooks");
|
||||
startPr();
|
||||
link("ci/plugin/hooks", "../evil");
|
||||
link("ci/plugin/more", "../evil");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(inputs())).toEqual(["ci/plugin"]);
|
||||
expect(readlinkSync("ci/plugin/hooks")).toBe("../hooks");
|
||||
expect(lstatSync("ci/plugin/more", { throwIfNoEntry: false })).toBe(
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("a file that an earlier step created stays", () => {
|
||||
startPr();
|
||||
write("generated/settings.json", "by an earlier step\n");
|
||||
|
||||
expect(restore(named("generated/settings.json"))).toEqual([]);
|
||||
expect(read("generated/settings.json")).toBe("by an earlier step\n");
|
||||
});
|
||||
|
||||
test("a link that the pull request puts above a missing path is removed", () => {
|
||||
startPr();
|
||||
write("evil/settings.json", "pr\n");
|
||||
link("generated", "evil");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(named("generated/settings.json")).sort()).toEqual([
|
||||
"generated",
|
||||
"generated/settings.json",
|
||||
]);
|
||||
expect(existsSync("generated/settings.json")).toBe(false);
|
||||
});
|
||||
|
||||
test("a submodule that the pull request moves stops the run", () => {
|
||||
const add = (oid: string) =>
|
||||
git("update-index", "--add", "--cacheinfo", `160000,${oid},vendor`);
|
||||
commit("first");
|
||||
add(git("rev-parse", "HEAD"));
|
||||
git("commit", "-qm", "base");
|
||||
git("push", "-q", "origin", "main");
|
||||
git("checkout", "-qb", "pr");
|
||||
const inputs = namedConfigPaths("--plugin-dir vendor/plugin");
|
||||
expect(restore(inputs)).toEqual([]);
|
||||
|
||||
add(git("rev-parse", "HEAD"));
|
||||
git("commit", "-qm", "pr");
|
||||
expect(() => restore(inputs)).toThrow("different commits of a submodule");
|
||||
});
|
||||
|
||||
test("the base branch's link above a named path is put back", () => {
|
||||
write("tools/ci/plugin/a.json", "base\n");
|
||||
link("ci", "tools/ci");
|
||||
startPr();
|
||||
rmSync("ci");
|
||||
write("ci/plugin/a.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(named("ci/plugin")).sort()).toEqual(["ci", "ci/plugin"]);
|
||||
expect(readlinkSync("ci")).toBe("tools/ci");
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test.each(["working-tree-encoding=UTF-16", "text eol=crlf", "ident"])(
|
||||
"a .gitattributes can't make git write a file differently: %s",
|
||||
(attribute) => {
|
||||
write("ci/a.sh", "base $Id$\n");
|
||||
write("ci/b.sh", "base\n");
|
||||
startPr();
|
||||
write("ci/b.sh", "pr\n");
|
||||
commit("pr");
|
||||
write(".gitattributes", `*.sh ${attribute}\n`);
|
||||
git("add", ".gitattributes");
|
||||
git("commit", "-qm", "attributes");
|
||||
rmSync("ci", { recursive: true });
|
||||
git("checkout", "-q", "--", "ci");
|
||||
expect(read("ci/a.sh")).not.toBe("base $Id$\n");
|
||||
|
||||
expect(restore(named("ci/a.sh", "ci/b.sh")).sort()).toEqual([
|
||||
"ci/a.sh",
|
||||
"ci/b.sh",
|
||||
]);
|
||||
expect(read("ci/a.sh")).toBe("base $Id$\n");
|
||||
expect(read("ci/b.sh")).toBe("base\n");
|
||||
},
|
||||
);
|
||||
|
||||
test("the base branch's own .gitattributes are left alone", () => {
|
||||
write("ci/a.sh", "base\n");
|
||||
write(".gitattributes", "*.sh text eol=crlf\n");
|
||||
write("other/.gitattributes", "");
|
||||
startPr();
|
||||
write("other/.gitattributes", "* text\n");
|
||||
commit("pr");
|
||||
rmSync("ci", { recursive: true });
|
||||
git("checkout", "-q", "--", "ci");
|
||||
|
||||
expect(restore(named("ci/a.sh"))).toEqual([]);
|
||||
expect(read("ci/a.sh")).toBe("base\r\n");
|
||||
});
|
||||
|
||||
test("what an earlier step changed stays if the pull request doesn't change it", () => {
|
||||
write("ci/plugin/dist.js", "base\n");
|
||||
write("ci/plugin/a.json", "base\n");
|
||||
startPr();
|
||||
write("ci/plugin/a.json", "pr\n");
|
||||
commit("pr");
|
||||
write("ci/plugin/dist.js", "by an earlier step\n");
|
||||
|
||||
expect(restore(namedConfigPaths("--plugin-dir ci/plugin"))).toEqual([
|
||||
"ci/plugin",
|
||||
]);
|
||||
expect(read("ci/plugin/dist.js")).toBe("by an earlier step\n");
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("a link that leads out of the checkout can't become a file", () => {
|
||||
link("ci/mcp.json", "/opt/shared/mcp.json");
|
||||
startPr();
|
||||
write("ci/mcp.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(named("ci/mcp.json"))).toEqual(["ci/mcp.json"]);
|
||||
expect(readlinkSync("ci/mcp.json")).toBe("/opt/shared/mcp.json");
|
||||
});
|
||||
|
||||
test("a path can't go back through a directory", () => {
|
||||
for (const path of [
|
||||
"tools/../ci/s.json",
|
||||
"./a/b/../../s.json",
|
||||
"a/./../s",
|
||||
"tools/../../shared/s.json",
|
||||
join(process.cwd(), "tools") + "/../s.json",
|
||||
]) {
|
||||
process.env.INPUT_SETTINGS = path;
|
||||
expect(() => namedConfigPaths("")).toThrow('Write it without ".."');
|
||||
}
|
||||
for (const path of [
|
||||
"./ci/..s.json",
|
||||
"a..b/s",
|
||||
"../outside/../s.json",
|
||||
process.cwd() + "/../s.json",
|
||||
]) {
|
||||
process.env.INPUT_SETTINGS = path;
|
||||
namedConfigPaths("");
|
||||
}
|
||||
});
|
||||
|
||||
test("a name that differs in case is another file where the file system says so", () => {
|
||||
write("docs/guide.md", "base\n");
|
||||
write("Docs/guide.md/readme", "base\n");
|
||||
const isCaseSensitive = read("docs/guide.md") === "base\n";
|
||||
startPr();
|
||||
if (!isCaseSensitive) return;
|
||||
write("Docs/guide.md/readme", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(named("docs/guide.md"))).toEqual([]);
|
||||
expect(read("Docs/guide.md/readme")).toBe("pr\n");
|
||||
});
|
||||
|
||||
test("names with glob characters are literal in the rules", () => {
|
||||
write("plugins/[ci]/x", "base\n");
|
||||
startPr();
|
||||
write("plugins/[ci]/x", "pr\n");
|
||||
commit("pr");
|
||||
expect(
|
||||
restoreAll(namedConfigPaths("--plugin-dir 'plugins/[ci]'")).denyRules,
|
||||
).toEqual(["Edit(./plugins/\\[ci\\])", "Edit(./plugins/\\[ci\\]/**)"]);
|
||||
});
|
||||
|
||||
test("a workspace reached through a link is the same checkout", () => {
|
||||
write("ci/mcp.json", "base\n");
|
||||
const workspace = join(tempDir, "workspace");
|
||||
symlinkSync(process.cwd(), workspace);
|
||||
process.env.GITHUB_WORKSPACE = workspace;
|
||||
startPr();
|
||||
write("ci/mcp.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(
|
||||
restore(namedConfigPaths(`--mcp-config ${workspace}/ci/mcp.json`)),
|
||||
).toEqual(["ci/mcp.json"]);
|
||||
expect(read("ci/mcp.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("a session can't edit what the inputs name, changed or not", () => {
|
||||
write("ci/plugin/check.sh", "base\n");
|
||||
write("ci/s.json", "base\n");
|
||||
startPr();
|
||||
write("ci/s.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
const { replaced, denyRules } = restoreAll(
|
||||
namedConfigPaths("--plugin-dir ci/plugin --settings ci/s.json"),
|
||||
);
|
||||
expect(replaced).toEqual(["ci/s.json"]);
|
||||
expect(denyRules.sort()).toEqual([
|
||||
"Edit(./ci/plugin)",
|
||||
"Edit(./ci/plugin/**)",
|
||||
"Edit(./ci/s.json)",
|
||||
"Edit(./ci/s.json/**)",
|
||||
]);
|
||||
});
|
||||
|
||||
test("what nothing names stays, also if Claude's config links to it", () => {
|
||||
write("docs/guide.md", "base\n");
|
||||
link("CLAUDE.md", "docs/guide.md");
|
||||
startPr();
|
||||
write("docs/guide.md", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restoreAll(namedConfigPaths("--model m"))).toEqual({
|
||||
replaced: [],
|
||||
denyRules: [],
|
||||
});
|
||||
});
|
||||
|
||||
describe("what the workflow's inputs name", () => {
|
||||
test("comes from the base branch, or is removed if only the pull request has it", () => {
|
||||
write("ci/settings.json", "base\n");
|
||||
write("ci/plugin/hooks/hooks.json", "base\n");
|
||||
startPr();
|
||||
write("ci/settings.json", "pr\n");
|
||||
write("ci/plugin/hooks/hooks.json", "pr\n");
|
||||
write("ci/mcp.json", "pr\n");
|
||||
write("ci/other.json", "pr\n");
|
||||
commit("pr");
|
||||
process.env.INPUT_SETTINGS = "ci/settings.json";
|
||||
|
||||
const named = namedConfigPaths(
|
||||
"--mcp-config ci/mcp.json --plugin-dir ./ci/plugin",
|
||||
);
|
||||
expect(restore(named).sort()).toEqual([
|
||||
"ci/mcp.json",
|
||||
"ci/plugin",
|
||||
"ci/settings.json",
|
||||
]);
|
||||
|
||||
expect(read("ci/settings.json")).toBe("base\n");
|
||||
expect(read("ci/plugin/hooks/hooks.json")).toBe("base\n");
|
||||
expect(existsSync("ci/mcp.json")).toBe(false);
|
||||
expect(read("ci/other.json")).toBe("pr\n");
|
||||
});
|
||||
|
||||
test("can't be the whole repository", () => {
|
||||
startPr();
|
||||
write("hooks/hooks.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(() => restore(namedConfigPaths("--plugin-dir ."))).toThrow(
|
||||
"Put the plugin in a subdirectory",
|
||||
);
|
||||
});
|
||||
|
||||
test("is the manifest and the plugins of a marketplace at the root", () => {
|
||||
write(
|
||||
".claude-plugin/marketplace.json",
|
||||
JSON.stringify({
|
||||
metadata: { pluginRoot: "./more" },
|
||||
plugins: [
|
||||
{ name: "a", source: "./plugins/a/" },
|
||||
{ name: "b", source: "b" },
|
||||
{ name: "d", source: "../d" },
|
||||
{ name: "c", source: { source: "github", repo: "o/c" } },
|
||||
],
|
||||
}),
|
||||
);
|
||||
write("plugins/a/hooks/hooks.json", "base\n");
|
||||
write("more/b/hooks/hooks.json", "base\n");
|
||||
startPr();
|
||||
write(
|
||||
".claude-plugin/marketplace.json",
|
||||
JSON.stringify({ plugins: [{ name: "a", source: "./evil" }] }),
|
||||
);
|
||||
write("plugins/a/hooks/hooks.json", "pr\n");
|
||||
write("more/b/hooks/hooks.json", "pr\n");
|
||||
commit("pr");
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = "https://example.com/x.git\n./\n";
|
||||
|
||||
expect(restore(namedConfigPaths("")).sort()).toEqual([
|
||||
".claude-plugin",
|
||||
"more/b",
|
||||
"plugins/a",
|
||||
]);
|
||||
expect(read("plugins/a/hooks/hooks.json")).toBe("base\n");
|
||||
expect(read("more/b/hooks/hooks.json")).toBe("base\n");
|
||||
expect(read(".claude-plugin/marketplace.json")).not.toContain("evil");
|
||||
expect(read("src/index.ts")).toBe("base\n");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["ci/marketplace.json", "ci/marketplace.json"],
|
||||
["./", ".claude-plugin/marketplace.json"],
|
||||
])("finds the plugins of a marketplace at %s", (input, path) => {
|
||||
const manifest = JSON.stringify({
|
||||
plugins: [{ name: "a", source: "./plugins/a" }],
|
||||
});
|
||||
write(path, manifest);
|
||||
write("plugins/a/hooks/hooks.json", "base\n");
|
||||
startPr();
|
||||
write("plugins/a/hooks/hooks.json", "pr\n");
|
||||
commit("pr");
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = input.startsWith(".")
|
||||
? input
|
||||
: `./${input}`;
|
||||
|
||||
expect(restore(namedConfigPaths(""))).toEqual(["plugins/a"]);
|
||||
expect(read("plugins/a/hooks/hooks.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("is a whole marketplace in a directory", () => {
|
||||
write("market/.claude-plugin/marketplace.json", "base\n");
|
||||
write("market/a/hooks.json", "base\n");
|
||||
startPr();
|
||||
write("market/a/hooks.json", "pr\n");
|
||||
commit("pr");
|
||||
for (const input of [
|
||||
"./market",
|
||||
"./market/.claude-plugin/marketplace.json",
|
||||
]) {
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = input;
|
||||
expect(restore(namedConfigPaths(""))).toEqual(["market"]);
|
||||
expect(read("market/a/hooks.json")).toBe("base\n");
|
||||
git("checkout", "-q", "--", "market");
|
||||
}
|
||||
});
|
||||
|
||||
test("can't be a plugin that is the whole repository", () => {
|
||||
write(
|
||||
".claude-plugin/marketplace.json",
|
||||
JSON.stringify({ plugins: [{ name: "a", source: "./" }] }),
|
||||
);
|
||||
startPr();
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = "./";
|
||||
|
||||
expect(() => restore(namedConfigPaths(""))).toThrow(
|
||||
"Put the plugin in a subdirectory",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("namedConfigPaths", () => {
|
||||
test("finds paths in every input that names files", () => {
|
||||
process.env.INPUT_SETTINGS = " .github/settings.json ";
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES =
|
||||
"./market\n../outside\n/elsewhere\n";
|
||||
expect(
|
||||
namedConfigPaths(
|
||||
`--mcp-config '{"mcpServers":{}}' a.json b.json
|
||||
--plugin-dir=plugin --settings '{"a":1}' --agents agents.json
|
||||
--append-system-prompt-file p.md --system-prompt-file ../x.md
|
||||
--plugin-dir-no-mcp 2024 --append-subagent-system-prompt-file q.md
|
||||
--setting-sources user --json-schema '{}'
|
||||
--allowedTools Read --model m`,
|
||||
),
|
||||
).toEqual({
|
||||
paths: [
|
||||
".github/settings.json",
|
||||
"a.json",
|
||||
"b.json",
|
||||
"plugin",
|
||||
"agents.json",
|
||||
"p.md",
|
||||
"2024",
|
||||
"q.md",
|
||||
],
|
||||
marketplaces: ["market"],
|
||||
});
|
||||
});
|
||||
|
||||
test("finds the project config in a --project-config-root", () => {
|
||||
startPr();
|
||||
const { paths } = namedConfigPaths("--project-config-root app");
|
||||
expect(paths).toContain("app/.claude");
|
||||
expect(paths).toContain("app/.mcp.json");
|
||||
expect(paths).not.toContain("app");
|
||||
expect(restore(namedConfigPaths(`--project-config-root .`))).toEqual([]);
|
||||
});
|
||||
|
||||
test("finds nothing in inputs that name no files in the checkout", () => {
|
||||
process.env.INPUT_SETTINGS = '{"permissions":{}}';
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = "https://example.com/x.git";
|
||||
expect(namedConfigPaths("--mcp-config /etc/mcp.json --settings")).toEqual({
|
||||
paths: [],
|
||||
marketplaces: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
+123
-6
@@ -97,9 +97,9 @@ describe("allow_fork_prs", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test("allows forks when action.yml didn't pass the input", async () => {
|
||||
test("refuses forks when the input isn't passed", async () => {
|
||||
delete process.env.ALLOW_FORK_PRS;
|
||||
expect(await isRefusedForkPr(unused, fork)).toBe(false);
|
||||
expect(await isRefusedForkPr(unused, fork)).toBe(true);
|
||||
});
|
||||
|
||||
test.each(["false", "False", "", "no", "flase", "0"])(
|
||||
@@ -185,10 +185,15 @@ test("setupBranch refuses a fork when allow_fork_prs is off", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
describe("run.ts with allow_fork_prs: false", () => {
|
||||
describe("run.ts with allow_fork_prs off, the default", () => {
|
||||
// Returns the exit code, the output and the requests made. The directory is not a
|
||||
// git repository, so a run that goes on to check something out fails.
|
||||
async function run(eventName: string, event: object, pull?: object) {
|
||||
async function run(
|
||||
eventName: string,
|
||||
event: object,
|
||||
pull?: object,
|
||||
env: Record<string, string> = {},
|
||||
) {
|
||||
const dir = mkdtempSync(join(tmpdir(), "fork-pr-"));
|
||||
const requests: string[] = [];
|
||||
const server = Bun.serve({
|
||||
@@ -197,8 +202,13 @@ describe("run.ts with allow_fork_prs: false", () => {
|
||||
fetch(request) {
|
||||
const { pathname } = new URL(request.url);
|
||||
requests.push(pathname);
|
||||
if (pathname.startsWith("/users/")) {
|
||||
const type = pathname.includes("bot") ? "Bot" : "User";
|
||||
return Response.json({ type });
|
||||
}
|
||||
if (pathname.endsWith("/permission")) {
|
||||
return Response.json({ permission: "write" });
|
||||
const writer = pathname.includes("/writer/");
|
||||
return Response.json({ permission: writer ? "write" : "read" });
|
||||
}
|
||||
return pull && pathname.endsWith("/pulls/7")
|
||||
? Response.json(pull)
|
||||
@@ -231,9 +241,9 @@ describe("run.ts with allow_fork_prs: false", () => {
|
||||
GITHUB_ENV: join(dir, "env"),
|
||||
GITHUB_API_URL: `http://127.0.0.1:${server.port}`,
|
||||
TRIGGER_PHRASE: "@claude",
|
||||
ALLOW_FORK_PRS: "false",
|
||||
// With no token, a run that asks for one fails.
|
||||
...(pull && { OVERRIDE_GITHUB_TOKEN: "t" }),
|
||||
...env,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -282,9 +292,116 @@ describe("run.ts with allow_fork_prs: false", () => {
|
||||
expect(result.requests).toEqual([
|
||||
"/repos/o/r/collaborators/writer/permission",
|
||||
"/repos/o/r/pulls/7",
|
||||
"/users/writer",
|
||||
]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["writer", "pull_request_target", 0],
|
||||
["outsider", "pull_request_target", 1],
|
||||
["writer", "workflow_run", 0],
|
||||
["outsider", "workflow_run", 1],
|
||||
])("%s's fork on %s exits %p", async (login, eventName, exitCode) => {
|
||||
const actor = { login, type: "User" };
|
||||
const head = { ...FORK, full_name: `${login}/r` };
|
||||
const event =
|
||||
eventName === "workflow_run"
|
||||
? {
|
||||
action: "completed",
|
||||
repository: { ...repository, full_name: "o/r" },
|
||||
sender: actor,
|
||||
workflow_run: { id: 1, actor, head_repository: head },
|
||||
}
|
||||
: {
|
||||
action: "opened",
|
||||
repository,
|
||||
sender: actor,
|
||||
pull_request: { number: 7, user: actor, ...pullRequest(FORK) },
|
||||
};
|
||||
const env = { GITHUB_ACTOR: login, PROMPT: "Review this" };
|
||||
const result = await run(eventName, event, pullRequest(FORK), env);
|
||||
expect(result.exitCode).toBe(exitCode);
|
||||
expect(result.log).toContain(
|
||||
exitCode
|
||||
? "Actor does not have write permissions"
|
||||
: "Skipped, because allow_fork_prs",
|
||||
);
|
||||
});
|
||||
|
||||
test("a bot's action on an outsider's fork still fails", async () => {
|
||||
const bot = { login: "helper[bot]", type: "Bot" };
|
||||
const result = await run(
|
||||
"pull_request_target",
|
||||
{
|
||||
action: "synchronize",
|
||||
repository,
|
||||
sender: bot,
|
||||
pull_request: {
|
||||
number: 7,
|
||||
user: { login: "outsider" },
|
||||
...pullRequest(FORK),
|
||||
},
|
||||
},
|
||||
pullRequest(FORK),
|
||||
{ GITHUB_ACTOR: bot.login, ALLOWED_BOTS: "*", PROMPT: "Review this" },
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.log).toContain("A bot acted on this pull request");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["writer", "t", "", 0],
|
||||
["outsider", "t", "", 1],
|
||||
["outsider", "", "", 0],
|
||||
["outsider", "", "key", 1],
|
||||
])(
|
||||
"%s's fork in a private repository with token %p and key %p exits %p",
|
||||
async (login, token, key, exitCode) => {
|
||||
const actor = { login, type: "User" };
|
||||
const result = await run(
|
||||
"pull_request",
|
||||
{
|
||||
action: "opened",
|
||||
repository: { ...repository, private: true },
|
||||
sender: actor,
|
||||
pull_request: { number: 7, user: actor, ...pullRequest(FORK) },
|
||||
},
|
||||
pullRequest(FORK),
|
||||
{
|
||||
GITHUB_ACTOR: login,
|
||||
PROMPT: "Review",
|
||||
OVERRIDE_GITHUB_TOKEN: token,
|
||||
ANTHROPIC_API_KEY: key,
|
||||
},
|
||||
);
|
||||
expect(result.exitCode).toBe(exitCode);
|
||||
},
|
||||
30_000, // without a token, the action retries before it fails
|
||||
);
|
||||
|
||||
test.each([
|
||||
["", 1],
|
||||
["helper", 0],
|
||||
])(
|
||||
"a bot's own fork with allowed_bots %p exits %p",
|
||||
async (bots, exitCode) => {
|
||||
const bot = { login: "helper[bot]", type: "Bot" };
|
||||
const result = await run(
|
||||
"pull_request_target",
|
||||
{
|
||||
action: "opened",
|
||||
repository,
|
||||
sender: bot,
|
||||
pull_request: { number: 7, user: bot, ...pullRequest(FORK) },
|
||||
},
|
||||
pullRequest(FORK),
|
||||
{ GITHUB_ACTOR: bot.login, ALLOWED_BOTS: bots, PROMPT: "Review" },
|
||||
);
|
||||
expect(result.exitCode).toBe(exitCode);
|
||||
if (exitCode) expect(result.log).toContain("non-human actor");
|
||||
},
|
||||
);
|
||||
|
||||
test("goes on with a comment on a pull request in this repository", async () => {
|
||||
const result = await run(
|
||||
"issue_comment",
|
||||
|
||||
@@ -282,7 +282,7 @@ describe("git wrappers", () => {
|
||||
|
||||
describe("with files taken from another branch", () => {
|
||||
const RESTORED =
|
||||
":(top).claude\n:(top)CLAUDE.md\n:(top)AGENTS.md\n:(top).mcp.json\n:(top,glob)**/package.json\n";
|
||||
":(top,literal).claude\n:(top,literal)CLAUDE.md\n:(top,literal)AGENTS.md\n:(top,literal).mcp.json\n:(top,glob)**/package.json\n";
|
||||
const write = (path: string, content: string) => {
|
||||
mkdirSync(join(repo, path, ".."), { recursive: true });
|
||||
writeFileSync(join(repo, path), content);
|
||||
|
||||
@@ -441,7 +441,7 @@ describe("session guard", () => {
|
||||
pinRestoredPaths([".claude", "package.json"]);
|
||||
const restoredFile = join(dir, "scripts/.restored-paths");
|
||||
expect(readFileSync(restoredFile, "utf8")).toBe(
|
||||
":(top).claude\n:(top,glob)**/package.json\n",
|
||||
":(top,literal).claude\n:(top,glob)**/package.json\n",
|
||||
);
|
||||
clearSessionState();
|
||||
expect(existsSync(join(dir, "scripts/.push-branch"))).toBe(false);
|
||||
|
||||
Reference in New Issue
Block a user