UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

596 lines (595 loc) • 22 kB
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs"; import { a as openRootFile, s as readFileDescriptorBounded } from "./boundary-file-read-BfaFLDqt.mjs"; import { i as isMissingPathError } from "./errno-DFcoqIT9.mjs"; import { n as resolveIdentityPathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import "./errors-BKzCeTYb.mjs"; import { t as FsSafeError } from "./fs-safe-BbWvmdVn.mjs"; import { i as resolveSandboxHostPathViaExistingAncestor, r as normalizeSandboxHostPath, t as getSandboxHostPathPolicyKey } from "./host-paths-CAIcciVP.mjs"; import { n as normalizeContainerPathCore, r as relativePathEscapesContainerRoot, t as isPathInsideContainerRoot } from "./path-utils-B84QmnB8.mjs"; import { c as resolveSandboxTmpfsMounts } from "./workspace-mounts-CKCN0wG6.mjs"; import { c as parseDirectoryEntries, i as PINNED_MUTATION_ACTION_LABELS, n as parseSandboxStatMtimeMs, r as parseSandboxStatSize, s as buildPinnedMutationPlan } from "./fs-bridge-stat-parse-BohRm5U2.mjs"; import { t as SANDBOX_FILE_IDENTITY } from "./file-mutation-identity-B9yq_vIv.mjs"; import { a as resolveSandboxFsMount, o as resolveSandboxFsPathWithMounts, t as buildSandboxFsMounts } from "./fs-paths-BcNIEM2k.mjs"; import fs from "node:fs"; import path from "node:path"; import { promisify } from "node:util"; import { GUEST_FILESYSTEM_CREATE_EXISTS_EXIT_CODE } from "@openclaw/fs-safe/guest"; //#region src/agents/sandbox/fs-bridge-path-safety.ts function sandboxBoundaryError(e, t, n) { if (n instanceof Error && !(n instanceof FsSafeError && n.code === "not-file")) return n; return new Error(`Sandbox boundary checks failed; cannot ${e}: ${t}`, { cause: n }); } var SandboxFsPathGuard = class { constructor(e) { this.mountsByContainer = e.mountsByContainer.map((e) => ({ hostRoot: e.hostRoot, containerRoot: e.containerRoot, writable: e.writable, source: e.source, canonicalHostRoot: resolveSandboxHostPathViaExistingAncestor(e.hostRoot) })); this.runCommand = e.runCommand; this.containerOnlyMounts = e.containerOnlyMounts ?? []; } async assertPathChecks(e, t) { for (const n of e) await this.assertPathSafety(n.target, { ...n.options, signal: t }); } async assertPathSafety(e, t) { const n = t.allowedType === "file-or-directory" ? this.pathIsExistingDirectory(e.hostPath) ? "directory" : "file" : t.allowedType; const r = await this.openBoundaryWithinRequiredMount(e, t.action, { aliasPolicy: t.aliasPolicy, allowedType: n, signal: t.signal }); await this.assertGuardedPathSafety(e, { ...t, allowedType: n }, r); } async openReadableFile(e, t, n, r) { const i = await this.resolveCanonicalReadTarget(e, "read files", t); const a = await this.openBoundaryWithinRequiredMount(i.target, "read files", { signal: t, allowedType: r === "file-or-directory" ? this.pathIsExistingDirectory(i.target.hostPath) ? "directory" : "file" : r }); if (!a.ok) throw sandboxBoundaryError("read files", e.containerPath, a.error); try { this.assertExpectedPolicyPath(i.target, a.path, n); if (getSandboxHostPathPolicyKey(i.canonicalHostPath) !== getSandboxHostPathPolicyKey(a.path)) throw new Error(`Sandbox path is hidden by another mount: ${e.containerPath}. Use the mounted container path directly.`); } catch (e) { fs.closeSync(a.fd); throw e; } return { ...a, containerPath: i.target.containerPath }; } async resolveCanonicalEndpoint(e, t) { const n = await this.resolveCanonicalContainerPath({ containerPath: e, allowFinalSymlinkForUnlink: false, resolveIdentity: t?.identity, signal: t?.signal }); const r = resolveSandboxFsMount(this.mountsByContainer, n, this.containerOnlyMounts, { containerOnlyAsUnmapped: t?.identity }); const i = r ? path.posix.relative(r.containerRoot, n).split("/") : []; return { containerPath: n, mount: r, hostPath: r ? path.resolve(r.hostRoot, ...i) : void 0, canonicalHostPath: r ? path.resolve(r.canonicalHostRoot, ...i) : void 0 }; } async resolveFileIdentity(e, t) { const n = await this.resolveCanonicalEndpoint(e.containerPath, { identity: true, signal: t }); return n.canonicalHostPath ?? `container:${n.containerPath}`; } async resolveReadPolicyPath(e, t) { const n = await this.resolveCanonicalReadTarget(e, "authorize file reads", t); return this.policyPathForCanonicalHostIdentity(n.target, resolveIdentityPathViaExistingAncestorSync(n.canonicalHostPath)); } policyPathForCanonicalHostIdentity(e, t) { const n = normalizeSandboxHostPath(t); const r = this.resolveMountByContainerPath(e.containerPath); const i = r && isPathInside(r.canonicalHostRoot, n) ? r : this.mountsByContainer.toSorted((e, t) => t.canonicalHostRoot.length - e.canonicalHostRoot.length).find((e) => isPathInside(e.canonicalHostRoot, n)); if (!i) throw new Error(`Sandbox path escapes allowed mounts: ${e.containerPath}`); const a = path.relative(i.canonicalHostRoot, n); return normalizeContainerPathCore(a ? path.posix.join(i.containerRoot, ...a.split(path.sep)) : i.containerRoot); } async resolveCanonicalReadTarget(e, t, n) { const r = await this.resolveCanonicalEndpoint(e.containerPath, { signal: n }); if (!r.mount || !r.hostPath || !r.canonicalHostPath) throw new Error(`Sandbox path escapes allowed mounts; cannot ${t}: ${r.containerPath}`); return { target: { ...e, containerPath: r.containerPath, hostPath: r.hostPath, writable: r.mount.writable }, canonicalHostPath: r.canonicalHostPath }; } resolveRequiredMount(e, t) { const n = this.resolveMountByContainerPath(e); if (!n) throw new Error(`Sandbox path escapes allowed mounts; cannot ${t}: ${e}`); return n; } async assertGuardedPathSafety(e, t, n) { if (!n.ok) { if (n.reason !== "path") { if (!(n.reason === "io" && t.allowedType === "directory" && this.pathIsExistingDirectory(e.hostPath))) throw sandboxBoundaryError(t.action, e.containerPath, n.error); } } else fs.closeSync(n.fd); const r = await this.resolveCanonicalContainerPath({ containerPath: e.containerPath, allowFinalSymlinkForUnlink: t.aliasPolicy?.allowFinalSymlinkForUnlink === true, signal: t.signal }); const i = this.resolveRequiredMount(r, t.action); if (t.requireWritable === "subtree" && this.containerOnlyMounts.some((e) => isPathInsideContainerRoot(r, e))) throw new Error(`Sandbox subtree contains a container-only mount; cannot ${t.action}: ${e.containerPath}. Use exec to access this mount.`); if (t.requireWritable && (!i.writable || t.requireWritable === "subtree" && this.mountsByContainer.some((e) => !e.writable && isPathInsideContainerRoot(r, e.containerRoot)))) throw new Error(`Sandbox path is read-only; cannot ${t.action}: ${e.containerPath}`); } async openBoundaryWithinRequiredMount(e, t, n) { const r = this.resolveRequiredMount(e.containerPath, t); n?.signal?.throwIfAborted(); const i = await openRootFile({ absolutePath: e.hostPath, rootPath: r.hostRoot, boundaryLabel: "sandbox mount root", rejectSymlinks: false, aliasPolicy: n?.aliasPolicy, allowedType: n?.allowedType }); if (n?.signal?.aborted) { if (i.ok) fs.closeSync(i.fd); n.signal.throwIfAborted(); } return i; } resolvePinnedEntry(e, t) { const n = path.posix.basename(e.containerPath); if (!n || n === "." || n === "/") throw new Error(`Invalid sandbox entry target: ${e.containerPath}`); const r = normalizeContainerPathCore(path.posix.dirname(e.containerPath)); const { mountRootPath: i, relativePath: a } = this.resolvePinnedDirectory(r, t, e.containerPath); return { mountRootPath: i, relativeParentPath: a, basename: n }; } async resolveAnchoredSandboxEntry(e, t, n) { const r = path.posix.basename(e.containerPath); if (!r || r === "." || r === "/") throw new Error(`Invalid sandbox entry target: ${e.containerPath}`); const i = normalizeContainerPathCore(path.posix.dirname(e.containerPath)); const a = await this.resolveCanonicalContainerPath({ containerPath: i, allowFinalSymlinkForUnlink: false, signal: n }); this.resolveRequiredMount(a, t); return { canonicalParentPath: a, basename: r }; } async resolveAnchoredPinnedEntry(e, t, n) { const r = await this.resolveAnchoredSandboxEntry(e, t, n); const { mountRootPath: i, relativePath: a } = this.resolvePinnedDirectory(r.canonicalParentPath, t, e.containerPath); return { mountRootPath: i, relativeParentPath: a, basename: r.basename }; } /** * Resolves the canonical mutation destination so callers can authorize the * real target before pinning. File-backed actions resolve the canonical * parent and re-attach the requested basename; directory actions * (`options.directory`) canonicalize the directory itself, which an * existing alias may rename, and tolerate the mount root. */ async resolveCanonicalMutationTarget(e, t, n) { if (n?.directory) { const r = await this.resolveCanonicalContainerPath({ containerPath: e.containerPath, allowFinalSymlinkForUnlink: false, signal: n?.signal }); this.resolveRequiredMount(r, t); return r; } const r = await this.resolveAnchoredSandboxEntry(e, t, n?.signal); this.resolveRequiredMount(r.canonicalParentPath, t); return r.canonicalParentPath === "/" ? `/${r.basename}` : `${r.canonicalParentPath}/${r.basename}`; } async resolveAnchoredPinnedDirectoryEntry(e, t, n) { const r = await this.resolveCanonicalContainerPath({ containerPath: e.containerPath, allowFinalSymlinkForUnlink: false, signal: n }); return this.resolvePinnedDirectoryEntry({ ...e, containerPath: r }, t); } resolvePinnedDirectoryEntry(e, t) { return this.resolvePinnedDirectory(e.containerPath, t); } resolvePinnedDirectory(e, t, n = e) { const r = this.resolveRequiredMount(e, t); const i = path.posix.relative(r.containerRoot, e); if (relativePathEscapesContainerRoot(i)) throw new Error(`Sandbox path escapes allowed mounts; cannot ${t}: ${n}`); return { mountRootPath: r.containerRoot, relativePath: i === "." ? "" : i }; } pathIsExistingDirectory(e) { try { return fs.statSync(e).isDirectory(); } catch { return false; } } assertExpectedPolicyPath(e, t, n) { if (n !== void 0 && this.policyPathForCanonicalHostIdentity(e, t) !== normalizeContainerPathCore(n)) throw new Error(`Sandbox file changed after authorization: ${e.containerPath}`); } resolveMountByContainerPath(e) { const t = normalizeContainerPathCore(e); return resolveSandboxFsMount(this.mountsByContainer, t, this.containerOnlyMounts); } async resolveCanonicalContainerPath(e) { const t = [ "set -eu", "target=\"$1\"", "allow_final=\"$2\"", "identity=\"$3\"", "suffix=\"\"", "read_canonical() {", " canonical=$(readlink -n -f -- \"$cursor\" && printf .) || return", " canonical=${canonical%.}", "}", "probe=\"$target\"", "if [ \"$allow_final\" = \"1\" ] && [ -L \"$target\" ]; then probe=${target%/*}; probe=${probe:-/}; fi", "cursor=\"$probe\"", "while [ ! -e \"$cursor\" ] && [ ! -L \"$cursor\" ]; do", " parent=${cursor%/*}; parent=${parent:-/}", " if [ \"$parent\" = \"$cursor\" ]; then break; fi", " base=${cursor##*/}", " suffix=\"/$base$suffix\"", " cursor=\"$parent\"", "done", "if [ \"$identity\" = \"1\" ]; then", " while ! read_canonical; do", " parent=${cursor%/*}; parent=${parent:-/}", " if [ \"$parent\" = \"$cursor\" ]; then canonical=\"$target\"; suffix=\"\"; break; fi", " base=${cursor##*/}", " suffix=\"/$base$suffix\"", " cursor=\"$parent\"", " done", "else", " read_canonical", "fi", "printf \"%s%s\\n\" \"$canonical\" \"$suffix\"" ].join("\n"); const n = (await this.runCommand(t, { args: [ e.containerPath, e.allowFinalSymlinkForUnlink ? "1" : "0", e.resolveIdentity ? "1" : "0" ], signal: e.signal })).stdout.toString("utf8").replace(/\n$/, ""); if (!n.startsWith("/")) throw new Error(`Failed to resolve sandbox path: ${e.containerPath}`); return normalizeContainerPathCore(n); } }; //#endregion //#region src/agents/sandbox/fs-bridge.ts const readFileAsync = promisify(fs.readFile); function createSandboxFsBridge(e) { return new SandboxFsBridgeImpl(e.sandbox, e.containerOnlyMounts); } var SandboxFsBridgeImpl = class { constructor(e, t) { this.sandbox = e; this.mounts = buildSandboxFsMounts(e); this.containerOnlyMounts = t ?? resolveSandboxTmpfsMounts(e.docker.tmpfs).map((e) => e.containerPath); const n = this.mounts.toSorted((e, t) => t.containerRoot.length - e.containerRoot.length); this.pathGuard = new SandboxFsPathGuard({ mountsByContainer: n, containerOnlyMounts: this.containerOnlyMounts, runCommand: (t, n) => e.backend.runShellCommand({ script: t, ...n }) }); } resolvePath(e) { const t = this.resolveResolvedPath(e); return { hostPath: t.hostPath, relativePath: t.relativePath, containerPath: t.containerPath }; } get pathMappings() { return this.mounts; } async [SANDBOX_FILE_IDENTITY](e) { return this.pathGuard.resolveFileIdentity(this.resolveResolvedPath(e), e.signal); } async resolveReadPolicyPath(e) { return await this.pathGuard.resolveReadPolicyPath(this.resolveResolvedPath(e), e.signal); } async resolvePinnedMutationTarget(e) { const t = this.resolveResolvedPath(e); const n = await this.pathGuard.resolveCanonicalMutationTarget(t, PINNED_MUTATION_ACTION_LABELS[e.action], { directory: e.action === "mkdir", signal: e.signal }); return { policyPath: n, pinnedPath: n }; } async readFile(e) { return (await this.readFileWithSource(e)).data; } async readFileWithSource(e) { const t = this.resolveResolvedPath(e); return this.readPinnedFile(t, e.maxBytes, e.signal, e.expectedPolicyPath); } async readDirectory(e) { const t = this.resolveResolvedPath(e); const n = await this.runCheckedCommand({ ...buildPinnedMutationPlan({ kind: "readdir", target: t, pinned: await this.pathGuard.resolveAnchoredPinnedDirectoryEntry(t, "list directories", e.signal) }), signal: e.signal }); return parseDirectoryEntries(n.stdout.toString("utf8")); } async copyFile(e) { const t = this.resolveResolvedPath({ filePath: e.sourcePath, cwd: e.cwd }); const n = this.resolveResolvedPath({ filePath: e.destinationPath, cwd: e.cwd }); this.ensureWriteAccess(n, "copy files"); await this.runCheckedCommand({ ...buildPinnedMutationPlan({ kind: "copy", sourceTarget: t, destinationTarget: n, source: await this.pathGuard.resolveAnchoredPinnedEntry(t, "copy files", e.signal), destination: await this.resolveMutationPin(n, e.pinnedPath, "copy files", e.signal), mkdir: e.mkdir !== false }), signal: e.signal }); } async writeFile(e) { await this.writeFileContents(e, "write"); } async createFileExclusive(e) { const { result: t, containerPath: n } = await this.writeFileContents(e, "create"); if (t.code === GUEST_FILESYSTEM_CREATE_EXISTS_EXIT_CODE) return "exists"; if (t.code !== 0) throw new Error(`sandbox create failed for ${n}: ${t.stderr.toString("utf8").trim()}`); return "created"; } async writeFileContents(e, t) { const n = PINNED_MUTATION_ACTION_LABELS[t]; const r = this.resolveResolvedPath(e); this.ensureWriteAccess(r, n); await this.pathGuard.assertPathSafety(r, { action: n, requireWritable: true, signal: e.signal }); const i = Buffer.isBuffer(e.data) ? e.data : Buffer.from(e.data, e.encoding ?? "utf8"); const a = await this.resolveMutationPin(r, e.pinnedPath, n, e.signal); return { result: await this.runCheckedCommand({ ...buildPinnedMutationPlan({ kind: t, target: r, pinned: a, mkdir: e.mkdir !== false }), allowFailure: t === "create" ? true : void 0, stdin: i, signal: e.signal }), containerPath: r.containerPath }; } async mkdirp(e) { const t = this.resolveResolvedPath(e); this.ensureWriteAccess(t, "create directories"); await this.runCheckedCommand({ ...buildPinnedMutationPlan({ kind: "mkdirp", target: t, pinned: this.pathGuard.resolvePinnedDirectoryEntry(e.pinnedPath === void 0 ? t : this.authorizedPinnedTarget(t, e.pinnedPath, "create directories", { directory: true }), "create directories") }), signal: e.signal }); } async remove(e) { const t = this.resolveResolvedPath(e); this.ensureWriteAccess(t, "remove files"); await this.runCheckedCommand({ ...buildPinnedMutationPlan({ kind: "remove", target: t, pinned: this.pathGuard.resolvePinnedEntry(e.pinnedPath === void 0 ? t : this.authorizedPinnedTarget(t, e.pinnedPath, "remove files"), "remove files"), recursive: e.recursive, force: e.force }), signal: e.signal }); } async rename(e) { const t = this.resolveResolvedPath({ filePath: e.from, cwd: e.cwd }); const n = this.resolveResolvedPath({ filePath: e.to, cwd: e.cwd }); this.ensureWriteAccess(t, "rename files"); this.ensureWriteAccess(n, "rename files"); await this.runCheckedCommand({ ...buildPinnedMutationPlan({ kind: "rename", sourceTarget: t, destinationTarget: n, source: this.pathGuard.resolvePinnedEntry(t, "rename files"), destination: this.pathGuard.resolvePinnedEntry(n, "rename files") }), signal: e.signal }); } async stat(e) { const t = this.resolveResolvedPath(e); if (e.expectedPolicyPath !== void 0) { let n; try { n = await this.pathGuard.openReadableFile(t, e.signal, e.expectedPolicyPath, "file-or-directory"); } catch (e) { if (isMissingPathError(e)) return null; throw e; } try { return { type: n.stat.isDirectory() ? "directory" : "file", size: parseSandboxStatSize(String(n.stat.size)), mtimeMs: Math.trunc(n.stat.mtimeMs) }; } finally { fs.closeSync(n.fd); } } const n = await this.pathGuard.resolveCanonicalReadTarget(t, "stat files", e.signal); const r = await this.pathGuard.resolveAnchoredSandboxEntry(t, "stat files", e.signal); const i = await this.runCheckedCommand({ checks: [{ target: n.target, options: { action: "stat files" } }], script: "set -eu\ncd -- \"$1\"\nLC_ALL=C stat -c \"%F|%s|%y\" -- \"$2\"", args: [r.canonicalParentPath, r.basename], allowFailure: true, signal: e.signal }); if (i.code !== 0) { const e = i.stderr.toString("utf8"); if (e.includes("No such file or directory")) return null; const n = e.trim() || `stat failed with code ${i.code}`; throw new Error(`stat failed for ${t.containerPath}: ${n}`); } const [a, o, s] = i.stdout.toString("utf8").trim().split("|"); return { type: coerceStatType(a), size: parseSandboxStatSize(o), mtimeMs: parseSandboxStatMtimeMs(s) }; } async readPinnedFile(e, t, n, r) { const i = await this.pathGuard.openReadableFile(e, n, r); try { n?.throwIfAborted(); let r; if (t === void 0) { const e = { signal: n, encoding: null }; r = await readFileAsync(i.fd, e); } else { if (!Number.isSafeInteger(t) || t < 0) throw new RangeError("maxBytes must be a non-negative safe integer"); const a = fs.fstatSync(i.fd); if (!a.isFile()) throw new Error(`Sandbox read requires a regular file: ${e.containerPath}`); if (a.size > t) throw new RangeError(`File exceeds ${t} bytes`); r = await readFileDescriptorBounded(i.fd, t); n?.throwIfAborted(); const o = fs.fstatSync(i.fd); if (!o.isFile() || o.size > t) throw new RangeError(`File exceeds ${t} bytes`); } const a = resolveSandboxFsMount(this.mounts, i.containerPath, this.containerOnlyMounts); return { data: r, canonicalPath: i.containerPath, ...a?.source === "workspace" ? { workspaceRelativePath: path.posix.relative(a.containerRoot, i.containerPath) } : {} }; } finally { fs.closeSync(i.fd); } } async runCheckedCommand(e) { await this.pathGuard.assertPathChecks(e.checks, e.signal); return await this.sandbox.backend.runShellCommand({ script: e.script, args: e.args, stdin: e.stdin, allowFailure: e.allowFailure, signal: e.signal }); } ensureWriteAccess(e, t) { if (this.sandbox.workspaceAccess === "ro" || !e.writable) throw new Error(`Sandbox path is read-only; cannot ${t}: ${e.containerPath}`); } resolveResolvedPath(e) { return resolveSandboxFsPathWithMounts({ filePath: e.filePath, cwd: e.cwd ?? this.sandbox.workspaceDir, defaultWorkspaceRoot: this.sandbox.workspaceDir, defaultContainerRoot: this.sandbox.containerWorkdir, mounts: this.mounts, containerOnlyMounts: this.containerOnlyMounts }); } /** * Pins a mutation for a destination the caller already authorized via * resolvePinnedMutationTarget. The canonical path is pinned lexically so no * sandbox-writable path component is resolved again after authorization; * the no-follow pinned walk then fails closed on any post-authorization * swap instead of redirecting the mutation. */ async resolveMutationPin(e, t, n, r) { if (t === void 0) return await this.pathGuard.resolveAnchoredPinnedEntry(e, n, r); return this.pathGuard.resolvePinnedEntry(this.authorizedPinnedTarget(e, t, n), n); } authorizedPinnedTarget(e, t, n, r) { const i = normalizeContainerPathCore(t); if (!r?.directory && path.posix.basename(i) !== path.posix.basename(e.containerPath)) throw new Error(`Pinned sandbox destination does not match the requested path; cannot ${n}: ${e.containerPath}`); return { ...e, containerPath: i }; } }; function coerceStatType(e) { const t = normalizeOptionalLowercaseString(e) ?? ""; if (t.includes("directory")) return "directory"; if (t.includes("file")) return "file"; return "other"; } //#endregion export { createSandboxFsBridge as t };