Skip to content

Commit fd5f2f0

Browse files
committed
fix(core): apply webfetch permissions to Code Mode fetch
1 parent fb2d998 commit fd5f2f0

8 files changed

Lines changed: 129 additions & 20 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export * as CodeModeExecution from "./execution.js"
2+
3+
import type { Context as ToolContext } from "@opencode/schema/tool"
4+
import { Context } from "effect"
5+
6+
/** The `execute` call a Code Mode program runs under, so extensions can act for its session like a tool does. */
7+
export class Service extends Context.Service<Service, ToolContext>()("@opencode/CodeModeExecution") {}

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ import type {
1212
} from "@opencode/schema/tool"
1313
import { Context, Effect, Ref, Schema, Semaphore } from "effect"
1414
import { definition, normalizedName } from "../tool/runtime.js"
15+
import { Permission } from "../permission.js"
1516
import { CodeModeCatalog } from "./catalog.js"
17+
import { CodeModeExecution } from "./execution.js"
1618
import { CodeModeWeb } from "./web.js"
1719

1820
const ExecuteFile = Schema.Struct({
@@ -80,6 +82,7 @@ const description = [
8082
export const create = (
8183
inventory: Inventory,
8284
executeTool: (name: string, tool: Info, input: unknown, context: ToolContext) => Effect.Effect<Result, Error>,
85+
permission: Permission.Interface,
8386
) => {
8487
return {
8588
name: "execute",
@@ -117,6 +120,8 @@ export const create = (
117120
}),
118121
hooks: progressHooks(record),
119122
}),
123+
Effect.provideService(CodeModeExecution.Service, context),
124+
Effect.provideService(Permission.Service, permission),
120125
)
121126
const toolCalls = yield* Ref.get(calls)
122127
const collected = (yield* Ref.get(files))
@@ -232,7 +237,7 @@ function renderCatalog(root: CatalogNode): ReadonlyArray<CodeModeCatalog.Tool |
232237

233238
// Inventories are immutable snapshots, so tool definitions, schemas, and the search index are built
234239
// once per inventory and shared by its catalog and every execution.
235-
const runtimes = new WeakMap<Inventory, CodeMode.Runtime<Run>>()
240+
const runtimes = new WeakMap<Inventory, CodeMode.Runtime<Run | CodeModeExecution.Service | Permission.Service>>()
236241

237242
function runtime(inventory: Inventory) {
238243
const cached = runtimes.get(inventory)

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

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

33
import { Extension } from "@opencode/codemode"
44
import { isRecord } from "@opencode/util/record"
5+
import { Effect } from "effect"
6+
import { Permission } from "../permission.js"
7+
import { CodeModeExecution } from "./execution.js"
58

69
const TIMEOUT_MS = 30_000
710

@@ -11,9 +14,27 @@ type Init = {
1114
readonly body?: string | Uint8Array<ArrayBuffer> | URLSearchParams
1215
}
1316

14-
const fetch = async (input: string | URL, init: Init = {}) => {
15-
if (URL.parse(String(input))?.protocol === "file:")
16-
throw new Error("fetch cannot be used for filesystem access.")
17+
const fetch = (input: string | URL, init: Init = {}) =>
18+
Effect.gen(function* () {
19+
const url = String(input)
20+
if (URL.parse(url)?.protocol === "file:")
21+
return yield* Effect.fail(new Error("fetch cannot be used for filesystem access."))
22+
const execution = yield* CodeModeExecution.Service
23+
const permission = yield* Permission.Service
24+
// The same rules as the webfetch tool, so a URL denied there is denied here.
25+
yield* permission.assert({
26+
action: "webfetch",
27+
resources: [url],
28+
save: ["*"],
29+
metadata: display([input, init]),
30+
sessionID: execution.sessionID,
31+
agent: execution.agent,
32+
source: { type: "tool", messageID: execution.messageID, id: execution.id },
33+
})
34+
return yield* Effect.tryPromise({ try: () => send(input, init), catch: (error) => error })
35+
})
36+
37+
const send = async (input: string | URL, init: Init) => {
1738
const response = await globalThis.fetch(input, {
1839
method: init.method,
1940
headers: init.headers,

‎packages/core/src/tool.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ const layer = Layer.effect(
7171
Effect.gen(function* () {
7272
const hooks = yield* PluginHooks.Service
7373
const image = yield* Image.Service
74+
const permission = yield* Permission.Service
7475

7576
type NormalizedItem = Tool.Content | "decode" | "size"
7677
const normalizeImages = Effect.fnUntraced(function* (content: ReadonlyArray<Tool.Content>) {
@@ -268,10 +269,13 @@ const layer = Layer.effect(
268269
const cached = catalog?.data === data && catalog.names === names ? catalog : undefined
269270
const codeModeInventory = cached?.inventory ?? { tools: codeModeTools, namespaces: data.namespaces }
270271
const codeModeTool = codeModeEnabled
271-
? CodeModeTool.create(codeModeInventory, (name, tool, input, context) =>
272-
beforeExecute(name, input, context).pipe(
273-
Effect.flatMap((event) => executeTool(tool, name, event.input, context)),
274-
),
272+
? CodeModeTool.create(
273+
codeModeInventory,
274+
(name, tool, input, context) =>
275+
beforeExecute(name, input, context).pipe(
276+
Effect.flatMap((event) => executeTool(tool, name, event.input, context)),
277+
),
278+
permission,
275279
)
276280
: undefined
277281
const codeModeCatalog = !codeModeEnabled
@@ -362,5 +366,5 @@ function namespaceError(name: string) {
362366
export const node = makeLocationNode({
363367
service: Service,
364368
layer,
365-
deps: [PluginHooks.node, Image.node],
369+
deps: [PluginHooks.node, Image.node, Permission.node],
366370
})

‎packages/core/test/lib/permission.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,10 @@ import { Effect, Layer } from "effect"
33

44
export const permissionLayer = (overrides: Partial<Permission.Interface> = {}) =>
55
Layer.mock(Permission.Service, { close: Effect.void, ...overrides })
6+
7+
export const permissionService = (overrides: Partial<Permission.Interface> = {}) =>
8+
Effect.runSync(
9+
Effect.gen(function* () {
10+
return yield* Permission.Service
11+
}).pipe(Effect.provide(permissionLayer(overrides))),
12+
)

‎packages/core/test/tool-execute.test.ts‎

Lines changed: 68 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1-
import { expect, test } from "bun:test"
1+
import { afterAll, beforeAll, describe, expect, test } from "bun:test"
22
import { CodeModeTool } from "@opencode/core/codemode/tool"
3+
import { Permission } from "@opencode/core/permission"
34
import { Tool } from "@opencode/core/tool"
45
import { execute } from "@opencode/core/tool/runtime"
56
import { Agent } from "@opencode/schema/agent"
67
import { Session } from "@opencode/schema/session"
78
import { SessionMessage } from "@opencode/schema/session-message"
89
import type { Info } from "@opencode/schema/tool"
910
import { Effect, Schema } from "effect"
11+
import { permissionService } from "./lib/permission"
1012

1113
const context = {
1214
sessionID: Session.ID.make("ses_execute"),
@@ -16,8 +18,10 @@ const context = {
1618
progress: () => Effect.void,
1719
}
1820

19-
const createCodeMode = (tools: ReadonlyMap<string, Info>) =>
20-
CodeModeTool.create({ tools }, (_, tool, input, context) => execute(tool, input, context))
21+
const allowAll = permissionService({ assert: () => Effect.void })
22+
23+
const createCodeMode = (tools: ReadonlyMap<string, Info>, permission = allowAll) =>
24+
CodeModeTool.create({ tools }, (_, tool, input, context) => execute(tool, input, context), permission)
2125

2226
test("execute describes invariant Code Mode behavior", () => {
2327
expect(createCodeMode(new Map()).description).toBe(
@@ -41,6 +45,65 @@ test("execute rejects filesystem fetches", async () => {
4145
expect(result.output.output).toContain("fetch cannot be used for filesystem access.")
4246
})
4347

48+
describe("fetch permissions", () => {
49+
const hits: Array<string> = []
50+
let server: ReturnType<typeof Bun.serve>
51+
beforeAll(() => {
52+
server = Bun.serve({
53+
port: 0,
54+
fetch: (request) => {
55+
hits.push(`${request.method} ${new URL(request.url).pathname}`)
56+
return new Response("ok")
57+
},
58+
})
59+
})
60+
afterAll(() => server.stop(true))
61+
62+
test("fetch asks the webfetch permission for its URL as the execute call", async () => {
63+
hits.length = 0
64+
const asked: Array<Permission.AssertInput> = []
65+
const url = `${server.url.origin}/allowed`
66+
const result = await Effect.runPromise(
67+
createCodeMode(
68+
new Map(),
69+
permissionService({ assert: (input) => Effect.sync(() => void asked.push(input)) }),
70+
).execute({ code: `return await (await fetch("${url}", { method: "POST" })).text()` }, context),
71+
)
72+
73+
expect(result.output.output).toBe("ok")
74+
expect(hits).toEqual(["POST /allowed"])
75+
expect(asked).toEqual([
76+
{
77+
action: "webfetch",
78+
resources: [url],
79+
save: ["*"],
80+
metadata: { method: "POST", url },
81+
sessionID: context.sessionID,
82+
agent: context.agent,
83+
source: { type: "tool", messageID: context.messageID, id: context.id },
84+
},
85+
])
86+
})
87+
88+
test("a URL denied for webfetch is never requested", async () => {
89+
hits.length = 0
90+
const url = `${server.url.origin}/denied`
91+
const denied = permissionService({
92+
assert: (input) =>
93+
Effect.fail(new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources })),
94+
})
95+
const result = await Effect.runPromise(
96+
createCodeMode(new Map(), denied).execute(
97+
{ code: `try { await fetch("${url}") } catch (e) { return "blocked: " + e.message }` },
98+
context,
99+
),
100+
)
101+
102+
expect(result.output.output).toStartWith("blocked: ")
103+
expect(hits).toEqual([])
104+
})
105+
})
106+
44107
test("canonical execution distinguishes declared, model-only, and raw schema outputs", async () => {
45108
const declared: Info = {
46109
name: "declared",
@@ -177,10 +240,10 @@ test("executions share the prepared runtime of an inventory while keeping per-ca
177240
execute: (input, context) => Effect.succeed({ content: `${context.id}:${(input as { value: string }).value}` }),
178241
}
179242
const inventory = { tools: new Map([["echo", echo]]) }
180-
const codeMode = CodeModeTool.create(inventory, (_, tool, input, context) => execute(tool, input, context))
243+
const codeMode = CodeModeTool.create(inventory, (_, tool, input, context) => execute(tool, input, context), allowAll)
181244
const run = (id: string) => {
182245
const progress: Array<Tool.Metadata> = []
183-
return CodeModeTool.create(inventory, (_, tool, input, context) => execute(tool, input, context))
246+
return CodeModeTool.create(inventory, (_, tool, input, context) => execute(tool, input, context), allowAll)
184247
.execute(
185248
{ code: `return await tools.echo({ value: "${id}" })` },
186249
{ ...context, id: Tool.CallID.make(id), progress: (update) => Effect.sync(() => progress.push(update)) },

‎packages/core/test/tool-registry.test.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, expect } from "bun:test"
22
import { Agent } from "@opencode/core/agent"
3-
import type { Permission } from "@opencode/core/permission"
3+
import { Permission } from "@opencode/core/permission"
44
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
55
import { Image } from "@opencode/core/image"
66
import { PluginHooks } from "@opencode/core/plugin/hooks"
@@ -14,6 +14,7 @@ import { codeModeListings, executeTool, toolDefinitions } from "./lib/tool"
1414
import { Deferred, Effect, Exit, Fiber, Layer, Logger, Schema, SchemaGetter, SchemaIssue, Scope } from "effect"
1515
import { z } from "zod"
1616
import { testEffect } from "./lib/effect"
17+
import { permissionLayer } from "./lib/permission"
1718

1819
const imageStore = Layer.mock(Image.Service, {
1920
normalize: (resource, content) => {
@@ -39,6 +40,7 @@ const imageStore = Layer.mock(Image.Service, {
3940
})
4041
const registryLayer = AppNodeBuilder.build(LayerNode.group([Tool.node, PluginHooks.node]), [
4142
Image.node.replace(imageStore),
43+
Permission.node.replace(permissionLayer()),
4244
])
4345
const it = testEffect(registryLayer)
4446
const identity = {
@@ -719,10 +721,7 @@ describe("Tool", () => {
719721
expect(snapshot.codeModeCatalog).toBeUndefined()
720722
expect((yield* snapshot.execute(call("mcp_lookup"))).output).toEqual({ text: "mcp_lookup" })
721723

722-
const hidden = yield* service.snapshot([
723-
...denyExecute,
724-
{ action: "mcp_lookup", resource: "*", effect: "deny" },
725-
])
724+
const hidden = yield* service.snapshot([...denyExecute, { action: "mcp_lookup", resource: "*", effect: "deny" }])
726725
expect(hidden.definitions.map((tool) => tool.name)).toEqual(["bash"])
727726
expect(yield* hidden.execute(call("mcp_lookup")).pipe(Effect.flip)).toBeInstanceOf(Tool.Error)
728727
}),

‎packages/core/test/tool-todo.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Effect, Layer, Stream } from "effect"
33
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
44
import { Config } from "@opencode/core/config"
55
import { Image } from "@opencode/core/image"
6+
import { Permission } from "@opencode/core/permission"
67
import { Session } from "@opencode/core/session"
78
import { Tool } from "@opencode/core/tool"
89
import { TodoTool } from "@opencode/core/tool/plugin/todo"
@@ -22,7 +23,9 @@ const todos = [
2223
{ content: "Rewrite everything", status: "cancelled" },
2324
] as const
2425

25-
const it = testEffect(AppNodeBuilder.build(Tool.node, [Image.node.replace(imagePassthrough)]))
26+
const it = testEffect(
27+
AppNodeBuilder.build(Tool.node, [Image.node.replace(imagePassthrough), Permission.node.replace(permissionLayer())]),
28+
)
2629

2730
const setup = (experimental: ConfigExperimental.Info | undefined) =>
2831
Effect.gen(function* () {

0 commit comments

Comments
 (0)