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,7 +1,10 @@
import syncFs from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import type { AgentTool } from "@mariozechner/pi-agent-core";
import { Type } from "@sinclair/typebox";
import { openBoundaryFile, type BoundaryFileOpenResult } from "../infra/boundary-file-read.js";
import { writeFileWithinRoot } from "../infra/fs-safe.js";
import { PATH_ALIAS_POLICIES, type PathAliasPolicy } from "../infra/path-alias-guards.js";
import { applyUpdateHunk } from "./apply-patch-update.js";
import { assertSandboxPath, resolveSandboxInputPath } from "./sandbox-paths.js";
@@ -235,9 +238,37 @@ function resolvePatchFileOps(options: ApplyPatchOptions): PatchFileOps {
mkdirp: (dir) => bridge.mkdirp({ filePath: dir, cwd: root }),
};
}
const workspaceOnly = options.workspaceOnly !== false;
return {
readFile: (filePath) => fs.readFile(filePath, "utf8"),
writeFile: (filePath, content) => fs.writeFile(filePath, content, "utf8"),
readFile: async (filePath) => {
if (!workspaceOnly) {
return await fs.readFile(filePath, "utf8");
}
const opened = await openBoundaryFile({
absolutePath: filePath,
rootPath: options.cwd,
boundaryLabel: "workspace root",
});
assertBoundaryRead(opened, filePath);
try {
return syncFs.readFileSync(opened.fd, "utf8");
} finally {
syncFs.closeSync(opened.fd);
}
},
writeFile: async (filePath, content) => {
if (!workspaceOnly) {
await fs.writeFile(filePath, content, "utf8");
return;
}
const relative = toRelativeWorkspacePath(options.cwd, filePath);
await writeFileWithinRoot({
rootDir: options.cwd,
relativePath: relative,
data: content,
encoding: "utf8",
});
},
remove: (filePath) => fs.rm(filePath),
mkdirp: (dir) => fs.mkdir(dir, { recursive: true }).then(() => {}),
};
@@ -298,6 +329,27 @@ function resolvePathFromCwd(filePath: string, cwd: string): string {
return path.normalize(resolveSandboxInputPath(filePath, cwd));
}
function toRelativeWorkspacePath(workspaceRoot: string, absolutePath: string): string {
const rootResolved = path.resolve(workspaceRoot);
const resolved = path.resolve(absolutePath);
const relative = path.relative(rootResolved, resolved);
if (!relative || relative === "." || relative.startsWith("..") || path.isAbsolute(relative)) {
throw new Error(`Path escapes sandbox root (${workspaceRoot}): ${absolutePath}`);
}
return relative;
}
function assertBoundaryRead(
opened: BoundaryFileOpenResult,
targetPath: string,
): asserts opened is Extract<BoundaryFileOpenResult, { ok: true }> {
if (opened.ok) {
return;
}
const reason = opened.reason === "validation" ? "unsafe path" : "path not found";
throw new Error(`Failed boundary read for ${targetPath} (${reason})`);
}
function toDisplayPath(resolved: string, cwd: string): string {
const relative = path.relative(cwd, resolved);
if (!relative || relative === "") {

View File

@@ -1,7 +1,9 @@
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { AgentToolResult } from "@mariozechner/pi-agent-core";
import { createEditTool, createReadTool, createWriteTool } from "@mariozechner/pi-coding-agent";
import { SafeOpenError, openFileWithinRoot, writeFileWithinRoot } from "../infra/fs-safe.js";
import { detectMime } from "../media/mime.js";
import { sniffMimeFromBase64 } from "../media/sniff-mime-from-base64.js";
import type { ImageSanitizationLimits } from "./image-sanitization.js";
@@ -665,6 +667,20 @@ export function createSandboxedEditTool(params: SandboxToolParams) {
return wrapToolParamNormalization(base, CLAUDE_PARAM_GROUPS.edit);
}
export function createHostWorkspaceWriteTool(root: string) {
const base = createWriteTool(root, {
operations: createHostWriteOperations(root),
}) as unknown as AnyAgentTool;
return wrapToolParamNormalization(base, CLAUDE_PARAM_GROUPS.write);
}
export function createHostWorkspaceEditTool(root: string) {
const base = createEditTool(root, {
operations: createHostEditOperations(root),
}) as unknown as AnyAgentTool;
return wrapToolParamNormalization(base, CLAUDE_PARAM_GROUPS.edit);
}
export function createOpenClawReadTool(
base: AnyAgentTool,
options?: OpenClawReadToolOptions,
@@ -741,6 +757,87 @@ function createSandboxEditOperations(params: SandboxToolParams) {
} as const;
}
function createHostWriteOperations(root: string) {
return {
mkdir: async (dir: string) => {
const relative = toRelativePathInRoot(root, dir, { allowRoot: true });
const resolved = relative ? path.resolve(root, relative) : path.resolve(root);
await assertSandboxPath({ filePath: resolved, cwd: root, root });
await fs.mkdir(resolved, { recursive: true });
},
writeFile: async (absolutePath: string, content: string) => {
const relative = toRelativePathInRoot(root, absolutePath);
await writeFileWithinRoot({
rootDir: root,
relativePath: relative,
data: content,
mkdir: true,
});
},
} as const;
}
function createHostEditOperations(root: string) {
return {
readFile: async (absolutePath: string) => {
const relative = toRelativePathInRoot(root, absolutePath);
const opened = await openFileWithinRoot({
rootDir: root,
relativePath: relative,
});
try {
return await opened.handle.readFile();
} finally {
await opened.handle.close().catch(() => {});
}
},
writeFile: async (absolutePath: string, content: string) => {
const relative = toRelativePathInRoot(root, absolutePath);
await writeFileWithinRoot({
rootDir: root,
relativePath: relative,
data: content,
mkdir: true,
});
},
access: async (absolutePath: string) => {
const relative = toRelativePathInRoot(root, absolutePath);
try {
const opened = await openFileWithinRoot({
rootDir: root,
relativePath: relative,
});
await opened.handle.close().catch(() => {});
} catch (error) {
if (error instanceof SafeOpenError && error.code === "not-found") {
throw createFsAccessError("ENOENT", absolutePath);
}
throw error;
}
},
} as const;
}
function toRelativePathInRoot(
root: string,
candidate: string,
options?: { allowRoot?: boolean },
): string {
const rootResolved = path.resolve(root);
const resolved = path.resolve(candidate);
const relative = path.relative(rootResolved, resolved);
if (relative === "" || relative === ".") {
if (options?.allowRoot) {
return "";
}
throw new Error(`Path escapes workspace root: ${candidate}`);
}
if (relative.startsWith("..") || path.isAbsolute(relative)) {
throw new Error(`Path escapes workspace root: ${candidate}`);
}
return relative;
}
function createFsAccessError(code: string, filePath: string): NodeJS.ErrnoException {
const error = new Error(`Sandbox FS error (${code}): ${filePath}`) as NodeJS.ErrnoException;
error.code = code;

View File

@@ -1,10 +1,4 @@
import {
codingTools,
createEditTool,
createReadTool,
createWriteTool,
readTool,
} from "@mariozechner/pi-coding-agent";
import { codingTools, createReadTool, readTool } from "@mariozechner/pi-coding-agent";
import type { OpenClawConfig } from "../config/config.js";
import type { ToolLoopDetectionConfig } from "../config/types.tools.js";
import { resolveMergedSafeBinProfileFixtures } from "../infra/exec-safe-bin-runtime-policy.js";
@@ -34,7 +28,8 @@ import {
} from "./pi-tools.policy.js";
import {
assertRequiredParams,
CLAUDE_PARAM_GROUPS,
createHostWorkspaceEditTool,
createHostWorkspaceWriteTool,
createOpenClawReadTool,
createSandboxedEditTool,
createSandboxedReadTool,
@@ -364,22 +359,14 @@ export function createOpenClawCodingTools(options?: {
if (sandboxRoot) {
return [];
}
// Wrap with param normalization for Claude Code compatibility
const wrapped = wrapToolParamNormalization(
createWriteTool(workspaceRoot),
CLAUDE_PARAM_GROUPS.write,
);
const wrapped = createHostWorkspaceWriteTool(workspaceRoot);
return [workspaceOnly ? wrapToolWorkspaceRootGuard(wrapped, workspaceRoot) : wrapped];
}
if (tool.name === "edit") {
if (sandboxRoot) {
return [];
}
// Wrap with param normalization for Claude Code compatibility
const wrapped = wrapToolParamNormalization(
createEditTool(workspaceRoot),
CLAUDE_PARAM_GROUPS.edit,
);
const wrapped = createHostWorkspaceEditTool(workspaceRoot);
return [workspaceOnly ? wrapToolWorkspaceRootGuard(wrapped, workspaceRoot) : wrapped];
}
return [tool];