From e4bbdd2096af6f28c8f648a4d84f896d71a2cc6a Mon Sep 17 00:00:00 2001 From: "coderabbitai[bot]" <136622811+coderabbitai[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:33:43 +0000 Subject: [PATCH 1/5] fix(security): prevent custom tool cache injection --- .../custom-tool-registry.integration.spec.ts | 111 ++++++++++++++++++ .../src/custom-tools/custom-tool-registry.ts | 65 +++++++++- 2 files changed, 173 insertions(+), 3 deletions(-) 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..4db5195f2b 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,114 @@ 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(["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("rejects a cache owned by another account", async () => { + fs.mkdirSync(cacheDir, { mode: 0o700 }) + const stat = fs.lstatSync(cacheDir) + stat.uid += 1 + // The first lstat is the existing parent, then the cache root. + const spy = vi.spyOn(fs, "lstatSync").mockReturnValueOnce(fs.statSync(sandbox)).mockReturnValueOnce(stat) + try { + expect((await registry.loadFromDirectory(toolDir)).failed[0]?.error).toContain( + "Unsafe custom tool cache", + ) + } finally { + spy.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/custom-tool-registry.ts b/packages/core/src/custom-tools/custom-tool-registry.ts index 1725f4aba3..2f29759714 100644 --- a/packages/core/src/custom-tools/custom-tool-registry.ts +++ b/packages/core/src/custom-tools/custom-tool-registry.ts @@ -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,49 @@ 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. + let ancestor = path.dirname(path.resolve(this.cacheDir)) + 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(this.cacheDir)) + 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 +291,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 +331,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 +345,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}`) } @@ -330,6 +385,9 @@ export class CustomToolRegistry { this.extensionPath, ) + fs.chmodSync(tempFile, 0o600) + this.validateCachePath(tempFile, false) + // 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, // while ensuring different tools' .env files don't overwrite each other. @@ -360,6 +418,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`) } } From e8480821b12d2eefc22e5b043aaa69a709cca7be Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Thu, 19 Nov 2026 00:43:55 +0000 Subject: [PATCH 2/5] fix(custom-tools): publish validated cache bundles atomically --- .../tla/CustomToolCache.Direct.cfg | 5 ++ docs/architecture/tla/CustomToolCache.cfg | 5 ++ docs/architecture/tla/CustomToolCache.tla | 61 +++++++++++++++++++ .../custom-tool-registry.integration.spec.ts | 47 +++++++++++++- .../__tests__/custom-tool-registry.spec.ts | 18 ++++++ .../src/custom-tools/custom-tool-registry.ts | 44 +++++++------ 6 files changed, 159 insertions(+), 21 deletions(-) create mode 100644 docs/architecture/tla/CustomToolCache.Direct.cfg create mode 100644 docs/architecture/tla/CustomToolCache.cfg create mode 100644 docs/architecture/tla/CustomToolCache.tla diff --git a/docs/architecture/tla/CustomToolCache.Direct.cfg b/docs/architecture/tla/CustomToolCache.Direct.cfg new file mode 100644 index 0000000000..337b2a80aa --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.Direct.cfg @@ -0,0 +1,5 @@ +CONSTANT AtomicPublish = FALSE +SPECIFICATION Spec +INVARIANT VisibleIsReady +INVARIANT FailedIsClean +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CustomToolCache.cfg b/docs/architecture/tla/CustomToolCache.cfg new file mode 100644 index 0000000000..26e92020d3 --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.cfg @@ -0,0 +1,5 @@ +CONSTANT AtomicPublish = TRUE +SPECIFICATION Spec +INVARIANT VisibleIsReady +INVARIANT FailedIsClean +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CustomToolCache.tla b/docs/architecture/tla/CustomToolCache.tla new file mode 100644 index 0000000000..b0523cfbe1 --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.tla @@ -0,0 +1,61 @@ +------------------------- MODULE CustomToolCache ------------------------- +(* +Source: CustomToolRegistry.import calls runEsbuild. Sink: import(bundle.mjs). +Failure: A reader sees a bundle before the write and mode checks finish. +Invariant: Each visible bundle is complete, private, and checked. +Failure: A failed writer leaves a pending file. Invariant: Failed writers clean up. +Expectation: Direct publication fails. Private staging passes. No new bug expected. +The review was read before this spec. The first-invariant blind step was missed. +Cost: One agent, about 6 minutes for the model and checks; no delegate. +TLC: Direct config fails VisibleIsReady at Start (2 states). Fixed config +passes both invariants (49 distinct states, depth 11). Each run took under 1s. +Replay: The four-case publication property fails 3 cases on the old code. +The fixed code passes all 53 focused tests. Type and lint checks pass. +Property: No bundle is visible before its mode check. Failed builds leave +no pending file. Tests cover success, compiler, validation, and rename errors. +Findings: The known review bug is present. No new bug or false alarm found. +The model does not prove the code. Stop can leave an unpublished temp file. +Gate: Run both configs and the publication table test by hand on each fix. +Sandbox note: TLC needs a local RMI socket. Host tests avoid mapped root uid. +Review ratchet: PR #2485 threads PRRT_kwDOSK-bwM64vzgN (ownership test), +PRRT_kwDOSK-bwM64vzgR (defaults), PRRT_kwDOSK-bwM64vzgV (publication). +Added: 1 (publication). Gap: 2 (test routing and path defaults). Covered: 0. +The gaps use direct table tests. This model checks write order only. +The compiler and file checks are oracles. Two writers use distinct pending names. +A reader can run after each step. Stop leaves the last file state on disk. +*) +EXTENDS Naturals, TLC +CONSTANT AtomicPublish +VARIABLES phase, published, pending +vars == <> +Writers == {1, 2} +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 +============================================================================= 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 4db5195f2b..9f207f192e 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 @@ -96,8 +96,10 @@ describe.sequential("CustomToolRegistry integration", () => { fs.mkdirSync(cacheDir, { mode: 0o700 }) const stat = fs.lstatSync(cacheDir) stat.uid += 1 - // The first lstat is the existing parent, then the cache root. - const spy = vi.spyOn(fs, "lstatSync").mockReturnValueOnce(fs.statSync(sandbox)).mockReturnValueOnce(stat) + const originalLstat = fs.lstatSync + const spy = vi.spyOn(fs, "lstatSync").mockImplementation((location, options) => { + return location === cacheDir ? stat : originalLstat(location, options) + }) try { expect((await registry.loadFromDirectory(toolDir)).failed[0]?.error).toContain( "Unsafe custom tool cache", @@ -107,6 +109,47 @@ describe.sequential("CustomToolRegistry integration", () => { } }) + 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 }) 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 2f29759714..e54ba8ced5 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" @@ -368,25 +368,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(tempFile, 0o600) - this.validateCachePath(tempFile, false) + 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, From 15d8290d3b2a0f4ec4996b18a836af2ff43386b8 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Thu, 19 Nov 2026 01:15:51 +0000 Subject: [PATCH 3/5] test(custom-tools): match canonical cache paths in ownership checks --- .../tla/CustomToolCache.Direct.cfg | 3 +++ .../tla/CustomToolCache.RawPath.cfg | 8 +++++++ docs/architecture/tla/CustomToolCache.cfg | 3 +++ docs/architecture/tla/CustomToolCache.tla | 23 ++++++++++++++++--- .../custom-tool-registry.integration.spec.ts | 21 ++++++++++++----- 5 files changed, 49 insertions(+), 9 deletions(-) create mode 100644 docs/architecture/tla/CustomToolCache.RawPath.cfg diff --git a/docs/architecture/tla/CustomToolCache.Direct.cfg b/docs/architecture/tla/CustomToolCache.Direct.cfg index 337b2a80aa..1b8e2f820d 100644 --- a/docs/architecture/tla/CustomToolCache.Direct.cfg +++ b/docs/architecture/tla/CustomToolCache.Direct.cfg @@ -3,3 +3,6 @@ SPECIFICATION Spec INVARIANT VisibleIsReady INVARIANT FailedIsClean CHECK_DEADLOCK FALSE + +CONSTANT CanonicalMatch = TRUE +INVARIANT OwnershipMockReachesRoot diff --git a/docs/architecture/tla/CustomToolCache.RawPath.cfg b/docs/architecture/tla/CustomToolCache.RawPath.cfg new file mode 100644 index 0000000000..679ad7e750 --- /dev/null +++ b/docs/architecture/tla/CustomToolCache.RawPath.cfg @@ -0,0 +1,8 @@ +CONSTANT AtomicPublish = TRUE +SPECIFICATION Spec +INVARIANT VisibleIsReady +INVARIANT FailedIsClean +CHECK_DEADLOCK FALSE + +CONSTANT CanonicalMatch = FALSE +INVARIANT OwnershipMockReachesRoot diff --git a/docs/architecture/tla/CustomToolCache.cfg b/docs/architecture/tla/CustomToolCache.cfg index 26e92020d3..90861ab596 100644 --- a/docs/architecture/tla/CustomToolCache.cfg +++ b/docs/architecture/tla/CustomToolCache.cfg @@ -3,3 +3,6 @@ SPECIFICATION Spec INVARIANT VisibleIsReady INVARIANT FailedIsClean CHECK_DEADLOCK FALSE + +CONSTANT CanonicalMatch = TRUE +INVARIANT OwnershipMockReachesRoot diff --git a/docs/architecture/tla/CustomToolCache.tla b/docs/architecture/tla/CustomToolCache.tla index b0523cfbe1..756dd77ae5 100644 --- a/docs/architecture/tla/CustomToolCache.tla +++ b/docs/architecture/tla/CustomToolCache.tla @@ -15,17 +15,29 @@ Property: No bundle is visible before its mode check. Failed builds leave no pending file. Tests cover success, compiler, validation, and rename errors. Findings: The known review bug is present. No new bug or false alarm found. The model does not prove the code. Stop can leave an unpublished temp file. -Gate: Run both configs and the publication table test by hand on each fix. +Gate: Run all configs and both property tables by hand on each fix. Sandbox note: TLC needs a local RMI socket. Host tests avoid mapped root uid. Review ratchet: PR #2485 threads PRRT_kwDOSK-bwM64vzgN (ownership test), PRRT_kwDOSK-bwM64vzgR (defaults), PRRT_kwDOSK-bwM64vzgV (publication). Added: 1 (publication). Gap: 2 (test routing and path defaults). Covered: 0. -The gaps use direct table tests. This model checks write order only. +The original gaps use direct table tests. +Round 2: PR #2485, thread PRRT_kwDOSK-bwM64vzgN, reply 4622881580. +Failure: A raw path match misses the cache root after parent alias resolution. +Invariant: The ownership double matches the resolved root for each path. +Expectation: Raw matching fails for an alias. Canonical matching passes. +Added: 1. Covered: 0. Gap: 0. The compiler and path lookup remain oracles. +Round 2 cost: One agent, about 3 minutes; no delegate. +TLC: RawPath fails OwnershipMockReachesRoot. Direct fails VisibleIsReady. +Fixed passes all three invariants (49 states). Each run took under 1s. +Replay: The raw comparison passes the direct case and fails the alias case. +Findings: The known path mismatch is real. No new bug or false alarm found. +The path property checks both routes with the real filesystem and registry. +Round 2 validation: All 54 registry tests, type checking, and package lint pass. The compiler and file checks are oracles. Two writers use distinct pending names. A reader can run after each step. Stop leaves the last file state on disk. *) EXTENDS Naturals, TLC -CONSTANT AtomicPublish +CONSTANTS AtomicPublish, CanonicalMatch VARIABLES phase, published, pending vars == <> Writers == {1, 2} @@ -58,4 +70,9 @@ Next == \E w \in Writers : Start(w) \/ Finish(w) \/ Restrict(w) \/ Check(w) \/ P 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) ============================================================================= 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 9f207f192e..63a1c9846d 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 @@ -92,18 +92,27 @@ describe.sequential("CustomToolRegistry integration", () => { }, ) - it("rejects a cache owned by another account", async () => { + it.each(["direct", "symlink-parent"])("rejects a cache owned by another account via %s", async (kind) => { fs.mkdirSync(cacheDir, { mode: 0o700 }) - const stat = fs.lstatSync(cacheDir) + 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 === cacheDir ? stat : originalLstat(location, options) + return location === resolvedCacheDir ? stat : originalLstat(location, options) }) try { - expect((await registry.loadFromDirectory(toolDir)).failed[0]?.error).toContain( - "Unsafe custom tool cache", - ) + 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() } From 739eb02aa2ea5ed5e69b6a2970a773e45c730bdd Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Thu, 19 Nov 2026 03:36:43 +0000 Subject: [PATCH 4/5] fix(tla): move custom tool cache writer bound to MC module --- docs/architecture/tla/CustomToolCache.Direct.cfg | 1 + .../architecture/tla/CustomToolCache.RawPath.cfg | 1 + docs/architecture/tla/CustomToolCache.cfg | 1 + docs/architecture/tla/CustomToolCache.tla | 16 +++++++++++++--- docs/architecture/tla/CustomToolCacheMC.tla | 6 ++++++ 5 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 docs/architecture/tla/CustomToolCacheMC.tla diff --git a/docs/architecture/tla/CustomToolCache.Direct.cfg b/docs/architecture/tla/CustomToolCache.Direct.cfg index 1b8e2f820d..f7b094f947 100644 --- a/docs/architecture/tla/CustomToolCache.Direct.cfg +++ b/docs/architecture/tla/CustomToolCache.Direct.cfg @@ -1,3 +1,4 @@ +CONSTANT Writers <- MCWriters CONSTANT AtomicPublish = FALSE SPECIFICATION Spec INVARIANT VisibleIsReady diff --git a/docs/architecture/tla/CustomToolCache.RawPath.cfg b/docs/architecture/tla/CustomToolCache.RawPath.cfg index 679ad7e750..8e6f962868 100644 --- a/docs/architecture/tla/CustomToolCache.RawPath.cfg +++ b/docs/architecture/tla/CustomToolCache.RawPath.cfg @@ -1,3 +1,4 @@ +CONSTANT Writers <- MCWriters CONSTANT AtomicPublish = TRUE SPECIFICATION Spec INVARIANT VisibleIsReady diff --git a/docs/architecture/tla/CustomToolCache.cfg b/docs/architecture/tla/CustomToolCache.cfg index 90861ab596..1f926c31f7 100644 --- a/docs/architecture/tla/CustomToolCache.cfg +++ b/docs/architecture/tla/CustomToolCache.cfg @@ -1,3 +1,4 @@ +CONSTANT Writers <- MCWriters CONSTANT AtomicPublish = TRUE SPECIFICATION Spec INVARIANT VisibleIsReady diff --git a/docs/architecture/tla/CustomToolCache.tla b/docs/architecture/tla/CustomToolCache.tla index 756dd77ae5..daedd1f91b 100644 --- a/docs/architecture/tla/CustomToolCache.tla +++ b/docs/architecture/tla/CustomToolCache.tla @@ -15,7 +15,7 @@ Property: No bundle is visible before its mode check. Failed builds leave no pending file. Tests cover success, compiler, validation, and rename errors. Findings: The known review bug is present. No new bug or false alarm found. The model does not prove the code. Stop can leave an unpublished temp file. -Gate: Run all configs and both property tables by hand on each fix. +Gate: Run all configs against CustomToolCacheMC and both property tables on each fix. Sandbox note: TLC needs a local RMI socket. Host tests avoid mapped root uid. Review ratchet: PR #2485 threads PRRT_kwDOSK-bwM64vzgN (ownership test), PRRT_kwDOSK-bwM64vzgR (defaults), PRRT_kwDOSK-bwM64vzgV (publication). @@ -35,12 +35,22 @@ The path property checks both routes with the real filesystem and registry. Round 2 validation: All 54 registry tests, type checking, and package lint pass. The compiler and file checks are oracles. Two writers use distinct pending names. A reader can run after each step. Stop leaves the last file state on disk. +Round 3: PR #2485, thread PRRT_kwDOSK-bwM65T3Dd, comment 4623919335. +Failure: The protocol fixes the writer count. The MC module must set the bound. +Expectation: Move the bound without changing the states or counterexamples. +Gap: 1. Added: 0. Covered: 0. A state invariant cannot check module placement. +The MC module supplies Writers. The protocol has no fixed writer count. +Round 3 cost: One agent, about 4 minutes; no delegate. +TLC: Fixed passes (49 states, depth 11). Direct fails VisibleIsReady (2 states). +RawPath fails OwnershipMockReachesRoot. Final runs took 27 to 42s. +Replay: Both existing property tables pass on the host (6 cases). +Findings: No new bug or false alarm. The model checks the same states. +Run: java -cp tlc2.TLC -metadir -config CustomToolCacheMC *) EXTENDS Naturals, TLC -CONSTANTS AtomicPublish, CanonicalMatch +CONSTANTS AtomicPublish, CanonicalMatch, Writers VARIABLES phase, published, pending vars == <> -Writers == {1, 2} Init == /\ phase = [w \in Writers |-> "idle"] /\ published = "absent" /\ pending = {} diff --git a/docs/architecture/tla/CustomToolCacheMC.tla b/docs/architecture/tla/CustomToolCacheMC.tla new file mode 100644 index 0000000000..b2cc401b04 --- /dev/null +++ b/docs/architecture/tla/CustomToolCacheMC.tla @@ -0,0 +1,6 @@ +------------------------ MODULE CustomToolCacheMC ------------------------ +(* Source: CustomToolCache.Writers. Sink: TLC exploration. +The model checks two writers. No new failure is expected from this move. *) +EXTENDS CustomToolCache +MCWriters == {1, 2} +============================================================================= From 4fd7bcdc33317434d35372b35c7b1d778336111f Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Thu, 19 Nov 2026 03:45:29 +0000 Subject: [PATCH 5/5] fix(custom-tools): keep cache cleanup within the configured root --- .../tla/CustomToolCache.Direct.cfg | 6 ++ .../tla/CustomToolCache.MixedPath.cfg | 15 ++++ .../tla/CustomToolCache.NoCleanupGuard.cfg | 15 ++++ .../tla/CustomToolCache.RawPath.cfg | 6 ++ docs/architecture/tla/CustomToolCache.cfg | 6 ++ docs/architecture/tla/CustomToolCache.tla | 89 +++++++++---------- docs/architecture/tla/CustomToolCacheMC.tla | 11 ++- .../custom-tool-registry.integration.spec.ts | 34 +++++++ .../src/custom-tools/custom-tool-registry.ts | 5 +- 9 files changed, 134 insertions(+), 53 deletions(-) create mode 100644 docs/architecture/tla/CustomToolCache.MixedPath.cfg create mode 100644 docs/architecture/tla/CustomToolCache.NoCleanupGuard.cfg diff --git a/docs/architecture/tla/CustomToolCache.Direct.cfg b/docs/architecture/tla/CustomToolCache.Direct.cfg index f7b094f947..1bb6409c3b 100644 --- a/docs/architecture/tla/CustomToolCache.Direct.cfg +++ b/docs/architecture/tla/CustomToolCache.Direct.cfg @@ -7,3 +7,9 @@ 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 index 8e6f962868..2c2f9e772c 100644 --- a/docs/architecture/tla/CustomToolCache.RawPath.cfg +++ b/docs/architecture/tla/CustomToolCache.RawPath.cfg @@ -7,3 +7,9 @@ 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 index 1f926c31f7..ead2a645cf 100644 --- a/docs/architecture/tla/CustomToolCache.cfg +++ b/docs/architecture/tla/CustomToolCache.cfg @@ -7,3 +7,9 @@ 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 index daedd1f91b..2f77f7f164 100644 --- a/docs/architecture/tla/CustomToolCache.tla +++ b/docs/architecture/tla/CustomToolCache.tla @@ -1,54 +1,40 @@ ------------------------- MODULE CustomToolCache ------------------------- -(* -Source: CustomToolRegistry.import calls runEsbuild. Sink: import(bundle.mjs). -Failure: A reader sees a bundle before the write and mode checks finish. -Invariant: Each visible bundle is complete, private, and checked. -Failure: A failed writer leaves a pending file. Invariant: Failed writers clean up. -Expectation: Direct publication fails. Private staging passes. No new bug expected. -The review was read before this spec. The first-invariant blind step was missed. -Cost: One agent, about 6 minutes for the model and checks; no delegate. -TLC: Direct config fails VisibleIsReady at Start (2 states). Fixed config -passes both invariants (49 distinct states, depth 11). Each run took under 1s. -Replay: The four-case publication property fails 3 cases on the old code. -The fixed code passes all 53 focused tests. Type and lint checks pass. -Property: No bundle is visible before its mode check. Failed builds leave -no pending file. Tests cover success, compiler, validation, and rename errors. -Findings: The known review bug is present. No new bug or false alarm found. -The model does not prove the code. Stop can leave an unpublished temp file. -Gate: Run all configs against CustomToolCacheMC and both property tables on each fix. -Sandbox note: TLC needs a local RMI socket. Host tests avoid mapped root uid. -Review ratchet: PR #2485 threads PRRT_kwDOSK-bwM64vzgN (ownership test), -PRRT_kwDOSK-bwM64vzgR (defaults), PRRT_kwDOSK-bwM64vzgV (publication). -Added: 1 (publication). Gap: 2 (test routing and path defaults). Covered: 0. -The original gaps use direct table tests. -Round 2: PR #2485, thread PRRT_kwDOSK-bwM64vzgN, reply 4622881580. -Failure: A raw path match misses the cache root after parent alias resolution. -Invariant: The ownership double matches the resolved root for each path. -Expectation: Raw matching fails for an alias. Canonical matching passes. -Added: 1. Covered: 0. Gap: 0. The compiler and path lookup remain oracles. -Round 2 cost: One agent, about 3 minutes; no delegate. -TLC: RawPath fails OwnershipMockReachesRoot. Direct fails VisibleIsReady. -Fixed passes all three invariants (49 states). Each run took under 1s. -Replay: The raw comparison passes the direct case and fails the alias case. -Findings: The known path mismatch is real. No new bug or false alarm found. -The path property checks both routes with the real filesystem and registry. -Round 2 validation: All 54 registry tests, type checking, and package lint pass. -The compiler and file checks are oracles. Two writers use distinct pending names. -A reader can run after each step. Stop leaves the last file state on disk. -Round 3: PR #2485, thread PRRT_kwDOSK-bwM65T3Dd, comment 4623919335. -Failure: The protocol fixes the writer count. The MC module must set the bound. -Expectation: Move the bound without changing the states or counterexamples. -Gap: 1. Added: 0. Covered: 0. A state invariant cannot check module placement. -The MC module supplies Writers. The protocol has no fixed writer count. -Round 3 cost: One agent, about 4 minutes; no delegate. -TLC: Fixed passes (49 states, depth 11). Direct fails VisibleIsReady (2 states). -RawPath fails OwnershipMockReachesRoot. Final runs took 27 to 42s. -Replay: Both existing property tables pass on the host (6 cases). -Findings: No new bug or false alarm. The model checks the same states. -Run: java -cp tlc2.TLC -metadir -config CustomToolCacheMC -*) +(* 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 +CONSTANTS AtomicPublish, CanonicalMatch, Writers, NormalizeCache, GuardCleanup, CleanupCases VARIABLES phase, published, pending vars == <> Init == /\ phase = [w \in Writers |-> "idle"] @@ -85,4 +71,9 @@ 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 index b2cc401b04..57b7b37e77 100644 --- a/docs/architecture/tla/CustomToolCacheMC.tla +++ b/docs/architecture/tla/CustomToolCacheMC.tla @@ -1,6 +1,13 @@ ------------------------ MODULE CustomToolCacheMC ------------------------ -(* Source: CustomToolCache.Writers. Sink: TLC exploration. -The model checks two writers. No new failure is expected from this move. *) +(* 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 63a1c9846d..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 @@ -63,6 +63,40 @@ describe.sequential("CustomToolRegistry integration", () => { 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) => { diff --git a/packages/core/src/custom-tools/custom-tool-registry.ts b/packages/core/src/custom-tools/custom-tool-registry.ts index e54ba8ced5..78e61d8bf5 100644 --- a/packages/core/src/custom-tools/custom-tool-registry.ts +++ b/packages/core/src/custom-tools/custom-tool-registry.ts @@ -254,7 +254,8 @@ export class CustomToolRegistry { private prepareCacheDirectory(): void { // Resolve platform aliases (e.g. /var on macOS), then check ancestors before writing. - let ancestor = path.dirname(path.resolve(this.cacheDir)) + 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)) @@ -277,7 +278,7 @@ export class CustomToolRegistry { fs.mkdirSync(parent, { recursive: true, mode: 0o700 }) this.validateCachePath(parent, true) } - this.cacheDir = path.join(parent, path.basename(this.cacheDir)) + this.cacheDir = path.join(parent, path.basename(normalizedCacheDir)) fs.mkdirSync(this.cacheDir, { recursive: true, mode: 0o700 }) this.validateCachePath(this.cacheDir, true) }