Skip to content

Commit 67855ea

Browse files
committed
fix(core): authorize Code Mode file fetches
Bun's fetch accepts file URLs, allowing Code Mode to bypass read and external-directory permissions. Authorize file targets through the shared FileAccess service before fetching the resolved path, using the invoking session, agent, and tool-call identity. Bind the web extension to execution scope so pending file approvals do not outlive the run. Leave request methods and URL schemes to the runtime. Add real-service tests for permissions, approval ordering, cancellation, encoded paths, native file-fetch behavior, and HTTP-to-file redirects. Fixes anomalyco#50771
1 parent 4617210 commit 67855ea

12 files changed

Lines changed: 293 additions & 16 deletions

File tree

‎packages/core/src/codemode/tool.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
export * as CodeModeTool from "./tool.js"
22

3-
import { CodeMode, Namespace, Tool, toolError } from "@opencode/codemode"
3+
import { CodeMode, Extension, Namespace, Tool, toolError } from "@opencode/codemode"
44
import type {
55
Content,
66
Context,
@@ -14,6 +14,7 @@ import { Effect, Ref, Schema, Semaphore } from "effect"
1414
import { definition, normalizedName } from "../tool/runtime.js"
1515
import { CodeModeCatalog } from "./catalog.js"
1616
import { CodeModeWeb } from "./web.js"
17+
import type { FileAccess } from "../file-access.js"
1718

1819
const ExecuteFile = Schema.Struct({
1920
data: Schema.String,
@@ -61,7 +62,7 @@ export type Inventory = {
6162
// Invariant model-facing guidance; the changing tool catalog is delivered through Instructions.
6263
const description = [
6364
"Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.",
64-
"`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable; all other external access goes through `tools`.",
65+
"`fetch` is available for HTTP requests and permission-checked file reads. Imports and timers are unavailable; all other external access goes through `tools`.",
6566
"Within `{ code }`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Inside `{ code }`, ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.",
6667
'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.<namespace>["tool-name"](input)`.',
6768
"Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.",
@@ -70,6 +71,7 @@ const description = [
7071

7172
export const create = (
7273
inventory: Inventory,
74+
access: Pick<FileAccess.Interface, "authorizeRead">,
7375
executeTool: (name: string, tool: Info, input: unknown, context: Context) => Effect.Effect<Result, Error>,
7476
) => {
7577
return {
@@ -79,6 +81,7 @@ export const create = (
7981
output: ExecuteOutput,
8082
execute: ({ code }, context) =>
8183
Effect.gen(function* () {
84+
const signal = yield* Effect.abortSignal
8285
const callIndex = yield* Ref.make(0)
8386
const files = yield* Ref.make<Array<CollectedFiles>>([])
8487
const calls = yield* Ref.make<Array<ExecuteCall>>([])
@@ -105,6 +108,7 @@ export const create = (
105108
return text === "" ? null : text
106109
}),
107110
progressHooks(record),
111+
[CodeModeWeb.extension(access, context, signal)],
108112
).execute(code)
109113
const toolCalls = yield* Ref.get(calls)
110114
const collected = (yield* Ref.get(files))
@@ -135,7 +139,7 @@ export const create = (
135139
content,
136140
metadata,
137141
}
138-
}),
142+
}).pipe(Effect.scoped),
139143
} satisfies Info
140144
}
141145

@@ -222,6 +226,7 @@ function runtime(
222226
inventory: Inventory,
223227
executeTool: (name: string, tool: Info, input: unknown) => Effect.Effect<unknown, unknown>,
224228
hooks?: CodeMode.Hooks,
229+
extensions: ReadonlyArray<Extension.Extension> = [],
225230
) {
226231
// A path may carry namespace metadata, a callable tool, child tools, or all three.
227232
const root: ToolNode = { children: new Map() }
@@ -236,7 +241,7 @@ function runtime(
236241
})
237242
}
238243
const tools = renderTools(root)
239-
return CodeMode.make<typeof tools>({ tools, extensions: [CodeModeWeb.extension], hooks })
244+
return CodeMode.make<typeof tools>({ tools, extensions, hooks })
240245
}
241246

242247
function getNode<T>(root: Node<T>, path: string) {

‎packages/core/src/codemode/web.ts‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
export * as CodeModeWeb from "./web.js"
22

33
import { Extension } from "@opencode/codemode"
4+
import { Effect } from "effect"
5+
import { fileURLToPath, pathToFileURL } from "node:url"
6+
import type { FileAccess } from "../file-access.js"
47

58
const TIMEOUT_MS = 30_000
69

@@ -10,12 +13,24 @@ type Init = {
1013
readonly body?: string | Uint8Array<ArrayBuffer> | URLSearchParams
1114
}
1215

13-
const fetch = async (input: string | URL, init: Init = {}) => {
14-
const response = await globalThis.fetch(input, {
16+
const fetch = async (
17+
input: string | URL,
18+
init: Init,
19+
access: Pick<FileAccess.Interface, "authorizeRead">,
20+
context: FileAccess.Invocation,
21+
signal: AbortSignal,
22+
) => {
23+
const url = new URL(input)
24+
const target =
25+
url.protocol === "file:"
26+
? pathToFileURL((await Effect.runPromise(access.authorizeRead(fileURLToPath(url), context), { signal })).absolute)
27+
: url
28+
signal.throwIfAborted()
29+
const response = await globalThis.fetch(target, {
1530
method: init.method,
1631
headers: init.headers,
1732
body: init.body,
18-
signal: AbortSignal.timeout(TIMEOUT_MS),
33+
signal: AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)]),
1934
})
2035
const bytes = await response.bytes()
2136
const headers = Object.fromEntries(response.headers)
@@ -37,7 +52,15 @@ const fetch = async (input: string | URL, init: Init = {}) => {
3752
}
3853
}
3954

40-
export const extension = Extension.make({ name: "web", globals: { fetch } })
55+
export const extension = (
56+
access: Pick<FileAccess.Interface, "authorizeRead">,
57+
context: FileAccess.Invocation,
58+
signal: AbortSignal,
59+
) =>
60+
Extension.make({
61+
name: "web",
62+
globals: { fetch: (input: string | URL, init: Init = {}) => fetch(input, init, access, context, signal) },
63+
})
4164

4265
/** What to show for a fetch call: its method and URL. */
4366
export const display = (args: ReadonlyArray<unknown>) => {

‎packages/core/src/tool.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { makeLocationNode } from "@opencode/util/effect/app-node"
99
import type { Agent } from "./agent.js"
1010
import { CodeModeCatalog } from "./codemode/catalog.js"
1111
import { CodeModeTool } from "./codemode/tool.js"
12+
import { FileAccess } from "./file-access.js"
1213
import { Image } from "./image.js"
1314
import { Permission } from "./permission.js"
1415
import { PluginHooks } from "./plugin/hooks.js"
@@ -69,6 +70,7 @@ const layer = Layer.effect(
6970
Effect.gen(function* () {
7071
const hooks = yield* PluginHooks.Service
7172
const image = yield* Image.Service
73+
const access = yield* FileAccess.Service
7274

7375
type NormalizedItem = Tool.Content | "decode" | "size"
7476
const normalizeImages = Effect.fnUntraced(function* (content: ReadonlyArray<Tool.Content>) {
@@ -237,7 +239,7 @@ const layer = Layer.effect(
237239
const codeModeInventory = { tools: codeModeTools, namespaces }
238240
const codeModeEnabled = !whollyDisabled("execute", rules)
239241
const codeModeTool = codeModeEnabled
240-
? CodeModeTool.create(codeModeInventory, (name, tool, input, context) =>
242+
? CodeModeTool.create(codeModeInventory, access, (name, tool, input, context) =>
241243
beforeExecute(name, input, context).pipe(
242244
Effect.flatMap((event) => executeTool(tool, name, event.input, context)),
243245
),
@@ -328,5 +330,5 @@ function namespaceError(name: string) {
328330
export const node = makeLocationNode({
329331
service: Service,
330332
layer,
331-
deps: [PluginHooks.node, Image.node],
333+
deps: [PluginHooks.node, Image.node, FileAccess.node],
332334
})
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
import { describe, expect } from "bun:test"
2+
import path from "node:path"
3+
import { pathToFileURL } from "node:url"
4+
import { Effect, Fiber } from "effect"
5+
import { Agent } from "@opencode/core/agent"
6+
import { Database } from "@opencode/core/database/database"
7+
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
8+
import { Image } from "@opencode/core/image"
9+
import { Location } from "@opencode/core/location"
10+
import { Permission } from "@opencode/core/permission"
11+
import { Project } from "@opencode/core/project"
12+
import { ProjectTable } from "@opencode/core/project/sql"
13+
import { Session } from "@opencode/core/session"
14+
import { SessionTable } from "@opencode/core/session/sql"
15+
import { Tool } from "@opencode/core/tool"
16+
import { LayerNode } from "@opencode/util/effect/layer-node"
17+
import { tempLocationLayer } from "../fixture/location"
18+
import { tmpdirScoped } from "../fixture/tmpdir"
19+
import { testEffect } from "../lib/effect"
20+
import { imagePassthrough } from "../lib/image"
21+
import { toolIdentity } from "../lib/tool"
22+
23+
const it = testEffect(
24+
AppNodeBuilder.build(LayerNode.group([Tool.node, Location.node, Database.node, Agent.node, Permission.node]), [
25+
Location.node.replace(tempLocationLayer),
26+
Image.node.replace(imagePassthrough),
27+
]),
28+
)
29+
const sessionID = Session.ID.make("ses_codemode_web")
30+
const invocation = { ...toolIdentity, agent: Agent.ID.make("test"), sessionID }
31+
32+
const setup = Effect.fnUntraced(function* (rules: Permission.Ruleset = []) {
33+
const database = yield* Database.Service
34+
const location = yield* Location.Service
35+
yield* database.db
36+
.insert(ProjectTable)
37+
.values({ id: Project.ID.global, worktree: location.directory, sandboxes: [] })
38+
.onConflictDoNothing()
39+
.run()
40+
.pipe(Effect.orDie)
41+
yield* database.db
42+
.insert(SessionTable)
43+
.values({
44+
id: sessionID,
45+
project_id: Project.ID.global,
46+
slug: "test",
47+
directory: location.directory,
48+
title: "test",
49+
version: "test",
50+
agent: "test",
51+
})
52+
.onConflictDoNothing()
53+
.run()
54+
.pipe(Effect.orDie)
55+
const agents = yield* Agent.Service
56+
yield* agents.transform((editor) =>
57+
editor.update(invocation.agent, (agent) => {
58+
agent.permissions = [{ action: "*", resource: "*", effect: "allow" }, ...rules]
59+
}),
60+
)
61+
})
62+
63+
const execute = Effect.fnUntraced(function* (code: string) {
64+
const tools = yield* Tool.Service
65+
const snapshot = yield* tools.snapshot()
66+
return yield* snapshot.execute({
67+
...invocation,
68+
call: { type: "tool-call", id: "call-fetch", name: "execute", input: { code } },
69+
})
70+
})
71+
72+
describe("Code Mode fetch", () => {
73+
it.live("uses read permissions for encoded file URLs and preserves allowed response methods", () =>
74+
Effect.gen(function* () {
75+
yield* setup([
76+
{ action: "read", resource: "*", effect: "deny" },
77+
{ action: "read", resource: "report # café.txt", effect: "allow" },
78+
])
79+
const location = yield* Location.Service
80+
const file = path.join(location.directory, "report # café.txt")
81+
yield* Effect.promise(() => Bun.write(file, '{"value":"allowed"}'))
82+
const url = JSON.stringify(pathToFileURL(file).href)
83+
const result = yield* execute(`
84+
const response = await fetch(new URL(${url}))
85+
return [response.status, response.ok, await response.text(), await response.json(), (await response.bytes()).length]
86+
`)
87+
expect(result.metadata?.error).toBeUndefined()
88+
expect(JSON.parse(result.content[0].type === "text" ? result.content[0].text : "")).toEqual([
89+
200,
90+
true,
91+
'{"value":"allowed"}',
92+
{ value: "allowed" },
93+
19,
94+
])
95+
}),
96+
)
97+
98+
for (const action of ["read", "external_directory"]) {
99+
it.live(`refuses ${action}-denied file reads even when the program catches the error`, () =>
100+
Effect.gen(function* () {
101+
yield* setup([{ action, resource: "*", effect: "deny" }])
102+
const location = yield* Location.Service
103+
const external = yield* tmpdirScoped()
104+
const file = path.join(action === "read" ? location.directory : external.path, "secret.txt")
105+
yield* Effect.promise(() => Bun.write(file, "must not be disclosed"))
106+
const result = yield* execute(`
107+
try { return await (await fetch(${JSON.stringify(pathToFileURL(file).href)})).text() }
108+
catch (error) { return error.message }
109+
`)
110+
expect(result.content).toEqual([{ type: "text", text: `Permission denied: ${action}` }])
111+
}),
112+
)
113+
}
114+
115+
it.live("waits for file approval and attributes it to the invoking session and tool call", () =>
116+
Effect.gen(function* () {
117+
yield* setup([{ action: "read", resource: "*", effect: "ask" }])
118+
const location = yield* Location.Service
119+
const file = path.join(location.directory, "pending.txt")
120+
yield* Effect.promise(() => Bun.write(file, "before approval"))
121+
const permissions = yield* Permission.Service
122+
const fiber = yield* execute(
123+
`return await (await fetch(${JSON.stringify(pathToFileURL(file).href)})).text()`,
124+
).pipe(Effect.forkScoped)
125+
const request = yield* Effect.gen(function* () {
126+
while (true) {
127+
const pending = yield* permissions.forSession(sessionID)
128+
if (pending[0]) return pending[0]
129+
yield* Effect.promise(() => Bun.sleep(1))
130+
}
131+
}).pipe(Effect.timeout("5 seconds"))
132+
expect(request).toMatchObject({
133+
sessionID,
134+
action: "read",
135+
resources: ["pending.txt"],
136+
source: { type: "tool", messageID: invocation.messageID, id: "call-fetch" },
137+
})
138+
yield* Effect.promise(() => Bun.write(file, "after approval"))
139+
yield* permissions.reply({ requestID: request.id, reply: "once" })
140+
expect((yield* Fiber.join(fiber)).content).toEqual([{ type: "text", text: "after approval" }])
141+
}),
142+
)
143+
144+
it.live("cancels pending file approval when the execution is interrupted", () =>
145+
Effect.gen(function* () {
146+
yield* setup([{ action: "read", resource: "*", effect: "ask" }])
147+
const location = yield* Location.Service
148+
const permissions = yield* Permission.Service
149+
const fiber = yield* execute(
150+
`return await fetch(${JSON.stringify(pathToFileURL(path.join(location.directory, "pending.txt")).href)})`,
151+
).pipe(Effect.forkScoped)
152+
yield* Effect.gen(function* () {
153+
while ((yield* permissions.forSession(sessionID)).length === 0) yield* Effect.promise(() => Bun.sleep(1))
154+
}).pipe(Effect.timeout("5 seconds"))
155+
yield* Fiber.interrupt(fiber)
156+
expect(yield* permissions.forSession(sessionID)).toEqual([])
157+
}),
158+
)
159+
160+
it.live("preserves Bun's file method handling and non-file URL schemes", () =>
161+
Effect.gen(function* () {
162+
yield* setup()
163+
const location = yield* Location.Service
164+
const file = path.join(location.directory, "unchanged.txt")
165+
yield* Effect.promise(() => Bun.write(file, "unchanged"))
166+
const result = yield* execute(`
167+
const values = []
168+
for (const init of [
169+
{},
170+
{ method: "HEAD" },
171+
{ method: "POST", body: "replacement" },
172+
{ method: "PUT", body: "replacement" },
173+
{ method: "PATCH", body: "replacement" },
174+
{ method: "DELETE" },
175+
{ body: "replacement" },
176+
]) {
177+
values.push(await (await fetch(${JSON.stringify(pathToFileURL(file).href)}, init)).text())
178+
}
179+
values.push(await (await fetch("data:text/plain,hello")).text())
180+
return values
181+
`)
182+
expect(result.content[0].type === "text" ? JSON.parse(result.content[0].text) : []).toEqual([
183+
...Array(7).fill("unchanged"),
184+
"hello",
185+
])
186+
expect(yield* Effect.promise(() => Bun.file(file).text())).toBe("unchanged")
187+
}),
188+
)
189+
190+
it.live("preserves HTTP redirects and rejects redirects to file URLs", () =>
191+
Effect.gen(function* () {
192+
yield* setup([{ action: "read", resource: "*", effect: "deny" }])
193+
const location = yield* Location.Service
194+
const file = path.join(location.directory, "secret.txt")
195+
yield* Effect.promise(() => Bun.write(file, "must not be disclosed"))
196+
const server = yield* Effect.acquireRelease(
197+
Effect.sync(() =>
198+
Bun.serve({
199+
port: 0,
200+
fetch: (request) => {
201+
const url = new URL(request.url)
202+
if (url.pathname === "/file") return Response.redirect(pathToFileURL(file).href, 302)
203+
if (url.pathname === "/redirect") return Response.redirect(new URL("/target", url).href, 302)
204+
return Response.json({ value: "network" })
205+
},
206+
}),
207+
),
208+
(server) => Effect.promise(() => server.stop(true)),
209+
)
210+
const allowed = yield* execute(
211+
`return await (await fetch(${JSON.stringify(new URL("/redirect", server.url).href)})).json()`,
212+
)
213+
expect(allowed.content).toEqual([{ type: "text", text: '{\n "value": "network"\n}' }])
214+
const denied = yield* execute(
215+
`return await (await fetch(${JSON.stringify(new URL("/file", server.url).href)})).text()`,
216+
)
217+
expect(denied.metadata?.error).toBe(true)
218+
expect(JSON.stringify(denied.content)).not.toContain("must not be disclosed")
219+
}),
220+
)
221+
})
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { Permission } from "@opencode/core/permission"
2+
import { FileAccess } from "@opencode/core/file-access"
23
import { Effect, Layer } from "effect"
34

45
export const permissionLayer = (overrides: Partial<Permission.Interface> = {}) =>
56
Layer.mock(Permission.Service, { close: Effect.void, ...overrides })
7+
8+
export const fileAccessUnavailable = Layer.mock(FileAccess.Service, {
9+
authorizeRead: () => Effect.die("File access is unavailable in this test"),
10+
})

0 commit comments

Comments
 (0)