Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion actions/setup/js/safe_outputs_handlers.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -806,7 +806,7 @@ function createHandlers(server, appendSafeOutput, config = {}) {
const stagedFileName = `${crypto.createHash("sha256").update(filePath).digest("hex")}${fileExt}`;
const targetPath = path.join(assetsDir, stagedFileName);
try {
writeGuardedFile(targetPath, fileContent);
writeGuardedFile(targetPath, fileContent, { mode: 0o600, directoryMode: 0o700 });
} catch (err) {
if (err && typeof err === "object" && "code" in err && err.code === ERR_VALIDATION) throw err;
throw new Error(`${ERR_SYSTEM}: Failed to copy file ${filePath} to ${targetPath}: ${getErrorMessage(err)}`, { cause: err });
Expand Down
8 changes: 7 additions & 1 deletion actions/setup/js/safe_outputs_handlers.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -826,7 +826,13 @@ describe("safe_outputs_handlers", () => {
expect(entry.size).toBe(Buffer.byteLength("test content"));
const stagedFile = path.join(testRunnerTemp, "gh-aw", "safeoutputs", "assets", `${crypto.createHash("sha256").update(testFile).digest("hex")}.png`);
expect(fs.readFileSync(stagedFile)).toEqual(Buffer.from("test content"));
expect(fs.statSync(stagedFile).mode & 0o777).toBe(0o600);
const stagedStat = fs.statSync(stagedFile);
expect(stagedStat.mode & 0o777).toBe(0o600);
expect(stagedStat.uid).toBe(process.getuid());
expect(stagedStat.gid).toBe(process.getgid());
for (const directory of [path.dirname(stagedFile), path.dirname(path.dirname(stagedFile)), path.dirname(path.dirname(path.dirname(stagedFile)))]) {
expect(fs.statSync(directory).mode & 0o777).toBe(0o700);
}
expect(entry.url).toContain("test-branch");

expect(result.content[0].type).toBe("text");
Expand Down
39 changes: 26 additions & 13 deletions actions/setup/js/symlink_guard.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,10 @@ function resolveIssueArtifactPath(filename) {
* @param {string} directory
* @param {boolean} create
* @param {(directoryPath: string) => T} operation
* @param {number} [directoryMode]
* @returns {T}
*/
function withGuardedDirectory(directory, create, operation) {
function withGuardedDirectory(directory, create, operation, directoryMode = 0o700) {
if (process.platform !== "linux") {
throw assetValidationError("Guarded asset access requires Linux descriptor-relative paths; macOS and Windows are unsupported");
}
Expand All @@ -151,12 +152,14 @@ function withGuardedDirectory(directory, create, operation) {
current = `/proc/self/fd/${parent.fd}/${component}`;
}
let stat;
let created = false;
try {
stat = lstatGuard(current);
} catch (error) {
if (!create || !error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") throw error;
try {
fs.mkdirSync(current, { mode: 0o700 });
fs.mkdirSync(current, { mode: directoryMode });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/codebase-design] directoryMode applies to every ancestor this call creates, not just the asset and Claim directories. On a first run, parents such as gh-aw/ or safeoutputs/ above assets would be created 0755, which is broader than the private 0700 the spec requires for guard-created subdirectories. Apply the wider mode only to the leaf directories the caller needs, or document why the ancestors must be traversable.

@copilot please address this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The staging caller now uses 0600/0700, keeping all newly created staging ancestors private. The separate publisher still uses its constrained publication pair outside the shared staging tree. Updated in 900bf5051c.

created = true;
} catch (mkdirError) {
if (!mkdirError || typeof mkdirError !== "object" || !("code" in mkdirError) || mkdirError.code !== "EEXIST") throw mkdirError;
}
Expand All @@ -168,6 +171,7 @@ function withGuardedDirectory(directory, create, operation) {
directories.push({ fd, filename: current, stat });
const opened = fs.fstatSync(fd);
if (opened.dev !== stat.dev || opened.ino !== stat.ino) throw assetValidationError("Asset directory changed while opening");
if (created) fs.fchmodSync(fd, directoryMode);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

directoryMode is applied to every newly created component while walking the full path, not just the asset-specific directory. For a fresh RUNNER_TEMP this can make shared parents such as gh-aw/safeoutputs mode 0755, exposing unrelated staging/configuration files to the unprivileged uploader. Please keep shared parents private and widen only the dedicated asset subtree.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Staging now uses the private 0600/0700 pair, so shared RUNNER_TEMP/gh-aw/safeoutputs ancestors created by the guard remain 0700. Updated in 900bf5051c.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conversely, an ancestor that already exists with the old default 0700 mode is never chmodded because created stays false. If RUNNER_TEMP is reused or another safe-output path created safeoutputs first, the 0644 file remains unreachable to the uploader and the original EACCES failure persists. Please ensure the dedicated asset path is traversable without relaxing unrelated existing directories.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ownership handoff now ensures the backend and uploader use the same runner UID/GID; existing private directories need no permission broadening. The Linux runner-identity test exercises writing and host-side reading without requiring root. Updated in 900bf5051c.

}
const verify = () => {
for (const directory of directories) {
Expand Down Expand Up @@ -230,18 +234,27 @@ function readGuardedFile(filename, maximumBytes = 10 * 1024 * 1024) {
* Exclusively create a staged/published file without following destination links.
* @param {string} filename
* @param {Buffer} content
* @param {{mode?: number, directoryMode?: number}} [options]
*/
function writeGuardedFile(filename, content) {
return withGuardedDirectory(path.dirname(filename), true, directory => {
const target = path.join(directory, path.basename(filename));
const fd = fs.openSync(target, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
try {
fs.fchmodSync(fd, 0o600);
fs.writeFileSync(fd, content);
} finally {
fs.closeSync(fd);
}
});
function writeGuardedFile(filename, content, { mode = 0o600, directoryMode = 0o700 } = {}) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/codebase-design] mode and directoryMode accept any number, so a future caller could publish 0666 or 0777 through the guard. Restrict them to the two allowed pairs (0o600/0o700 and 0o644/0o755) and add a test that rejects other values.

@copilot please address this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added validation for only the 0600/0700 and 0644/0755 pairs, with tests rejecting other and mismatched values before creating directories. Updated in 900bf5051c.

if (!((mode === 0o600 && directoryMode === 0o700) || (mode === 0o644 && directoryMode === 0o755))) {
throw assetValidationError("Invalid guarded asset permissions");
}
return withGuardedDirectory(
path.dirname(filename),
true,
directory => {
const target = path.join(directory, path.basename(filename));
const fd = fs.openSync(target, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
try {
fs.writeFileSync(fd, content);
fs.fchmodSync(fd, mode);
} finally {
fs.closeSync(fd);
}
},
directoryMode
);
}

module.exports = { lstatGuard, normalizeGuardedPath, resolveWorkspaceOrTmpPath, resolveIssueArtifactPath, validateUploadSourcePath, withGuardedDirectory, readGuardedFile, writeGuardedFile };
35 changes: 35 additions & 0 deletions actions/setup/js/symlink_guard.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const fs = require("fs");
const path = require("path");
const os = require("os");
const { execFileSync } = require("child_process");
const { lstatGuard, readGuardedFile, writeGuardedFile } = require("./symlink_guard.cjs");

Expand Down Expand Up @@ -148,6 +149,40 @@ describe("lstatGuard", () => {
}
});

it.skipIf(process.platform !== "linux")("creates private assets and directories despite restrictive umasks", () => {
for (const mask of ["000", "077"]) {
const target = path.resolve(tmpDir, `assets-${mask}`, "claims", "claim-1", "chart.png");
execFileSync(process.execPath, ["-e", 'process.umask(parseInt(process.argv[1], 8)); require(process.argv[2]).writeGuardedFile(process.argv[3], Buffer.from("chart"));', mask, path.resolve(__dirname, "symlink_guard.cjs"), target]);
const stat = fs.statSync(target);
expect(stat.mode & 0o777).toBe(0o600);
expect(stat.uid).toBe(process.getuid());
expect(stat.gid).toBe(process.getgid());
for (const directory of [path.dirname(target), path.dirname(path.dirname(target)), path.dirname(path.dirname(path.dirname(target))), path.resolve(tmpDir, `assets-${mask}`)]) {
expect(fs.statSync(directory).mode & 0o777).toBe(0o700);
}
expect(() => writeGuardedFile(target, Buffer.from("overwrite"))).toThrow("EEXIST");
expect(fs.readFileSync(target, "utf8")).toBe("chart");
}
expect(fs.statSync(tmpDir).mode & 0o777).toBe(0o700);
});

it("accepts only the private staging and published asset permission pairs", () => {
const publishTarget = path.join(tmpDir, "published", "chart.png");
writeGuardedFile(publishTarget, Buffer.from("chart"), { mode: 0o644, directoryMode: 0o755 });
expect(fs.statSync(publishTarget).mode & 0o777).toBe(0o644);
expect(fs.statSync(path.dirname(publishTarget)).mode & 0o777).toBe(0o755);

for (const options of [
{ mode: 0o666, directoryMode: 0o777 },
{ mode: 0o600, directoryMode: 0o755 },
{ mode: 0o644, directoryMode: 0o700 },
]) {
const target = path.join(tmpDir, "invalid", `${options.mode}-${options.directoryMode}`, "chart.png");
expect(() => writeGuardedFile(target, Buffer.from("chart"), options)).toThrow(expect.objectContaining({ code: "ERR_VALIDATION" }));
expect(fs.existsSync(path.dirname(target))).toBe(false);
}
});

it.each(["symlink", "regular"])("rejects a file swapped to a different %s between inspection and open", kind => {
const source = path.join(tmpDir, "source.png");
const sentinel = path.join(tmpDir, "sentinel.png");
Expand Down
2 changes: 1 addition & 1 deletion actions/setup/js/upload_assets.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ async function main() {

// Copy file to branch with target filename
try {
writeGuardedFile(targetFileName, fileContent);
writeGuardedFile(targetFileName, fileContent, { mode: 0o644, directoryMode: 0o755 });

// Add to git
await exec.exec("git", ["add", targetFileName]);
Expand Down
4 changes: 4 additions & 0 deletions actions/setup/js/upload_assets.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,10 @@ describe("upload_assets.cjs", () => {
}
expect(mockCore.setFailed).not.toHaveBeenCalled();
expect(fs.readFileSync(target, "utf8")).toBe("verified chart");
const publishedStat = fs.statSync(target);
expect(publishedStat.mode & 0o777).toBe(0o644);
expect(publishedStat.uid).toBe(process.getuid());
expect(publishedStat.gid).toBe(process.getgid());
expect(crypto.createHash("sha256").update(fs.readFileSync(target)).digest("hex")).toBe(sha);
});

Expand Down
Loading