diff --git a/docs/architecture/tla/CustomToolCache.Direct.cfg b/docs/architecture/tla/CustomToolCache.Direct.cfg new file mode 100644 index 0000000000..1bb6409c3b --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.Direct.cfg @@ -0,0 +1,15 @@ +CONSTANT Writers <- MCWriters +CONSTANT AtomicPublish = FALSE +SPECIFICATION Spec +INVARIANT VisibleIsReady +INVARIANT FailedIsClean +CHECK_DEADLOCK FALSE + +CONSTANT CanonicalMatch = TRUE +INVARIANT OwnershipMockReachesRoot + +CONSTANT NormalizeCache = TRUE +CONSTANT GuardCleanup = TRUE +CONSTANT CleanupCases <- MCCleanupCases +INVARIANT CleanupSelectsRoot +INVARIANT UnsafeRootIsUntouched diff --git a/docs/architecture/tla/CustomToolCache.MixedPath.cfg b/docs/architecture/tla/CustomToolCache.MixedPath.cfg new file mode 100644 index 0000000000..e7e6cd3202 --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.MixedPath.cfg @@ -0,0 +1,15 @@ +CONSTANT Writers <- MCWriters +CONSTANT AtomicPublish = TRUE +SPECIFICATION Spec +INVARIANT VisibleIsReady +INVARIANT FailedIsClean +CHECK_DEADLOCK FALSE + +CONSTANT CanonicalMatch = TRUE +INVARIANT OwnershipMockReachesRoot + +CONSTANT NormalizeCache = FALSE +CONSTANT GuardCleanup = TRUE +CONSTANT CleanupCases <- MCCleanupCases +INVARIANT CleanupSelectsRoot +INVARIANT UnsafeRootIsUntouched diff --git a/docs/architecture/tla/CustomToolCache.NoCleanupGuard.cfg b/docs/architecture/tla/CustomToolCache.NoCleanupGuard.cfg new file mode 100644 index 0000000000..829621e02f --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.NoCleanupGuard.cfg @@ -0,0 +1,15 @@ +CONSTANT Writers <- MCWriters +CONSTANT AtomicPublish = TRUE +SPECIFICATION Spec +INVARIANT VisibleIsReady +INVARIANT FailedIsClean +CHECK_DEADLOCK FALSE + +CONSTANT CanonicalMatch = TRUE +INVARIANT OwnershipMockReachesRoot + +CONSTANT NormalizeCache = TRUE +CONSTANT GuardCleanup = FALSE +CONSTANT CleanupCases <- MCCleanupCases +INVARIANT CleanupSelectsRoot +INVARIANT UnsafeRootIsUntouched diff --git a/docs/architecture/tla/CustomToolCache.RawPath.cfg b/docs/architecture/tla/CustomToolCache.RawPath.cfg new file mode 100644 index 0000000000..2c2f9e772c --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.RawPath.cfg @@ -0,0 +1,15 @@ +CONSTANT Writers <- MCWriters +CONSTANT AtomicPublish = TRUE +SPECIFICATION Spec +INVARIANT VisibleIsReady +INVARIANT FailedIsClean +CHECK_DEADLOCK FALSE + +CONSTANT CanonicalMatch = FALSE +INVARIANT OwnershipMockReachesRoot + +CONSTANT NormalizeCache = TRUE +CONSTANT GuardCleanup = TRUE +CONSTANT CleanupCases <- MCCleanupCases +INVARIANT CleanupSelectsRoot +INVARIANT UnsafeRootIsUntouched diff --git a/docs/architecture/tla/CustomToolCache.cfg b/docs/architecture/tla/CustomToolCache.cfg new file mode 100644 index 0000000000..ead2a645cf --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.cfg @@ -0,0 +1,15 @@ +CONSTANT Writers <- MCWriters +CONSTANT AtomicPublish = TRUE +SPECIFICATION Spec +INVARIANT VisibleIsReady +INVARIANT FailedIsClean +CHECK_DEADLOCK FALSE + +CONSTANT CanonicalMatch = TRUE +INVARIANT OwnershipMockReachesRoot + +CONSTANT NormalizeCache = TRUE +CONSTANT GuardCleanup = TRUE +CONSTANT CleanupCases <- MCCleanupCases +INVARIANT CleanupSelectsRoot +INVARIANT UnsafeRootIsUntouched diff --git a/docs/architecture/tla/CustomToolCache.tla b/docs/architecture/tla/CustomToolCache.tla new file mode 100644 index 0000000000..2f77f7f164 --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.tla @@ -0,0 +1,79 @@ +------------------------- MODULE CustomToolCache ------------------------- +(* Sources: CustomToolRegistry.import/runEsbuild and RegistryOptions.cacheDir. +Sinks: import(bundle.mjs), the lstatSync test double, and clearCache. *) +(* VisibleIsReady: Readers see only complete, private, checked bundles. +FailedIsClean: Failed writers leave no pending file. *) +(* OwnershipMockReachesRoot: The ownership double matches the resolved cache root. +CleanupSelectsRoot: Cleanup selects the configured root for each input path. *) +(* UnsafeRootIsUntouched: Cleanup preserves roots that fail validation. +Compiler, path results, and filesystem checks are oracles. MC sets the bounds. *) +(* Expectation: Each faulty variant fails its invariant. Fixed variants pass. +The reviews preceded the new invariants. The blind step was missed. *) +(* Findings: Replays confirm the reported bugs. No new bug or false alarm found. +The model does not prove the code. A stopped process can leave a pending file. *) +(* TLC: Fixed passes all five invariants (49 states, depth 11). +Direct fails VisibleIsReady after Start (2 states). RawPath fails at the start. *) +(* MixedPath fails CleanupSelectsRoot. NoCleanupGuard fails UnsafeRootIsUntouched. +Latest runs took under 1s each. Round 3 runs took 27 to 42s. *) +(* Replay: Old publication fails 3 of 4 cases. Raw ownership matching fails aliases. +Old cleanup fails 4 of 7 cases. Guard sabotage deletes all 3 unsafe sentinels. *) +(* Validation: Fixed code passes 40 integration and 21 unit tests. +Both type checks and focused lint pass. Suppression counts do not increase. *) +(* Review ratchet, PR #2485: Added 4, covered 0, gap 4 across four rounds. +Gaps cover test routing, defaults, module placement, and PR metadata. *) +(* Round 1: Threads PRRT_kwDOSK-bwM64vzgN, PRRT_kwDOSK-bwM64vzgR, PRRT_kwDOSK-bwM64vzgV. Added 1, gap 2. +Publication became an invariant. Test routing and defaults use direct tests. *) +(* Round 2: Thread PRRT_kwDOSK-bwM64vzgN, reply 4622881580. Added 1. +Canonical ownership matching became an invariant. *) +(* Round 3: Thread PRRT_kwDOSK-bwM65T3Dd, comment 4623919335. Gap 1. +Writer bounds moved to MC. A state invariant cannot check module placement. *) +(* Round 4: Review 5968844313. Added 2, gap 1. +Cleanup gained two invariants. PR metadata is outside the model. *) +(* Cost: One agent, no delegates. Rounds 1/2/3/4 took about 6/3/4/6 minutes. +Header cleanup took about 2 minutes. These are work estimates. *) +(* Gate: Run all five configs against CustomToolCacheMC and the property tables. +Use -metadir outside the repo. TLC needs a local socket. Run file tests on the host. *) +EXTENDS Naturals, TLC +CONSTANTS AtomicPublish, CanonicalMatch, Writers, NormalizeCache, GuardCleanup, CleanupCases +VARIABLES phase, published, pending +vars == <> +Init == /\ phase = [w \in Writers |-> "idle"] + /\ published = "absent" + /\ pending = {} +Start(w) == /\ phase[w] = "idle" + /\ phase' = [phase EXCEPT ![w] = "writing"] + /\ pending' = pending \cup {w} + /\ published' = IF AtomicPublish THEN published ELSE "partial" +Finish(w) == /\ phase[w] = "writing" + /\ phase' = [phase EXCEPT ![w] = "complete"] + /\ published' = IF AtomicPublish THEN published ELSE "readable" + /\ UNCHANGED pending +Restrict(w) == /\ phase[w] = "complete" + /\ phase' = [phase EXCEPT ![w] = "private"] + /\ UNCHANGED <> +Check(w) == /\ phase[w] = "private" + /\ phase' = [phase EXCEPT ![w] = "checked"] + /\ UNCHANGED <> +Publish(w) == /\ phase[w] = "checked" + /\ phase' = [phase EXCEPT ![w] = "done"] + /\ published' = "ready" + /\ pending' = pending \ {w} +Fail(w) == /\ phase[w] \in {"writing", "complete", "private", "checked"} + /\ phase' = [phase EXCEPT ![w] = "failed"] + /\ pending' = pending \ {w} + /\ UNCHANGED published +Next == \E w \in Writers : Start(w) \/ Finish(w) \/ Restrict(w) \/ Check(w) \/ Publish(w) \/ Fail(w) +Spec == Init /\ [][Next]_vars +VisibleIsReady == published \in {"absent", "ready"} +FailedIsClean == \A w \in Writers : phase[w] = "failed" => w \notin pending +(* Source: configured cache path. Sink: lstatSync ownership test double. *) +CachePaths == {"cache", "alias/cache"} +Canonical(p) == IF p = "alias/cache" THEN "cache" ELSE p +MockTarget(p) == IF CanonicalMatch THEN Canonical(p) ELSE p +OwnershipMockReachesRoot == \A p \in CachePaths : MockTarget(p) = Canonical(p) +(* Path results are input oracles. The model does not copy Node path parsing. *) +CleanupTarget(c) == IF NormalizeCache THEN c.normalizedTarget ELSE c.mixedTarget +CleanupSelectsRoot == \A c \in CleanupCases : CleanupTarget(c) = c.root +MayClear(safe) == IF GuardCleanup THEN safe ELSE TRUE +UnsafeRootIsUntouched == \A safe \in BOOLEAN : ~safe => ~MayClear(safe) +============================================================================= diff --git a/docs/architecture/tla/CustomToolCacheMC.tla b/docs/architecture/tla/CustomToolCacheMC.tla new file mode 100644 index 0000000000..57b7b37e77 --- /dev/null +++ b/docs/architecture/tla/CustomToolCacheMC.tla @@ -0,0 +1,13 @@ +------------------------ MODULE CustomToolCacheMC ------------------------ +(* TLC bounds for CustomToolCache: Two writers and four path forms. +The spec header records expectations, cost, findings, and validation. *) +EXTENDS CustomToolCache +MCWriters == {1, 2} +(* These path results come from Node path.resolve, dirname, and basename. *) +MCCleanupCases == { + [form |-> "plain", root |-> "cache", normalizedTarget |-> "cache", mixedTarget |-> "cache"], + [form |-> "dot", root |-> "cache", normalizedTarget |-> "cache", mixedTarget |-> "parent"], + [form |-> "dots", root |-> "cache", normalizedTarget |-> "cache", mixedTarget |-> "parent"], + [form |-> "dotdot", root |-> "cache", normalizedTarget |-> "cache", mixedTarget |-> "grandparent"] +} +============================================================================= diff --git a/packages/core/src/custom-tools/__tests__/custom-tool-registry.integration.spec.ts b/packages/core/src/custom-tools/__tests__/custom-tool-registry.integration.spec.ts index 568e58bdf1..55f3f010b4 100644 --- a/packages/core/src/custom-tools/__tests__/custom-tool-registry.integration.spec.ts +++ b/packages/core/src/custom-tools/__tests__/custom-tool-registry.integration.spec.ts @@ -1,5 +1,8 @@ // pnpm --filter @roo-code/core test src/custom-tools/__tests__/custom-tool-registry.integration.spec.ts +import fs from "fs" +import os from "os" +import { createHash } from "crypto" import path from "path" import { fileURLToPath } from "url" @@ -17,6 +20,200 @@ describe.sequential("CustomToolRegistry integration", () => { registry = new CustomToolRegistry() }) + describe.skipIf(process.platform === "win32")("cache security", () => { + let sandbox: string + let toolDir: string + let cacheDir: string + let entryDir: string + + beforeEach(() => { + sandbox = fs.mkdtempSync(path.join(os.tmpdir(), "tool-cache-security-")) + toolDir = path.join(sandbox, "tools") + cacheDir = path.join(sandbox, "cache") + fs.mkdirSync(toolDir) + const source = path.join(toolDir, "safe.ts") + fs.writeFileSync( + source, + 'export default { name: "safe", description: "trusted", execute: async () => "ok" }', + ) + fs.writeFileSync(path.join(toolDir, ".env"), "SYNTHETIC_TEST_VALUE=example") + const key = `${source}:${fs.statSync(source).mtimeMs}` + entryDir = path.join(cacheDir, createHash("sha256").update(key).digest("hex").slice(0, 16)) + registry = new CustomToolRegistry({ cacheDir }) + }) + + afterEach(() => fs.rmSync(sandbox, { recursive: true, force: true })) + + it("creates a private cache, reuses bundles across instances, and clears it", async () => { + expect((await registry.loadFromDirectory(toolDir)).loaded).toEqual(["safe"]) + for (const location of [ + cacheDir, + entryDir, + path.join(entryDir, "bundle.mjs"), + path.join(entryDir, ".env"), + ]) { + expect(fs.statSync(location).mode & 0o077).toBe(0) + } + const bundle = path.join(entryDir, "bundle.mjs") + const modified = fs.statSync(bundle).mtimeMs + const second = new CustomToolRegistry({ cacheDir }) + expect((await second.loadFromDirectory(toolDir)).loaded).toEqual(["safe"]) + expect(fs.statSync(bundle).mtimeMs).toBe(modified) + second.clearCache() + expect(fs.readdirSync(cacheDir)).toEqual([]) + }) + + it.each(["", "/.", "/./.", "/nested/.."])("clears only the configured cache with suffix %s", (suffix) => { + fs.mkdirSync(cacheDir, { mode: 0o700 }) + fs.mkdirSync(path.join(cacheDir, "nested")) + const cachedBundle = path.join(cacheDir, "bundle.mjs") + const sibling = path.join(toolDir, "sentinel") + fs.writeFileSync(cachedBundle, "cached") + fs.writeFileSync(sibling, "keep") + new CustomToolRegistry({ cacheDir: `${cacheDir}${suffix}` }).clearCache() + expect(fs.existsSync(cachedBundle)).toBe(false) + expect(fs.readFileSync(sibling, "utf8")).toBe("keep") + }) + + it.each(["permissions", "symlink", "symlink-dot"])("does not clear an unsafe cache root: %s", (kind) => { + fs.mkdirSync(cacheDir, { mode: 0o700 }) + let sentinel: string + if (kind.startsWith("symlink")) { + fs.rmdirSync(cacheDir) + fs.symlinkSync(toolDir, cacheDir) + sentinel = path.join(toolDir, "bundle.mjs") + } else { + fs.chmodSync(cacheDir, 0o777) + sentinel = path.join(cacheDir, "bundle.mjs") + } + fs.writeFileSync(sentinel, "keep") + const error = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + new CustomToolRegistry({ cacheDir: kind === "symlink-dot" ? `${cacheDir}/.` : cacheDir }).clearCache() + expect(fs.readFileSync(sentinel, "utf8")).toBe("keep") + expect(error).toHaveBeenCalledWith(expect.stringContaining("clearCache failed to clean disk cache")) + } finally { + error.mockRestore() + } + }) + + it.each(["root", "entry", "bundle", "symlink-root", "symlink-entry", "symlink-bundle", "hardlink-bundle"])( + "rejects an unsafe %s before importing attacker code", + async (kind) => { + fs.mkdirSync(entryDir, { recursive: true, mode: 0o700 }) + const payload = path.join(sandbox, "payload.mjs") + const marker = path.join(sandbox, "executed") + fs.writeFileSync( + payload, + `import fs from "node:fs"; fs.writeFileSync(${JSON.stringify(marker)}, "bad")`, + ) + const bundle = path.join(entryDir, "bundle.mjs") + fs.copyFileSync(payload, bundle) + fs.chmodSync(bundle, 0o600) + const target = kind.endsWith("root") ? cacheDir : kind.endsWith("entry") ? entryDir : bundle + if (kind.startsWith("symlink")) { + fs.rmSync(target, { recursive: true, force: true }) + fs.symlinkSync(kind === "symlink-bundle" ? payload : toolDir, target) + } else if (kind === "hardlink-bundle") { + fs.linkSync(bundle, path.join(sandbox, "linked.mjs")) + } else { + fs.chmodSync(target, kind === "bundle" ? 0o666 : 0o777) + } + const result = await registry.loadFromDirectory(toolDir) + expect(result.loaded).toEqual([]) + expect(result.failed[0]?.error).toContain("Unsafe custom tool cache") + expect(fs.existsSync(marker)).toBe(false) + }, + ) + + it.each(["direct", "symlink-parent"])("rejects a cache owned by another account via %s", async (kind) => { + fs.mkdirSync(cacheDir, { mode: 0o700 }) + if (kind === "symlink-parent") { + const alias = path.join(sandbox, "alias") + fs.symlinkSync(sandbox, alias) + cacheDir = path.join(alias, "cache") + registry = new CustomToolRegistry({ cacheDir }) + } + const resolvedCacheDir = fs.realpathSync(cacheDir) + const stat = fs.lstatSync(resolvedCacheDir) + stat.uid += 1 + const originalLstat = fs.lstatSync + const spy = vi.spyOn(fs, "lstatSync").mockImplementation((location, options) => { + return location === resolvedCacheDir ? stat : originalLstat(location, options) + }) + try { + const result = await registry.loadFromDirectory(toolDir) + expect(result.loaded).toEqual([]) + expect(result.failed).toEqual([ + { file: "safe.ts", error: `Unsafe custom tool cache path: ${resolvedCacheDir}` }, + ]) + } finally { + spy.mockRestore() + } + }) + + it.each(["success", "build failure", "validation failure", "publish failure"])( + "publishes only complete private bundles and removes pending files: %s", + async (outcome) => { + const bundle = path.join(entryDir, "bundle.mjs") + const originalChmod = fs.chmodSync + const originalRename = fs.renameSync + const chmod = vi.spyOn(fs, "chmodSync").mockImplementation((location, mode) => { + if (String(location).endsWith(".mjs")) { + expect(fs.existsSync(bundle)).toBe(false) + expect(fs.readFileSync(location, "utf8")).toContain('name: "safe"') + if (outcome === "validation failure") return originalChmod(location, 0o644) + } + return originalChmod(location, mode) + }) + const rename = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => { + expect(destination).toBe(bundle) + expect(fs.statSync(source).mode & 0o777).toBe(0o600) + if (outcome === "publish failure") throw new Error("Synthetic publish failure") + originalRename(source, destination) + }) + if (outcome === "build failure") fs.writeFileSync(path.join(toolDir, "safe.ts"), "export default {") + try { + const result = await registry.loadFromDirectory(toolDir) + expect(result.loaded).toEqual(outcome === "success" ? ["safe"] : []) + expect(result.failed).toHaveLength(outcome === "success" ? 0 : 1) + // A source change creates a new hash, so inspect all entries. + const entries = fs.readdirSync(cacheDir) + for (const entry of entries) { + expect( + fs.readdirSync(path.join(cacheDir, entry)).filter((name) => name.endsWith(".tmp.mjs")), + ).toEqual([]) + } + expect(fs.existsSync(bundle)).toBe(outcome === "success") + expect(rename).toHaveBeenCalledTimes(outcome === "success" || outcome === "publish failure" ? 1 : 0) + } finally { + chmod.mockRestore() + rename.mockRestore() + } + }, + ) + + it("creates nested configured cache directories privately", async () => { + const nested = path.join(cacheDir, "nested", "cache") + const nestedRegistry = new CustomToolRegistry({ cacheDir: nested }) + expect((await nestedRegistry.loadFromDirectory(toolDir)).loaded).toEqual(["safe"]) + expect(fs.statSync(nested).mode & 0o077).toBe(0) + }) + + it("rechecks permissions before using the in-memory cache", async () => { + expect((await registry.loadFromDirectory(toolDir)).loaded).toEqual(["safe"]) + fs.chmodSync(entryDir, 0o777) + expect((await registry.loadFromDirectory(toolDir)).failed[0]?.error).toContain("Unsafe custom tool cache") + }) + + it("rejects cache paths beneath a replaceable parent", async () => { + fs.chmodSync(sandbox, 0o777) + expect((await registry.loadFromDirectory(toolDir)).failed[0]?.error).toContain( + "Unsafe custom tool cache parent", + ) + }) + }) + describe("loadFromDirectory", () => { it("should load tools from TypeScript files", async () => { const result = await registry.loadFromDirectory(TEST_FIXTURES_DIR) diff --git a/packages/core/src/custom-tools/__tests__/custom-tool-registry.spec.ts b/packages/core/src/custom-tools/__tests__/custom-tool-registry.spec.ts index 32886001a8..5c22e8fcd9 100644 --- a/packages/core/src/custom-tools/__tests__/custom-tool-registry.spec.ts +++ b/packages/core/src/custom-tools/__tests__/custom-tool-registry.spec.ts @@ -1,5 +1,8 @@ // pnpm --filter @roo-code/core test src/custom-tools/__tests__/custom-tool-registry.spec.ts +import os from "os" +import path from "path" + import { type CustomToolDefinition, parametersSchema as z } from "@roo-code/types" import { CustomToolRegistry } from "../custom-tool-registry.js" @@ -11,6 +14,21 @@ describe("CustomToolRegistry", () => { registry = new CustomToolRegistry() }) + describe("cache location", () => { + afterEach(() => vi.unstubAllGlobals()) + + it.each([ + { platform: "linux", uid: 1234, options: undefined, base: os.tmpdir(), suffix: "1234" }, + { platform: "win32", uid: undefined, options: {}, base: os.homedir(), suffix: "user" }, + { platform: "linux", uid: 0, options: {}, base: os.tmpdir(), suffix: "0" }, + { platform: "linux", uid: 1234, options: { cacheDir: "custom/cache" }, base: "", suffix: "" }, + ])("uses the expected cache path for $platform/$uid/$options", ({ platform, uid, options, base, suffix }) => { + vi.stubGlobal("process", { ...process, platform, getuid: uid === undefined ? undefined : () => uid }) + const instance = new CustomToolRegistry(options) + expect(instance["cacheDir"]).toBe(options?.cacheDir ?? path.join(base, `dynamic-tools-cache-${suffix}`)) + }) + }) + describe("validation", () => { it("should accept a valid tool definition", () => { const validTool = { diff --git a/packages/core/src/custom-tools/custom-tool-registry.ts b/packages/core/src/custom-tools/custom-tool-registry.ts index 1725f4aba3..78e61d8bf5 100644 --- a/packages/core/src/custom-tools/custom-tool-registry.ts +++ b/packages/core/src/custom-tools/custom-tool-registry.ts @@ -10,7 +10,7 @@ import fs from "fs" import path from "path" -import { createHash } from "crypto" +import { createHash, randomUUID } from "crypto" import os from "os" import type { CustomToolDefinition, SerializedCustomToolDefinition, CustomToolParametersSchema } from "@roo-code/types" @@ -37,7 +37,12 @@ export class CustomToolRegistry { private lastLoaded: Map = new Map() constructor(options?: RegistryOptions) { - this.cacheDir = options?.cacheDir ?? path.join(os.tmpdir(), "dynamic-tools-cache") + this.cacheDir = + options?.cacheDir ?? + path.join( + process.platform === "win32" ? os.homedir() : os.tmpdir(), + `dynamic-tools-cache-${process.getuid?.() ?? "user"}`, + ) // Default to current working directory's node_modules. this.nodePaths = options?.nodePaths ?? [path.join(process.cwd(), "node_modules")] this.extensionPath = options?.extensionPath @@ -234,6 +239,50 @@ export class CustomToolRegistry { return this.extensionPath } + /** Reject cache paths that another account could supply or replace. */ + private validateCachePath(cachePath: string, directory: boolean): void { + const stat = fs.lstatSync(cachePath) + const uid = process.getuid?.() + if ( + (directory ? !stat.isDirectory() : !stat.isFile()) || + (uid !== undefined && (stat.uid !== uid || (stat.mode & 0o077) !== 0)) || + (!directory && stat.nlink !== 1) + ) { + throw new Error(`Unsafe custom tool cache path: ${cachePath}`) + } + } + + private prepareCacheDirectory(): void { + // Resolve platform aliases (e.g. /var on macOS), then check ancestors before writing. + const normalizedCacheDir = path.resolve(this.cacheDir) + let ancestor = path.dirname(normalizedCacheDir) + const missing: string[] = [] + while (!fs.lstatSync(ancestor, { throwIfNoEntry: false })) { + missing.unshift(path.basename(ancestor)) + ancestor = path.dirname(ancestor) + } + let parent = fs.realpathSync(ancestor) + for (let current = parent; ; current = path.dirname(current)) { + const stat = fs.statSync(current) + const uid = process.getuid?.() + if ( + uid !== undefined && + ((stat.uid !== uid && stat.uid !== 0) || ((stat.mode & 0o022) !== 0 && (stat.mode & 0o1000) === 0)) + ) { + throw new Error(`Unsafe custom tool cache parent: ${current}`) + } + if (path.dirname(current) === current) break + } + for (const component of missing) { + parent = path.join(parent, component) + fs.mkdirSync(parent, { recursive: true, mode: 0o700 }) + this.validateCachePath(parent, true) + } + this.cacheDir = path.join(parent, path.basename(normalizedCacheDir)) + fs.mkdirSync(this.cacheDir, { recursive: true, mode: 0o700 }) + this.validateCachePath(this.cacheDir, true) + } + /** * Clear the TypeScript compilation cache (both in-memory and on disk). * This removes all tool-specific subdirectories and their contents. @@ -243,6 +292,7 @@ export class CustomToolRegistry { if (fs.existsSync(this.cacheDir)) { try { + this.prepareCacheDirectory() const entries = fs.readdirSync(this.cacheDir, { withFileTypes: true }) for (const entry of entries) { const entryPath = path.join(this.cacheDir, entry.name) @@ -282,9 +332,13 @@ export class CustomToolRegistry { const stat = fs.statSync(absolutePath) const cacheKey = `${absolutePath}:${stat.mtimeMs}` + this.prepareCacheDirectory() + // Check if we have a cached version in memory. if (this.tsCache.has(cacheKey)) { const cachedPath = this.tsCache.get(cacheKey)! + this.validateCachePath(path.dirname(cachedPath), true) + this.validateCachePath(cachedPath, false) return import(`file://${cachedPath}`) } @@ -292,12 +346,14 @@ export class CustomToolRegistry { // Use a tool-specific subdirectory to avoid .env file conflicts between tools. const toolCacheDir = path.join(this.cacheDir, hash) - fs.mkdirSync(toolCacheDir, { recursive: true }) + fs.mkdirSync(toolCacheDir, { recursive: true, mode: 0o700 }) + this.validateCachePath(toolCacheDir, true) const tempFile = path.join(toolCacheDir, "bundle.mjs") // Check if we have a cached version on disk (from a previous run/instance). - if (fs.existsSync(tempFile)) { + if (fs.lstatSync(tempFile, { throwIfNoEntry: false })) { + this.validateCachePath(tempFile, false) this.tsCache.set(cacheKey, tempFile) return import(`file://${tempFile}`) } @@ -313,22 +369,31 @@ export class CustomToolRegistry { // Bundle the TypeScript file with dependencies using esbuild CLI. // - Node.js built-ins are external (they can't be bundled and are always available) // - npm packages are bundled with CommonJS require() shim for compatibility - await runEsbuild( - { - entryPoint: absolutePath, - outfile: tempFile, - format: "esm", - platform: "node", - target: "node18", - bundle: true, - sourcemap: "inline", - packages: "bundle", - nodePaths, - external: NODE_BUILTIN_MODULES, - banner: COMMONJS_REQUIRE_BANNER, - }, - this.extensionPath, - ) + const pendingFile = path.join(toolCacheDir, `bundle-${randomUUID()}.tmp.mjs`) + try { + await runEsbuild( + { + entryPoint: absolutePath, + outfile: pendingFile, + format: "esm", + platform: "node", + target: "node18", + bundle: true, + sourcemap: "inline", + packages: "bundle", + nodePaths, + external: NODE_BUILTIN_MODULES, + banner: COMMONJS_REQUIRE_BANNER, + }, + this.extensionPath, + ) + + fs.chmodSync(pendingFile, 0o600) + this.validateCachePath(pendingFile, false) + fs.renameSync(pendingFile, tempFile) + } finally { + fs.rmSync(pendingFile, { force: true }) + } // Copy .env files from the tool's source directory to the tool-specific cache directory. // This allows tools that use dotenv with __dirname to find their .env files, @@ -360,6 +425,7 @@ export class CustomToolRegistry { const stat = fs.statSync(srcPath) if (stat.isFile()) { fs.copyFileSync(srcPath, destPath) + fs.chmodSync(destPath, 0o600) console.log(`[CustomToolRegistry] copied ${envFile} to tool cache directory`) } }