Compare commits

...
2 Commits
Author SHA1 Message Date
e5c0fcd418 Restore GITHUB_OUTPUT when the session ends (#2121)
* Restore GITHUB_OUTPUT when the session ends

An output that a session left unfinished kept the runner from reading the action's
own outputs after it, so the app token wasn't revoked.

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

* Say in the log that outputs a session wrote are dropped

The warning now points to --json-schema for passing results on.

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

---------

Co-authored-by: Claude <[email protected]>
2026-11-23 17:31:06 -08:00
eb56b6666f Log text as plain text, and post buffered comments in the run step (#2122)
Text that the action logs, such as a prompt, a comment or a file name, could
contain workflow commands. Console output now shows them as plain text, and
git's output goes through console. The prompt input is no longer logged.

Buffered inline comments are posted at the end of the run step instead of in
a step of their own, so they aren't posted when a run is cancelled or times
out. The issue triage recipe passes only the issue's number.

Co-authored-by: Claude <[email protected]>
2026-11-23 15:51:21 -08:00
20 changed files with 519 additions and 126 deletions
-18
View File
@@ -447,24 +447,6 @@ runs:
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/cleanup-ssh-signing.ts
- name: Post buffered inline comments
if: always() && inputs.classify_inline_comments != 'false'
shell: bash
env:
BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0"
GITHUB_TOKEN: ${{ steps.run.outputs.github_token || inputs.github_token || github.token }}
REPO_OWNER: ${{ github.event.repository.owner.login }}
REPO_NAME: ${{ github.event.repository.name }}
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
run: |
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
"$BUN_BIN" --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/post-buffered-inline-comments.ts
- name: Revoke app token
if: always() && inputs.github_token == '' && steps.run.outputs.github_token != '' && steps.run.outputs.skipped_due_to_workflow_validation_mismatch != 'true'
shell: bash
+3 -2
View File
@@ -1,3 +1,4 @@
import * as core from "@actions/core";
import { spawnSync } from "child_process";
import { readdirSync, readFileSync } from "fs";
@@ -109,8 +110,8 @@ export function stopDescendants(): void {
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(", ")}`,
core.warning(
`Processes of another user could not be stopped: ${left.join(", ")}`,
);
}
}
+2
View File
@@ -7,6 +7,7 @@ import { setupClaudeCodeSettings } from "./setup-claude-code-settings";
import { validateEnvironmentVariables } from "./validate-env";
import { installPlugins } from "./install-plugins";
import { onCancel } from "./cancel";
import { escapeConsoleOutput } from "./log";
import { setExecutionFileOutputIfPresent } from "./execution-file";
import { setupWorkloadIdentity } from "./workload-identity";
import type { WorkloadIdentityHandle } from "./workload-identity";
@@ -95,5 +96,6 @@ async function run() {
}
if (import.meta.main) {
escapeConsoleOutput();
run();
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Changes what the runner would take for a workflow command, so that it's only shown.
* The runner reads `::name::` at the start of a line and `##[name]` anywhere in it.
*/
export function escapeWorkflowCommands(text: string): string {
return (
text
.replaceAll("##[", "##[\\")
// The runner skips spaces first. This skips all that isn't visible ASCII.
.replace(/^([^\x21-\x7e\r\n]*)::/gm, "$1\\::")
);
}
/**
* Keeps text that is logged, such as a comment or a file name, from running workflow
* commands. To run one, use @actions/core, which doesn't go through console.
*/
export function escapeConsoleOutput(): void {
for (const method of ["log", "info", "warn", "error", "debug"] as const) {
const write = console[method].bind(console);
console[method] = (...args: unknown[]) => {
const text = args.map((arg) =>
typeof arg === "string" ? arg : Bun.inspect(arg, { depth: 2 }),
);
write(escapeWorkflowCommands(text.join(" ")));
};
}
}
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bun
import { spawnSync } from "node:child_process";
import { describe, expect, test } from "bun:test";
import { escapeWorkflowCommands } from "../src/log";
describe("escapeWorkflowCommands", () => {
test.each([
["::warning::x", "\\::warning::x"],
["a\n::warning::x", "a\n\\::warning::x"],
["a\r::warning::x", "a\r\\::warning::x"],
["a\r\n \t::warning::x", "a\r\n \t\\::warning::x"],
[" \u0085 ::warning::x", " \u0085 \\::warning::x"],
["::warning file=a::x", "\\::warning file=a::x"],
["a ##[warning]x", "a ##[\\warning]x"],
["##[##[warning]x", "##[\\##[\\warning]x"],
["####[warning]x", "####[\\warning]x"],
])("escapes %j", (text, escaped) => {
expect(escapeWorkflowCommands(text)).toBe(escaped);
});
test.each(["std::string::npos", "## [x]", "a: b", "- see ::x", ""])(
"keeps %j",
(text) => {
expect(escapeWorkflowCommands(text)).toBe(text);
},
);
});
test("escapeConsoleOutput escapes what console writes, and not @actions/core", () => {
const { stdout, stderr } = spawnSync(
"bun",
[
"-e",
`import { escapeConsoleOutput } from "./src/log";
import * as core from "@actions/core";
escapeConsoleOutput();
console.log("a\\n::warning::b", { c: "##[warning]d" }, "100%s");
console.error("failed:", new Error("\\n::warning::e"));
try { await Bun.$\`git no-such-command\`.quiet(); } catch (e) { console.error(e); }
core.warning("f\\n::warning::g");`,
],
{ cwd: new URL("..", import.meta.url).pathname, encoding: "utf8" },
);
expect(stdout).toContain("a\n\\::warning::b");
expect(stdout).toContain("##[\\warning]d");
expect(stdout).toContain("100%s");
expect(stdout).toContain("\n::warning::f%0A::warning::g\n");
expect(stderr).toContain("\n\\::warning::e");
expect(stderr).toContain("no-such-command' is not a git command");
});
+2
View File
@@ -105,6 +105,8 @@ You can access any GitHub context variable using the standard GitHub Actions syn
- `${{ github.base_ref }}` - Base branch for PRs
- `${{ github.head_ref }}` - Head branch for PRs
Titles, descriptions, comments and branch names can come from people without write access. Prefer to pass only numbers, and let Claude read the rest with its tools, especially in a public repository.
## Advanced Configuration with claude_args
For more control over Claude's behavior, use the `claude_args` input to pass CLI arguments directly:
+2 -2
View File
@@ -134,7 +134,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. 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.
Steps that run after Claude, including post steps such as `actions/checkout`'s cleanup, trust `GITHUB_ENV`, `GITHUB_PATH` and git's config files, and the action's own outputs in `GITHUB_OUTPUT`. 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 `--json-schema` to pass results on. What a session writes to `GITHUB_OUTPUT` is dropped, because the action passes on only its own outputs. What a session writes to `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 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.
@@ -145,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.
- 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`.
- 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. Later `always()` and post steps still run, the tracking comment isn't updated, and buffered inline comments aren't posted. 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.
+3 -6
View File
@@ -409,11 +409,8 @@ jobs:
prompt: |
REPO: ${{ github.repository }}
ISSUE NUMBER: ${{ github.event.issue.number }}
TITLE: ${{ github.event.issue.title }}
BODY: ${{ github.event.issue.body }}
AUTHOR: ${{ github.event.issue.user.login }}
Analyze this new issue and:
Read this new issue with `./scripts/gh.sh issue view`, then:
1. Determine if it's a bug report, feature request, or question
2. Assess priority (critical, high, medium, low)
3. Suggest appropriate labels
@@ -437,7 +434,7 @@ jobs:
**Key Configuration:**
- Triggered on new issues
- Issue context in prompt
- Claude reads the issue itself. The prompt only has its number, because anyone who can open an issue controls its title and body
- Label management capabilities
- Requires `scripts/gh.sh` and `scripts/edit-issue-labels.sh` in your repo (see this repo's `scripts/` directory for examples)
@@ -590,7 +587,7 @@ prompt: |
### Common Tool Permissions
- **PR Comments**: `Bash(gh pr comment:*)`
- **Inline Comments**: `mcp__github_inline_comment__create_inline_comment` — pass `confirmed: true` to post immediately. When omitted, the comment is buffered and classified after the session ends (real review comments post, test/probe comments are filtered). This prevents subagent test comments from reaching PRs. To disable classification entirely, set `classify_inline_comments: 'false'` on the action.
- **Inline Comments**: `mcp__github_inline_comment__create_inline_comment` — pass `confirmed: true` to post immediately. When omitted, the comment is buffered and classified after the session ends (real review comments post, test/probe comments are filtered). If the run is cancelled, times out or crashes first, buffered comments are not posted. This prevents subagent test comments from reaching PRs. To disable classification entirely, set `classify_inline_comments: 'false'` on the action.
- **File Operations**: `Read,Write,Edit`
- **Git Operations**: `Bash(git:*)`
+9
View File
@@ -1,3 +1,12 @@
/** For an input that has no environment variable of its own. */
export function getActionInput(name: string): string | undefined {
try {
return JSON.parse(process.env.ALL_INPUTS ?? "{}")[name] || undefined;
} catch {
return undefined;
}
}
export function collectActionInputsPresence(): string {
const inputDefaults: Record<string, string> = {
trigger_phrase: "@claude",
@@ -1,4 +1,3 @@
#!/usr/bin/env bun
/**
* Reads buffered inline-comment calls from /tmp/inline-comments-buffer.jsonl,
* classifies each as "real review" vs "test/probe" using Haiku, and posts
@@ -9,9 +8,12 @@
* preserves backward compatibility — before this change, all unconfirmed
* calls posted immediately.
*/
import * as core from "@actions/core";
import { readFileSync } from "fs";
import { createOctokit } from "../github/api/client";
import { isEntityContext, type GitHubContext } from "../github/context";
import { redactSecrets } from "../github/utils/sanitizer";
import { getActionInput } from "./collect-inputs";
const BUFFER_PATH = "/tmp/inline-comments-buffer.jsonl";
@@ -44,10 +46,11 @@ Comments:
`;
async function classifyComments(bodies: string[]): Promise<boolean[] | null> {
const apiKey = process.env.ANTHROPIC_API_KEY;
// Not from the environment, where it can be a key for another ANTHROPIC_BASE_URL.
const apiKey = getActionInput("anthropic_api_key");
if (!apiKey) {
console.log(
"ANTHROPIC_API_KEY not set — skipping classification, posting all unconfirmed comments",
"anthropic_api_key not set — skipping classification, posting all unconfirmed comments",
);
return null;
}
@@ -144,10 +147,18 @@ async function postComment(
}
}
async function main() {
export async function postBufferedInlineComments({
context,
githubToken,
bufferPath = BUFFER_PATH,
}: {
context: GitHubContext;
githubToken: string;
bufferPath?: string;
}): Promise<void> {
let raw: string;
try {
raw = readFileSync(BUFFER_PATH, "utf8");
raw = readFileSync(bufferPath, "utf8");
} catch {
console.log("No buffered inline comments");
return;
@@ -165,17 +176,13 @@ async function main() {
console.log(`Found ${comments.length} buffered inline comment(s)`);
const githubToken = process.env.GITHUB_TOKEN;
const owner = process.env.REPO_OWNER;
const repo = process.env.REPO_NAME;
const prNumber = process.env.PR_NUMBER;
if (!githubToken || !owner || !repo || !prNumber) {
console.log(
"::warning::Missing GITHUB_TOKEN/REPO_OWNER/REPO_NAME/PR_NUMBER — cannot post buffered comments",
if (!isEntityContext(context) || !context.isPR) {
core.warning(
"The event is not for a pull request — cannot post buffered comments",
);
return;
}
const { owner, repo } = context.repository;
// Partition: confirmed=false are never posted; the rest are candidates
const neverPost = comments.filter((c) => c.confirmed === false);
@@ -199,11 +206,13 @@ async function main() {
verdicts === null ? [] : candidates.filter((_, i) => verdicts[i] === false);
if (filtered.length > 0) {
console.log(
`::warning::${filtered.length} buffered comment(s) classified as test/probe — NOT posted:`,
core.warning(
`${filtered.length} buffered comment(s) classified as test/probe — NOT posted:`,
);
for (const c of filtered) {
console.log(` [${c.path}:${c.line}] ${c.body.slice(0, 120)}`);
console.log(
` [${c.path}:${c.line}] ${redactSecrets(c.body).slice(0, 120)}`,
);
}
}
@@ -213,7 +222,7 @@ async function main() {
}
const octokit = createOctokit(githubToken).rest;
const pull_number = parseInt(prNumber, 10);
const pull_number = context.entityNumber;
const pr = await octokit.pulls.get({ owner, repo, pull_number });
const headSha = pr.data.head.sha;
@@ -227,8 +236,3 @@ async function main() {
}
console.log(`Posted ${posted}/${toPost.length}`);
}
main().catch((e) => {
console.error("post-buffered-inline-comments failed:", e);
process.exit(1);
});
+22 -5
View File
@@ -64,6 +64,7 @@ import {
import { validateBranchName } from "../github/operations/branch";
import type { BranchInfo } from "../github/operations/branch";
import { collectActionInputsPresence } from "./collect-inputs";
import { postBufferedInlineComments } from "./post-buffered-inline-comments";
import { updateCommentLink } from "./update-comment-link";
import { formatTurnsFromData } from "./format-turns";
import type { Turn } from "./format-turns";
@@ -76,6 +77,7 @@ import { setupClaudeCodeSettings } from "../../base-action/src/setup-claude-code
import { installPlugins } from "../../base-action/src/install-plugins";
import { preparePrompt } from "../../base-action/src/prepare-prompt";
import { onCancel } from "../../base-action/src/cancel";
import { escapeConsoleOutput } from "../../base-action/src/log";
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";
@@ -205,21 +207,23 @@ async function run() {
// 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 restoreSessionFiles: (() => void) | undefined;
let hadSession = false;
let isFinishing = false;
// Revoking the app token depends on this output, and a session can write it.
// Revoking the app token depends on this output. A session can write it, and what it
// wrote is still there if the file could not be restored.
const keepRevocationOn = () =>
core.setOutput("skipped_due_to_workflow_validation_mismatch", "false");
onCancel(
[
() => restoreSessionFiles?.({ cancelled: true }),
() => restoreSessionFiles?.(),
() => 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.
// The same goes for this one.
() => core.setOutput("conclusion", claudeSuccess ? "success" : "failure"),
clearSessionState,
() => workloadIdentity?.stop(),
@@ -300,7 +304,6 @@ async function run() {
: !!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}`);
if (!containsTrigger) {
@@ -481,6 +484,7 @@ async function run() {
);
let claudeResult: ClaudeRunResult;
hadSession = true;
try {
claudeResult = await runClaude(promptConfig.path, {
claudeArgs: prepareResult.claudeArgs,
@@ -574,9 +578,22 @@ async function run() {
// Set remaining action-level outputs
core.setOutput("branch_name", claudeBranch);
core.setOutput("github_token", githubToken);
// Last, because the step that revokes the app token needs the outputs. This isn't a
// step of its own, so that only the run step is given the API key.
if (hadSession && context?.inputs.classifyInlineComments && githubToken) {
try {
await postBufferedInlineComments({ context, githubToken });
} catch (error) {
core.setFailed(
`Posting buffered inline comments failed: ${redactSecrets(String(error))}`,
);
}
}
}
}
if (import.meta.main) {
escapeConsoleOutput();
run();
}
+2
View File
@@ -508,6 +508,8 @@ export async function fetchGitHubData({
// Use git hash-object to compute the SHA for the current file content
const sha = execFileSync("git", ["hash-object", file.path], {
encoding: "utf-8",
// Its errors name the file, so they are only logged below.
stdio: ["ignore", "pipe", "pipe"],
}).trim();
return {
...file,
+14 -4
View File
@@ -3,6 +3,16 @@ import { GITHUB_SERVER_URL } from "../api/config";
import { encodeBranchNameForUrl } from "./comments/common";
import { $ } from "bun";
/** Git's output can hold file names, so it's logged through console. */
async function git(...args: string[]): Promise<void> {
const result = await $`git ${args}`.quiet().nothrow();
const output = `${result.stdout}${result.stderr}`.trim();
if (output) console.log(output);
if (result.exitCode !== 0) {
throw new Error(`Command failed: git ${args.join(" ")}`);
}
}
async function pushLfsObjects(branch: string): Promise<void> {
let tracked: string;
try {
@@ -10,7 +20,7 @@ async function pushLfsObjects(branch: string): Promise<void> {
} catch {
return; // Git LFS isn't installed here
}
if (tracked.trim()) await $`git lfs push origin ${branch}`;
if (tracked.trim()) await git("lfs", "push", "origin", branch);
}
export async function checkAndCommitOrDeleteBranch(
@@ -102,18 +112,18 @@ export async function checkAndCommitOrDeleteBranch(
console.log("Found uncommitted changes, committing them...");
// Add all changes, minus anything restored from the base branch
await $`git add -A ${pathspecArgs}`;
await git("add", "-A", ...pathspecArgs);
// Commit with a descriptive message
const runId = process.env.GITHUB_RUN_ID || "unknown";
const commitMessage = `Auto-commit: Save uncommitted changes from Claude\n\nRun ID: ${runId}`;
await $`git commit -m ${commitMessage}`;
await git("commit", "-m", commitMessage);
// Hooks are off by now, and Git LFS uploads from a hook.
await pushLfsObjects(claudeBranch);
// Push the changes
await $`git push origin ${claudeBranch}`;
await git("push", "origin", claudeBranch);
console.log(
"✅ Successfully committed and pushed uncommitted changes",
+28 -5
View File
@@ -7,7 +7,10 @@
*/
import { $ } from "bun";
import { execFileSync } from "child_process";
import { execFileSync, spawnSync } from "child_process";
import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import type { ParsedGitHubContext } from "../context";
import { isPullRequestEvent } from "../context";
import { retryWithBackoff } from "../../utils/retry";
@@ -137,16 +140,36 @@ export function validateBranchName(branchName: string): void {
}
/**
* Executes a git command safely using execFileSync to avoid shell interpolation.
* Executes a git command safely using spawnSync to avoid shell interpolation.
*
* Security: execFileSync passes arguments directly to the git binary without
* Security: spawnSync passes arguments directly to the git binary without
* invoking a shell, preventing command injection attacks where malicious input
* could be interpreted as shell commands (e.g., branch names containing `;`, `|`, `&&`).
* Git's output can hold commit subjects and file names, so it's logged through console.
*
* @param args - Git command arguments (e.g., ["checkout", "branch-name"])
*/
function execGit(args: string[], env: NodeJS.ProcessEnv = process.env): void {
execFileSync("git", args, { stdio: "inherit", env });
export function execGit(
args: string[],
env: NodeJS.ProcessEnv = process.env,
): void {
// Not a pipe, which a process that a hook leaves running would keep open
const dir = mkdtempSync(join(tmpdir(), "claude-git-"));
const path = join(dir, "output");
const fd = openSync(path, "wx");
try {
const { error, status } = spawnSync("git", args, {
stdio: ["inherit", fd, fd],
env,
});
const output = readFileSync(path, "utf8").trim();
if (output) console.log(output);
if (error) throw error;
if (status !== 0) throw new Error(`Command failed: git ${args.join(" ")}`);
} finally {
closeSync(fd);
rmSync(dir, { recursive: true, force: true });
}
}
export type BranchInfo = {
+6 -1
View File
@@ -52,7 +52,12 @@ type TrackedPaths = { files: Set<string>; dirs: Set<string> };
// links into one are recorded as placeholders.
function listTrackedPaths(): TrackedPaths {
const gitPathList = (args: string[]) =>
execFileSync("git", args, { encoding: "utf8", maxBuffer: Infinity })
execFileSync("git", args, {
encoding: "utf8",
maxBuffer: Infinity,
// Git's warnings can name files.
stdio: ["ignore", "pipe", "pipe"],
})
.split("\0")
.filter(Boolean);
const modified = new Set(
+59 -18
View File
@@ -3,6 +3,8 @@ import { execFileSync } from "child_process";
import {
closeSync,
constants,
fchmodSync,
fchownSync,
fstatSync,
lstatSync,
mkdirSync,
@@ -16,8 +18,14 @@ import {
import { homedir } from "os";
import { dirname, isAbsolute, join, resolve } from "path";
// 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 };
// The action itself writes to some after the session. A session may write to one that
// keeps its writes, but not put a link in its place.
type TrackedFile = {
label: string;
path: string;
isWritten?: boolean;
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.
@@ -26,6 +34,7 @@ type FileSnapshot = TrackedFile & {
wasSymlink: boolean;
content?: Buffer;
mode?: number;
owner?: { uid: number; gid: number };
names?: number;
// For a symlink: what it points to, and the regular file that ends up at.
link?: { target: string; resolved: string };
@@ -124,10 +133,12 @@ function filesLaterStepsTrust(): TrackedFile[] {
);
// The action adds to these after the session, so a link there would redirect that to
// a file later steps trust.
// a file later steps trust. What a session adds to GITHUB_OUTPUT could only pass for
// the action's own outputs, or keep the runner from reading those.
const written = ["GITHUB_OUTPUT", "GITHUB_STEP_SUMMARY"].flatMap((label) => {
const path = process.env[label];
return path ? [{ label, path, keepsWrites: true }] : [];
const keepsWrites = label === "GITHUB_STEP_SUMMARY";
return path ? [{ label, path, isWritten: true, keepsWrites }] : [];
});
const seen = new Set<string>();
@@ -161,6 +172,7 @@ function readSnapshot(file: TrackedFile): FileSnapshot {
wasSymlink,
content: readFileSync(fd),
mode: stats.mode & 0o777,
owner: { uid: stats.uid, gid: stats.gid },
names: stats.nlink,
...(wasSymlink && {
link: {
@@ -180,7 +192,16 @@ function isUnchanged(before: FileSnapshot, now: FileSnapshot): boolean {
if (before.state !== now.state || before.wasSymlink !== now.wasSymlink) {
return false;
}
return before.state !== "file" || before.content!.equals(now.content!);
if (before.state !== "file") return true;
// Without the right mode and owner, the action's own writes fail.
const { owner } = before;
if (
before.isWritten &&
(before.mode !== now.mode || owner!.uid !== now.owner!.uid)
) {
return false;
}
return before.content!.equals(now.content!);
}
/**
@@ -213,38 +234,53 @@ function isItsOwnFile(before: FileSnapshot): boolean {
}
}
/** The runner may be another user, so it needs the same mode and owner to read it. */
function writeAsBefore(path: string, before: FileSnapshot): void {
const fd = openSync(path, "wx", before.mode);
try {
writeFileSync(fd, before.content!);
fchmodSync(fd, before.mode!);
const { uid, gid } = fstatSync(fd);
const { owner } = before;
if (owner!.uid !== uid || owner!.gid !== gid) {
try {
fchownSync(fd, owner!.uid, owner!.gid);
} catch {
// Only root can give a file away
}
}
} finally {
closeSync(fd);
}
}
/**
* 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. 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.
* action runs git again. Replacing a file rather than writing to it means a session
* cannot redirect the write by swapping in a symlink.
*
* This stops a session that can only write through its tools. It is not a
* sandbox: code running as the runner's user can stop the action before it
* restores anything.
*/
export function snapshotSessionFiles(
beforeSession?: () => void,
): (options?: { cancelled: boolean }) => void {
export function snapshotSessionFiles(beforeSession?: () => void): () => void {
const files = filesLaterStepsTrust();
const snapshots = files.map(readSnapshot);
// What the action changes for the session goes back too, without a warning.
beforeSession?.();
const atStart = files.map(readSnapshot);
return ({ cancelled } = { cancelled: false }) => {
return () => {
const restored: string[] = [];
for (const [index, before] of snapshots.entries()) {
try {
const now = readSnapshot(before);
const dropsWrites = cancelled && before.label === "GITHUB_OUTPUT";
const ownFile = before.keepsWrites && isItsOwnFile(before);
if (ownFile && !dropsWrites) continue;
const isOwnFile = before.isWritten && isItsOwnFile(before);
if (isOwnFile && before.keepsWrites) continue;
// The file it leads to can have the same content so far.
const leadsElsewhere =
before.keepsWrites && !ownFile && now.state === "file";
before.isWritten && !isOwnFile && now.state === "file";
if (!leadsElsewhere && isUnchanged(before, now)) continue;
const changedBySession =
leadsElsewhere || !isUnchanged(atStart[index]!, now);
@@ -257,7 +293,7 @@ export function snapshotSessionFiles(
const path = restorePath(before);
rmSync(path, { force: true, recursive: true });
if (before.state === "file") {
writeFileSync(path, before.content!, { mode: before.mode });
writeAsBefore(path, before);
}
if (changedBySession) restored.push(before.label);
} catch (error) {
@@ -272,6 +308,11 @@ export function snapshotSessionFiles(
`The session changed files that later steps trust, so they were restored: ${restored.join(", ")}`,
);
}
if (restored.includes("GITHUB_OUTPUT")) {
core.warning(
"What a session writes to GITHUB_OUTPUT is dropped. To pass results on, use --json-schema in claude_args.",
);
}
};
}
+20 -2
View File
@@ -57,6 +57,24 @@ describe("action metadata", () => {
);
});
test("should not pass credentials from inputs to steps after the run step", () => {
const steps = readMetadata("action.yml").split(/^ - name: /m);
const later = steps.slice(
steps.findIndex((step) => step.startsWith("Run Claude Code Action")) + 1,
);
expect(later.length).toBeGreaterThan(0);
for (const step of later) {
const body = step.replace(/^ if: .+$/m, "");
expect(body).not.toMatch(
/inputs\.|env\.|ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN/,
);
if (body.includes("outputs.github_token")) {
expect(step).toContain("inputs.github_token == ''");
}
}
});
test("should keep restrict_untrusted_prs on by default and pass it to the run step", () => {
const metadata = readMetadata("action.yml");
@@ -85,7 +103,7 @@ describe("action metadata", () => {
.split("\n")
.filter((line) => line.includes("${GITHUB_ACTION_PATH}/src/"));
expect(commands).toHaveLength(3);
expect(commands).toHaveLength(2);
for (const command of commands) {
expect(command).toContain(
' --no-env-file --config="${GITHUB_ACTION_PATH}/bunfig.toml"' +
@@ -99,7 +117,7 @@ describe("action metadata", () => {
test("should turn off Bun's transpiler cache for the action's scripts", () => {
const steps = stepsRunningScripts(path);
expect(steps).toHaveLength(path === "action.yml" ? 3 : 1);
expect(steps).toHaveLength(path === "action.yml" ? 2 : 1);
for (const step of steps) {
expect(step).toMatch(
/^ env:\n(?: {8}.*\n|\n)*? {8}BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0"$/m,
+59
View File
@@ -0,0 +1,59 @@
import { afterEach, beforeEach, expect, spyOn, test } from "bun:test";
import { execFileSync } from "node:child_process";
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { execGit } from "../src/github/operations/branch";
const originalCwd = process.cwd();
let dir: string;
let logSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "exec-git-"));
process.chdir(dir);
const git = (...args: string[]) => execFileSync("git", args);
git("init", "-q", "-b", "main");
git("config", "user.email", "[email protected]");
git("config", "user.name", "Test");
git("commit", "-q", "--allow-empty", "-m", "base");
git("checkout", "-q", "--detach");
git("commit", "-q", "--allow-empty", "-m", "a subject");
logSpy = spyOn(console, "log").mockImplementation(() => {});
});
afterEach(() => {
logSpy.mockRestore();
process.chdir(originalCwd);
rmSync(dir, { recursive: true, force: true });
});
test("execGit logs git's output, which can hold a commit's subject, through console", () => {
execGit(["checkout", "main", "--"]);
expect(String(logSpy.mock.calls)).toContain("a subject");
});
test("execGit throws when git fails, and logs why", () => {
expect(() => execGit(["checkout", "no-such-branch", "--"])).toThrow(
"Command failed: git checkout no-such-branch --",
);
expect(String(logSpy.mock.calls)).toContain("no-such-branch");
});
test("execGit doesn't wait for a process that a hook leaves running", () => {
mkdirSync(join(dir, ".git/hooks"), { recursive: true });
const hook = join(dir, ".git/hooks/post-checkout");
writeFileSync(hook, "#!/bin/sh\nsleep 20 &\necho $! > pid\n", {
mode: 0o755,
});
const start = Date.now();
execGit(["checkout", "main", "--"]);
process.kill(Number(readFileSync(join(dir, "pid"), "utf8")));
expect(Date.now() - start).toBeLessThan(10_000);
});
@@ -0,0 +1,95 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { postBufferedInlineComments } from "../src/entrypoints/post-buffered-inline-comments";
import { createMockContext } from "./mockContext";
describe("postBufferedInlineComments", () => {
let requests: { url: string; body: any; key: string | null }[];
let spies: { mockRestore: () => void }[];
let verdicts: boolean[];
let dir: string;
let bufferPath: string;
const names = ["ALL_INPUTS", "ANTHROPIC_API_KEY"];
const savedEnv = names.map((name) => [name, process.env[name]] as const);
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "buffered-comments-"));
bufferPath = join(dir, "buffer.jsonl");
requests = [];
verdicts = [true, false];
process.env.ANTHROPIC_API_KEY = "key-from-environment";
const answer = async (input: any, init: any) => {
const url = String(input?.url ?? input);
const headers = new Headers(init?.headers);
const body = init?.body ? JSON.parse(init.body) : undefined;
requests.push({ url, body, key: headers.get("x-api-key") });
return Response.json(
url.includes("/v1/messages")
? { content: [{ type: "text", text: JSON.stringify(verdicts) }] }
: { id: 1, head: { sha: "head-sha" } },
);
};
spies = [
spyOn(globalThis, "fetch").mockImplementation(answer as any),
spyOn(console, "log").mockImplementation(() => {}),
spyOn(process.stdout, "write").mockImplementation(() => true),
];
writeFileSync(
bufferPath,
[
{ path: "a.ts", line: 1, body: "real" },
{ path: "b.ts", line: 2, body: "test" },
{ path: "c.ts", line: 3, body: "never", confirmed: false },
]
.map((comment) => JSON.stringify(comment) + "\n")
.join(""),
);
});
afterEach(() => {
spies.forEach((spy) => spy.mockRestore());
for (const [name, value] of savedEnv) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
rmSync(dir, { recursive: true, force: true });
});
const run = (isPR = true) =>
postBufferedInlineComments({
context: createMockContext({ isPR, entityNumber: 7 }),
bufferPath,
githubToken: "token",
});
const posted = () =>
requests
.filter(({ url }) => url.endsWith("/pulls/7/comments"))
.map(({ body }) => body.path);
test("classifies with the key from the input and posts the real ones", async () => {
process.env.ALL_INPUTS = JSON.stringify({ anthropic_api_key: "key" });
await run();
expect(
requests.filter(({ key }) => key).map(({ url, key }) => [url, key]),
).toEqual([["https://api.anthropic.com/v1/messages", "key"]]);
expect(posted()).toEqual(["a.ts"]);
});
test("posts nothing on an issue", async () => {
await run(false);
expect(requests).toEqual([]);
});
test.each([undefined, "{}", "not JSON"])(
"posts all candidates if the inputs are %j, without sending a key from the environment",
async (inputs) => {
delete process.env.ALL_INPUTS;
if (inputs) process.env.ALL_INPUTS = inputs;
await run();
expect(requests.filter(({ key }) => key)).toEqual([]);
expect(posted()).toEqual(["a.ts", "b.ts"]);
},
);
});
+88 -41
View File
@@ -3,6 +3,7 @@ import * as core from "@actions/core";
import { execFileSync } from "child_process";
import {
appendFileSync,
chmodSync,
existsSync,
linkSync,
lstatSync,
@@ -169,25 +170,6 @@ describe("session guard", () => {
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],
@@ -231,31 +213,96 @@ describe("session guard", () => {
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("GITHUB_STEP_SUMMARY, which keeps what a session wrote", () => {
let path: string;
beforeEach(() => {
path = process.env.GITHUB_STEP_SUMMARY = join(dir, "summary");
writeFileSync(path, "by an earlier part\n");
});
test("to the file", () => {
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("to one it put in the file's place", () => {
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("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("through a link that was there before", () => {
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("GITHUB_OUTPUT, which the action's own outputs go to", () => {
let path: string;
beforeEach(() => {
path = process.env.GITHUB_OUTPUT = join(dir, "output");
writeFileSync(path, "by_action=1\n");
chmodSync(path, 0o640);
});
test.each([
["wrote to it", () => appendFileSync(path, "report<<EOF\n")],
["replaced it", () => (rmSync(path), writeFileSync(path, "x=1\n"))],
["made it read-only", () => chmodSync(path, 0o440)],
["made it unreadable", () => chmodSync(path, 0)],
])("restores it when a session %s", (_, inSession) => {
const restore = snapshotSessionFiles();
inSession();
restore();
expect(readFileSync(path, "utf8")).toBe("by_action=1\n");
expect(statSync(path).mode & 0o777).toBe(0o640);
expect(warnings()[0]).toContain("GITHUB_OUTPUT");
expect(warnings()[1]).toContain("--json-schema");
});
test("keeps a link that was there before", () => {
const target = join(dir, "target");
rmSync(path);
writeFileSync(target, "by_action=1\n");
symlinkSync(target, path);
const restore = snapshotSessionFiles();
appendFileSync(path, "x=1\n");
restore();
expect(lstatSync(path).isSymbolicLink()).toBe(true);
expect(readFileSync(target, "utf8")).toBe("by_action=1\n");
});
});
describe("a config that was already a symlink", () => {
let target: string;
let link: string;