mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-11-18 20:46:19 +08:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eae045c9a7 | ||
|
|
fad9fff936 |
+2
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
## Access Control
|
||||
|
||||
- **Text From Other People**: Triggering a run does not make someone else's text a request. When a maintainer labels or assigns another person's issue, slash commands in its body do not run, but Claude still reads the body to understand the task, so review it first. A pull request's body can also start a run when a maintainer pushes to, reopens or labels it, where `track_progress` is set. Editing or deleting another person's comment or review does not start a run, even with a `prompt`.
|
||||
- **Text From Other People**: Triggering a run does not make someone else's text a request. When a maintainer labels or assigns another person's issue, slash commands in its body do not run, but Claude still reads the body to understand the task, so review it first. A pull request's body can also start a run when a maintainer pushes to, reopens or labels it, where `track_progress` is set. Editing or dismissing another person's comment or review, or deleting any comment, does not start a run, even with a `prompt`.
|
||||
- **Repository Access**: The action can only be triggered by users with write access to the repository. This is checked for issue, pull request, comment, and review events, and for `workflow_run` events, where both the workflow actor and the actor that started the upstream run are checked. `workflow_dispatch`, `repository_dispatch`, and `schedule` events are not checked separately — GitHub itself requires write access to dispatch a workflow, and scheduled runs have no external actor.
|
||||
- **Bot User Control**: By default, GitHub Apps and bots cannot trigger this action for security reasons. Use the `allowed_bots` parameter to enable specific bots or all bots
|
||||
- **⚠️ Allowed bots are not checked for repository permissions.** A bot that matches an entry does **not** need to be installed on your repository or have write access. On a **public repository**, external parties — including GitHub Apps created by anyone — may be able to trigger workflow events such as opening issues, commenting, or reviewing pull requests. If your workflow listens on those events and `allowed_bots` is set to `'*'`, any such App can invoke this action with a prompt it controls.
|
||||
@@ -126,7 +126,7 @@ Bots often open pull requests from branches in your own repository. Runs there u
|
||||
|
||||
### What a session can leave behind
|
||||
|
||||
Steps that run after Claude, including post steps such as `actions/checkout`'s cleanup, trust `GITHUB_ENV`, `GITHUB_PATH` and git's config files. When the session ends, the action restores those files, including config pulled in through `include.path`, to how they were before it started, and logs a warning naming any it changed. A session therefore can't pass environment variables to later steps through `GITHUB_ENV`, and `git config` changes it made, such as the upstream that `git push -u` records, don't last. Use `GITHUB_OUTPUT` or `--json-schema` to pass results on.
|
||||
Steps that run after Claude, including post steps such as `actions/checkout`'s cleanup, trust `GITHUB_ENV`, `GITHUB_PATH` and git's config files. When the session ends, the action restores those files, including config pulled in through `include.path`, to how they were before it started, and logs a warning naming any it changed. A session therefore can't pass environment variables to later steps through `GITHUB_ENV`, and `git config` changes it made, such as the upstream that `git push -u` records, don't last. Use `GITHUB_OUTPUT` or `--json-schema` to pass results on. What a session writes to `GITHUB_OUTPUT` and `GITHUB_STEP_SUMMARY` is kept, unless it replaced the file with a link or something else that isn't a file.
|
||||
|
||||
While Claude runs, and for the action's own git commands afterwards, git ignores `core.fsmonitor`. Git hooks are off for the action's own commits after the session, and from before the checkout on pull requests that `restrict_untrusted_prs` applies to. During the session these are set in the repository's git config and by the wrapper scripts. Global git config also sets `safe.bareRepository=explicit` for the session, so git won't use a repository it finds in a folder that has no `.git`. A workflow that has Claude work in a bare repository needs to pass `--git-dir`. If a run is cancelled before it restores this, the setting stays in the global config of a self-hosted runner that keeps its home directory. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
|
||||
|
||||
|
||||
@@ -35,7 +35,10 @@ import type { GitHubContext } from "../github/context";
|
||||
import { detectMode } from "../modes/detector";
|
||||
import { prepareTagMode } from "../modes/tag";
|
||||
import { prepareAgentMode } from "../modes/agent";
|
||||
import { checkContainsTrigger } from "../github/validation/trigger";
|
||||
import {
|
||||
checkContainsTrigger,
|
||||
isModeration,
|
||||
} from "../github/validation/trigger";
|
||||
import {
|
||||
clearSessionState,
|
||||
disableGitPrograms,
|
||||
@@ -249,7 +252,8 @@ async function run() {
|
||||
const containsTrigger =
|
||||
modeName === "tag"
|
||||
? isEntityContext(context) && checkContainsTrigger(context)
|
||||
: !!context.inputs?.prompt;
|
||||
: !!context.inputs?.prompt &&
|
||||
!(isEntityContext(context) && isModeration(context));
|
||||
console.log(`Mode: ${modeName}`);
|
||||
console.log(`Context prompt: ${context.inputs?.prompt || "NO PROMPT"}`);
|
||||
console.log(`Trigger result: ${containsTrigger}`);
|
||||
|
||||
@@ -16,7 +16,8 @@ import {
|
||||
import { homedir } from "os";
|
||||
import { dirname, isAbsolute, join, resolve } from "path";
|
||||
|
||||
type TrackedFile = { label: string; path: string };
|
||||
// A session may write to one that keeps its writes, but not put a link in its place.
|
||||
type TrackedFile = { label: string; path: string; keepsWrites?: boolean };
|
||||
|
||||
// "opaque" is anything that can't be saved and compared: a directory, a FIFO, a
|
||||
// device, a file too large to hold, or one that can't be read.
|
||||
@@ -25,6 +26,7 @@ type FileSnapshot = TrackedFile & {
|
||||
wasSymlink: boolean;
|
||||
content?: Buffer;
|
||||
mode?: number;
|
||||
names?: number;
|
||||
// For a symlink: what it points to, and the regular file that ends up at.
|
||||
link?: { target: string; resolved: string };
|
||||
};
|
||||
@@ -121,8 +123,15 @@ function filesLaterStepsTrust(): TrackedFile[] {
|
||||
path ? [{ label, path }] : [],
|
||||
);
|
||||
|
||||
// The action adds to these after the session, so a link there would redirect that to
|
||||
// a file later steps trust.
|
||||
const written = ["GITHUB_OUTPUT", "GITHUB_STEP_SUMMARY"].flatMap((label) => {
|
||||
const path = process.env[label];
|
||||
return path ? [{ label, path, keepsWrites: true }] : [];
|
||||
});
|
||||
|
||||
const seen = new Set<string>();
|
||||
return [...named, ...gitConfigFilesInUse()].filter(({ path }) => {
|
||||
return [...named, ...gitConfigFilesInUse(), ...written].filter(({ path }) => {
|
||||
const absolute = resolve(path);
|
||||
if (seen.has(absolute)) return false;
|
||||
seen.add(absolute);
|
||||
@@ -152,6 +161,7 @@ function readSnapshot(file: TrackedFile): FileSnapshot {
|
||||
wasSymlink,
|
||||
content: readFileSync(fd),
|
||||
mode: stats.mode & 0o777,
|
||||
names: stats.nlink,
|
||||
...(wasSymlink && {
|
||||
link: {
|
||||
target: readlinkSync(file.path),
|
||||
@@ -190,6 +200,19 @@ function restorePath(before: FileSnapshot): string {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether what is written to a file now ends up in that file and no other. A new name
|
||||
* for a file that later steps trust is as good as a symlink to it.
|
||||
*/
|
||||
function isItsOwnFile(before: FileSnapshot): boolean {
|
||||
try {
|
||||
const stats = lstatSync(restorePath(before));
|
||||
return stats.isFile() && stats.nlink <= (before.names ?? 1);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the files later steps trust, and returns a function that puts them
|
||||
* back. Call the returned function as soon as the session ends and before the
|
||||
@@ -212,8 +235,12 @@ export function snapshotSessionFiles(beforeSession?: () => void): () => void {
|
||||
for (const [index, before] of snapshots.entries()) {
|
||||
try {
|
||||
const now = readSnapshot(before);
|
||||
if (isUnchanged(before, now)) continue;
|
||||
const changedBySession = !isUnchanged(atStart[index]!, now);
|
||||
if (before.keepsWrites && isItsOwnFile(before)) continue;
|
||||
// The file it leads to can have the same content so far.
|
||||
const leadsElsewhere = before.keepsWrites && now.state === "file";
|
||||
if (!leadsElsewhere && isUnchanged(before, now)) continue;
|
||||
const changedBySession =
|
||||
leadsElsewhere || !isUnchanged(atStart[index]!, now);
|
||||
if (before.state === "opaque") {
|
||||
core.warning(
|
||||
`Could not restore ${before.label} after the session: it was not a regular file before`,
|
||||
|
||||
@@ -12,13 +12,11 @@ import {
|
||||
import type { ParsedGitHubContext } from "../context";
|
||||
import { isSameLogin } from "./actor";
|
||||
|
||||
export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
|
||||
const {
|
||||
inputs: { assigneeTrigger, labelTrigger, triggerPhrase, prompt },
|
||||
} = context;
|
||||
|
||||
// Deleting or editing someone else's comment or review fires these events with
|
||||
// the moderator as the actor. The text must come from the person who was checked.
|
||||
/**
|
||||
* Whether the text of a comment or review event comes from the person who was checked.
|
||||
* Deleting or editing someone else's fires these events with the moderator as the actor.
|
||||
*/
|
||||
function isTextFromActor(context: ParsedGitHubContext): boolean {
|
||||
if (
|
||||
(isIssueCommentEvent(context) ||
|
||||
isPullRequestReviewCommentEvent(context)) &&
|
||||
@@ -35,6 +33,26 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
|
||||
console.log("Review was written by someone other than the actor");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a comment or review event comes from moderation, so that its text must not
|
||||
* start a run. A new comment or review is always its author's own, and some apps have
|
||||
* one login as its author and another as the actor.
|
||||
*/
|
||||
export function isModeration(context: ParsedGitHubContext): boolean {
|
||||
const isNew =
|
||||
context.eventAction === "created" || context.eventAction === "submitted";
|
||||
return !isNew && !isTextFromActor(context);
|
||||
}
|
||||
|
||||
export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
|
||||
const {
|
||||
inputs: { assigneeTrigger, labelTrigger, triggerPhrase, prompt },
|
||||
} = context;
|
||||
|
||||
if (!isTextFromActor(context)) return false;
|
||||
|
||||
// A prompt replaces the trigger phrase, but a configured label or assignee
|
||||
// still decides which label or assignment event starts a run. Otherwise any
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { join } from "path";
|
||||
|
||||
const writer = { login: "writer", type: "User" };
|
||||
const outsider = { login: "outsider", type: "User" };
|
||||
const repository = { id: 1, name: "r", owner: { login: "o" } };
|
||||
const issue = { number: 7, user: outsider };
|
||||
|
||||
// The directory is not a git repository, so a run that starts fails later on.
|
||||
async function runWithPrompt(eventName: string, event: object) {
|
||||
const dir = mkdtempSync(join(tmpdir(), "moderation-"));
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
hostname: "127.0.0.1",
|
||||
fetch: (request) =>
|
||||
request.url.endsWith("/permission")
|
||||
? Response.json({ permission: "write" })
|
||||
: Response.json({}, { status: 404 }),
|
||||
});
|
||||
try {
|
||||
for (const file of ["output", "env"]) writeFileSync(join(dir, file), "");
|
||||
writeFileSync(join(dir, "event.json"), JSON.stringify(event));
|
||||
const child = Bun.spawn(
|
||||
[
|
||||
process.execPath,
|
||||
"run",
|
||||
join(import.meta.dir, "../src/entrypoints/run.ts"),
|
||||
],
|
||||
{
|
||||
cwd: dir,
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
env: {
|
||||
PATH: process.env.PATH,
|
||||
HOME: dir,
|
||||
RUNNER_TEMP: dir,
|
||||
GITHUB_EVENT_NAME: eventName,
|
||||
GITHUB_EVENT_PATH: join(dir, "event.json"),
|
||||
GITHUB_REPOSITORY: "o/r",
|
||||
GITHUB_ACTOR: "writer",
|
||||
GITHUB_RUN_ID: "1",
|
||||
GITHUB_OUTPUT: join(dir, "output"),
|
||||
GITHUB_ENV: join(dir, "env"),
|
||||
GITHUB_API_URL: `http://127.0.0.1:${server.port}`,
|
||||
OVERRIDE_GITHUB_TOKEN: "t",
|
||||
ALLOW_FORK_PRS: "true",
|
||||
PROMPT: "Respond to this",
|
||||
},
|
||||
},
|
||||
);
|
||||
const log = await new Response(child.stdout).text();
|
||||
await child.exited;
|
||||
return log;
|
||||
} finally {
|
||||
server.stop(true);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const SKIPPED = "No trigger found, skipping remaining steps";
|
||||
const STARTED = "Preparing with mode: agent";
|
||||
|
||||
test("a prompt doesn't run when a maintainer edits or deletes someone else's comment", async () => {
|
||||
for (const action of ["edited", "deleted"]) {
|
||||
const log = await runWithPrompt("issue_comment", {
|
||||
action,
|
||||
repository,
|
||||
sender: writer,
|
||||
issue,
|
||||
comment: { id: 1, body: "x", user: outsider },
|
||||
});
|
||||
expect(log).toContain(SKIPPED);
|
||||
expect(log).not.toContain(STARTED);
|
||||
}
|
||||
});
|
||||
|
||||
test("a prompt runs on a new comment, and on events that have none", async () => {
|
||||
const events: [string, object][] = [
|
||||
[
|
||||
"issue_comment",
|
||||
{ action: "created", issue, comment: { id: 1, body: "x", user: writer } },
|
||||
],
|
||||
// With a prompt, label_trigger doesn't limit which label starts a run.
|
||||
["issues", { action: "labeled", issue, label: { name: "triage" } }],
|
||||
];
|
||||
for (const [eventName, event] of events) {
|
||||
const log = await runWithPrompt(eventName, {
|
||||
repository,
|
||||
sender: writer,
|
||||
...event,
|
||||
});
|
||||
expect(log).toContain(STARTED);
|
||||
}
|
||||
});
|
||||
@@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
|
||||
import * as core from "@actions/core";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
appendFileSync,
|
||||
existsSync,
|
||||
linkSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
@@ -27,7 +29,9 @@ import {
|
||||
const KEYS = [
|
||||
"GITHUB_ACTION_PATH",
|
||||
"GITHUB_ENV",
|
||||
"GITHUB_OUTPUT",
|
||||
"GITHUB_PATH",
|
||||
"GITHUB_STEP_SUMMARY",
|
||||
"HOME",
|
||||
"XDG_CONFIG_HOME",
|
||||
"GIT_CONFIG_GLOBAL",
|
||||
@@ -154,6 +158,104 @@ describe("session guard", () => {
|
||||
expect(statSync(path).mode & 0o777).toBe(0o640);
|
||||
});
|
||||
|
||||
describe.each(["GITHUB_OUTPUT", "GITHUB_STEP_SUMMARY"])(
|
||||
"%s, which the action adds to after the session",
|
||||
(name) => {
|
||||
let path: string;
|
||||
|
||||
beforeEach(() => {
|
||||
path = join(dir, name);
|
||||
process.env[name] = path;
|
||||
writeFileSync(path, "by an earlier part\n");
|
||||
});
|
||||
|
||||
test("keeps what a session wrote", () => {
|
||||
const restore = snapshotSessionFiles();
|
||||
appendFileSync(path, "by the session\n");
|
||||
restore();
|
||||
expect(readFileSync(path, "utf8")).toBe(
|
||||
"by an earlier part\nby the session\n",
|
||||
);
|
||||
expect(warnings()).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps it if the session replaced the file", () => {
|
||||
const restore = snapshotSessionFiles();
|
||||
rmSync(path);
|
||||
writeFileSync(path, "by the session\n");
|
||||
restore();
|
||||
expect(readFileSync(path, "utf8")).toBe("by the session\n");
|
||||
expect(warnings()).toEqual([]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["a symlink", symlinkSync],
|
||||
["a hard link", linkSync],
|
||||
])("doesn't follow %s to a file later steps trust", (_, link) => {
|
||||
const restore = snapshotSessionFiles();
|
||||
rmSync(path);
|
||||
link(process.env.GITHUB_PATH!, path);
|
||||
restore();
|
||||
appendFileSync(path, "/tmp/shims\n");
|
||||
expect(readFileSync(process.env.GITHUB_PATH!, "utf8")).toBe(
|
||||
"/opt/tool\n",
|
||||
);
|
||||
expect(readFileSync(path, "utf8")).toBe(
|
||||
"by an earlier part\n/tmp/shims\n",
|
||||
);
|
||||
expect(warnings()[0]).toContain(name);
|
||||
});
|
||||
|
||||
test("doesn't follow a hard link to a file with the same content", () => {
|
||||
writeFileSync(path, "");
|
||||
writeFileSync(process.env.GITHUB_ENV!, "");
|
||||
const restore = snapshotSessionFiles();
|
||||
rmSync(path);
|
||||
linkSync(process.env.GITHUB_ENV!, path);
|
||||
restore();
|
||||
appendFileSync(path, "X=1\n");
|
||||
expect(readFileSync(process.env.GITHUB_ENV!, "utf8")).toBe("");
|
||||
expect(warnings()[0]).toContain(name);
|
||||
});
|
||||
|
||||
test("puts back a file the session deleted", () => {
|
||||
const restore = snapshotSessionFiles();
|
||||
rmSync(path);
|
||||
restore();
|
||||
expect(readFileSync(path, "utf8")).toBe("by an earlier part\n");
|
||||
});
|
||||
|
||||
test("says nothing if there was no file before and after", () => {
|
||||
rmSync(path);
|
||||
snapshotSessionFiles()();
|
||||
expect(existsSync(path)).toBe(false);
|
||||
expect(warnings()).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps what a session wrote to a file that had a second name before", () => {
|
||||
linkSync(path, join(dir, "second-name"));
|
||||
const restore = snapshotSessionFiles();
|
||||
appendFileSync(path, "by the session\n");
|
||||
restore();
|
||||
expect(readFileSync(path, "utf8")).toContain("by the session\n");
|
||||
expect(warnings()).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps a link that was there before, and what a session wrote to it", () => {
|
||||
const target = join(dir, "target");
|
||||
rmSync(path);
|
||||
writeFileSync(target, "");
|
||||
symlinkSync(target, path);
|
||||
const restore = snapshotSessionFiles();
|
||||
appendFileSync(path, "by the session\n");
|
||||
restore();
|
||||
expect(lstatSync(path).isSymbolicLink()).toBe(true);
|
||||
expect(readFileSync(target, "utf8")).toBe("by the session\n");
|
||||
expect(warnings()).toEqual([]);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
describe("a config that was already a symlink", () => {
|
||||
let target: string;
|
||||
let link: string;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
checkContainsTrigger,
|
||||
escapeRegExp,
|
||||
isModeration,
|
||||
} from "../src/github/validation/trigger";
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import {
|
||||
@@ -625,3 +626,98 @@ describe("checkContainsTrigger when the text is someone else's", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isModeration", () => {
|
||||
const event = (
|
||||
base: ParsedGitHubContext,
|
||||
kind: "comment" | "review",
|
||||
eventAction: string,
|
||||
author: string | null,
|
||||
actor: string,
|
||||
) =>
|
||||
({
|
||||
...base,
|
||||
eventAction,
|
||||
actor,
|
||||
payload: {
|
||||
...base.payload,
|
||||
action: eventAction,
|
||||
[kind]: {
|
||||
...(base.payload as any)[kind],
|
||||
user: author && { login: author },
|
||||
},
|
||||
},
|
||||
}) as ParsedGitHubContext;
|
||||
const comments = [
|
||||
mockIssueCommentContext,
|
||||
mockPullRequestReviewCommentContext,
|
||||
];
|
||||
|
||||
it("is true when someone else edits or deletes a comment", () => {
|
||||
for (const base of comments) {
|
||||
for (const action of ["edited", "deleted"]) {
|
||||
for (const author of ["outsider", null]) {
|
||||
expect(
|
||||
isModeration(event(base, "comment", action, author, "maintainer")),
|
||||
).toBe(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("is true when someone else edits or dismisses a review", () => {
|
||||
for (const action of ["edited", "dismissed"]) {
|
||||
expect(
|
||||
isModeration(
|
||||
event(
|
||||
mockPullRequestReviewContext,
|
||||
"review",
|
||||
action,
|
||||
"outsider",
|
||||
"maintainer",
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("is true for any deleted comment", () => {
|
||||
for (const base of comments) {
|
||||
expect(
|
||||
isModeration(event(base, "comment", "deleted", "writer", "writer")),
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("is false for a person's own edit", () => {
|
||||
for (const base of comments) {
|
||||
expect(
|
||||
isModeration(event(base, "comment", "edited", "Writer", "writer")),
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("is false for a new comment or review, whatever login its app has", () => {
|
||||
for (const base of comments) {
|
||||
expect(
|
||||
isModeration(event(base, "comment", "created", "app[bot]", "App")),
|
||||
).toBe(false);
|
||||
}
|
||||
expect(
|
||||
isModeration(
|
||||
event(
|
||||
mockPullRequestReviewContext,
|
||||
"review",
|
||||
"submitted",
|
||||
"app[bot]",
|
||||
"App",
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("is false for events with no comment or review", () => {
|
||||
expect(isModeration(mockIssueLabeledContext)).toBe(false);
|
||||
expect(isModeration(mockIssueOpenedContext)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user