Compare commits

...
1 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
4 changed files with 154 additions and 65 deletions
+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, 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`.
- 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.
+5 -4
View File
@@ -207,22 +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(),
+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.",
);
}
};
}
+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;