fix(security): harden root file guards and host writes

This commit is contained in:
Peter Steinberger
2026-02-26 13:32:02 +01:00
parent 2ca2d5ab1c
commit e3385a6578
8 changed files with 387 additions and 81 deletions

View File

@@ -1,4 +1,3 @@
import { constants as fsConstants } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import {
@@ -29,7 +28,7 @@ import {
import { loadConfig, writeConfigFile } from "../../config/config.js";
import { resolveSessionTranscriptsDirForAgent } from "../../config/sessions/paths.js";
import { sameFileIdentity } from "../../infra/file-identity.js";
import { SafeOpenError, readLocalFileSafely } from "../../infra/fs-safe.js";
import { SafeOpenError, readLocalFileSafely, writeFileWithinRoot } from "../../infra/fs-safe.js";
import { assertNoPathAliasEscape } from "../../infra/path-alias-guards.js";
import { isNotFoundPathError } from "../../infra/path-guards.js";
import { DEFAULT_AGENT_ID, normalizeAgentId } from "../../routing/session-key.js";
@@ -121,13 +120,6 @@ type ResolvedAgentWorkspaceFilePath =
reason: string;
};
const SUPPORTS_NOFOLLOW = process.platform !== "win32" && "O_NOFOLLOW" in fsConstants;
const OPEN_WRITE_FLAGS =
fsConstants.O_WRONLY |
fsConstants.O_CREAT |
fsConstants.O_TRUNC |
(SUPPORTS_NOFOLLOW ? fsConstants.O_NOFOLLOW : 0);
async function resolveWorkspaceRealPath(workspaceDir: string): Promise<string> {
try {
return await fs.realpath(workspaceDir);
@@ -238,25 +230,6 @@ async function statFileSafely(filePath: string): Promise<FileMeta | null> {
}
}
async function writeFileSafely(filePath: string, content: string): Promise<void> {
const handle = await fs.open(filePath, OPEN_WRITE_FLAGS, 0o600);
try {
const [stat, lstat] = await Promise.all([handle.stat(), fs.lstat(filePath)]);
if (lstat.isSymbolicLink() || !stat.isFile()) {
throw new Error("unsafe file path");
}
if (stat.nlink > 1) {
throw new Error("hardlinked file path is not allowed");
}
if (!sameFileIdentity(stat, lstat)) {
throw new Error("path changed during write");
}
await handle.writeFile(content, "utf-8");
} finally {
await handle.close().catch(() => {});
}
}
async function listAgentFiles(workspaceDir: string, options?: { hideBootstrap?: boolean }) {
const files: Array<{
name: string;
@@ -729,7 +702,12 @@ export const agentsHandlers: GatewayRequestHandlers = {
}
const content = String(params.content ?? "");
try {
await writeFileSafely(resolvedPath.ioPath, content);
await writeFileWithinRoot({
rootDir: workspaceDir,
relativePath: name,
data: content,
encoding: "utf8",
});
} catch {
respond(
false,