GeezerVison is showing github.com — fix(core): apply webfetch permissions to Code Mode fetch · anomalyco/opencode@fd5f2f0
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboard +7Lines changed: 7 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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") {} |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/codemode/tool.ts +6-1Lines changed: 6 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -12,7 +12,9 @@ import type { | 12 | 12 | } from "@opencode/schema/tool" | 13 | 13 | import { Context, Effect, Ref, Schema, Semaphore } from "effect" | 14 | 14 | import { definition, normalizedName } from "../tool/runtime.js" | | 15 | +import { Permission } from "../permission.js" | 15 | 16 | import { CodeModeCatalog } from "./catalog.js" | | 17 | +import { CodeModeExecution } from "./execution.js" | 16 | 18 | import { CodeModeWeb } from "./web.js" | 17 | 19 |
| 18 | 20 | const ExecuteFile = Schema.Struct({ | @@ -80,6 +82,7 @@ const description = [ | 80 | 82 | export const create = ( | 81 | 83 | inventory: Inventory, | 82 | 84 | executeTool: (name: string, tool: Info, input: unknown, context: ToolContext) => Effect.Effect<Result, Error>, | | 85 | + permission: Permission.Interface, | 83 | 86 | ) => { | 84 | 87 | return { | 85 | 88 | name: "execute", | @@ -117,6 +120,8 @@ export const create = ( | 117 | 120 | }), | 118 | 121 | hooks: progressHooks(record), | 119 | 122 | }), | | 123 | + Effect.provideService(CodeModeExecution.Service, context), | | 124 | + Effect.provideService(Permission.Service, permission), | 120 | 125 | ) | 121 | 126 | const toolCalls = yield* Ref.get(calls) | 122 | 127 | const collected = (yield* Ref.get(files)) | @@ -232,7 +237,7 @@ function renderCatalog(root: CatalogNode): ReadonlyArray<CodeModeCatalog.Tool | | 232 | 237 |
| 233 | 238 | // Inventories are immutable snapshots, so tool definitions, schemas, and the search index are built | 234 | 239 | // 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>>() | 236 | 241 |
| 237 | 242 | function runtime(inventory: Inventory) { | 238 | 243 | const cached = runtimes.get(inventory) | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/codemode/web.ts +24-3Lines changed: 24 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -2,6 +2,9 @@ export * as CodeModeWeb from "./web.js" | 2 | 2 |
| 3 | 3 | import { Extension } from "@opencode/codemode" | 4 | 4 | import { isRecord } from "@opencode/util/record" | | 5 | +import { Effect } from "effect" | | 6 | +import { Permission } from "../permission.js" | | 7 | +import { CodeModeExecution } from "./execution.js" | 5 | 8 |
| 6 | 9 | const TIMEOUT_MS = 30_000 | 7 | 10 |
| @@ -11,9 +14,27 @@ type Init = { | 11 | 14 | readonly body?: string | Uint8Array<ArrayBuffer> | URLSearchParams | 12 | 15 | } | 13 | 16 |
| 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) => { | 17 | 38 | const response = await globalThis.fetch(input, { | 18 | 39 | method: init.method, | 19 | 40 | headers: init.headers, | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/tool.ts +9-5Lines changed: 9 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -71,6 +71,7 @@ const layer = Layer.effect( | 71 | 71 | Effect.gen(function* () { | 72 | 72 | const hooks = yield* PluginHooks.Service | 73 | 73 | const image = yield* Image.Service | | 74 | + const permission = yield* Permission.Service | 74 | 75 |
| 75 | 76 | type NormalizedItem = Tool.Content | "decode" | "size" | 76 | 77 | const normalizeImages = Effect.fnUntraced(function* (content: ReadonlyArray<Tool.Content>) { | @@ -268,10 +269,13 @@ const layer = Layer.effect( | 268 | 269 | const cached = catalog?.data === data && catalog.names === names ? catalog : undefined | 269 | 270 | const codeModeInventory = cached?.inventory ?? { tools: codeModeTools, namespaces: data.namespaces } | 270 | 271 | 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, | 275 | 279 | ) | 276 | 280 | : undefined | 277 | 281 | const codeModeCatalog = !codeModeEnabled | @@ -362,5 +366,5 @@ function namespaceError(name: string) { | 362 | 366 | export const node = makeLocationNode({ | 363 | 367 | service: Service, | 364 | 368 | layer, | 365 | | - deps: [PluginHooks.node, Image.node], | | 369 | + deps: [PluginHooks.node, Image.node, Permission.node], | 366 | 370 | }) |
Collapse file Copy file name to clipboardExpand all lines: packages/core/test/lib/permission.ts +7Lines changed: 7 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -3,3 +3,10 @@ import { Effect, Layer } from "effect" | 3 | 3 |
| 4 | 4 | export const permissionLayer = (overrides: Partial<Permission.Interface> = {}) => | 5 | 5 | 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 | + ) |
Collapse file Copy file name to clipboardExpand all lines: packages/core/test/tool-execute.test.ts +68-5Lines changed: 68 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | | -import { expect, test } from "bun:test" | | 1 | +import { afterAll, beforeAll, describe, expect, test } from "bun:test" | 2 | 2 | import { CodeModeTool } from "@opencode/core/codemode/tool" | | 3 | +import { Permission } from "@opencode/core/permission" | 3 | 4 | import { Tool } from "@opencode/core/tool" | 4 | 5 | import { execute } from "@opencode/core/tool/runtime" | 5 | 6 | import { Agent } from "@opencode/schema/agent" | 6 | 7 | import { Session } from "@opencode/schema/session" | 7 | 8 | import { SessionMessage } from "@opencode/schema/session-message" | 8 | 9 | import type { Info } from "@opencode/schema/tool" | 9 | 10 | import { Effect, Schema } from "effect" | | 11 | +import { permissionService } from "./lib/permission" | 10 | 12 |
| 11 | 13 | const context = { | 12 | 14 | sessionID: Session.ID.make("ses_execute"), | @@ -16,8 +18,10 @@ const context = { | 16 | 18 | progress: () => Effect.void, | 17 | 19 | } | 18 | 20 |
| 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) | 21 | 25 |
| 22 | 26 | test("execute describes invariant Code Mode behavior", () => { | 23 | 27 | expect(createCodeMode(new Map()).description).toBe( | @@ -41,6 +45,65 @@ test("execute rejects filesystem fetches", async () => { | 41 | 45 | expect(result.output.output).toContain("fetch cannot be used for filesystem access.") | 42 | 46 | }) | 43 | 47 |
| | 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 | + | 44 | 107 | test("canonical execution distinguishes declared, model-only, and raw schema outputs", async () => { | 45 | 108 | const declared: Info = { | 46 | 109 | name: "declared", | @@ -177,10 +240,10 @@ test("executions share the prepared runtime of an inventory while keeping per-ca | 177 | 240 | execute: (input, context) => Effect.succeed({ content: `${context.id}:${(input as { value: string }).value}` }), | 178 | 241 | } | 179 | 242 | 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) | 181 | 244 | const run = (id: string) => { | 182 | 245 | 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) | 184 | 247 | .execute( | 185 | 248 | { code: `return await tools.echo({ value: "${id}" })` }, | 186 | 249 | { ...context, id: Tool.CallID.make(id), progress: (update) => Effect.sync(() => progress.push(update)) }, | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/test/tool-registry.test.ts +4-5Lines changed: 4 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import { describe, expect } from "bun:test" | 2 | 2 | import { Agent } from "@opencode/core/agent" | 3 | | -import type { Permission } from "@opencode/core/permission" | | 3 | +import { Permission } from "@opencode/core/permission" | 4 | 4 | import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" | 5 | 5 | import { Image } from "@opencode/core/image" | 6 | 6 | import { PluginHooks } from "@opencode/core/plugin/hooks" | @@ -14,6 +14,7 @@ import { codeModeListings, executeTool, toolDefinitions } from "./lib/tool" | 14 | 14 | import { Deferred, Effect, Exit, Fiber, Layer, Logger, Schema, SchemaGetter, SchemaIssue, Scope } from "effect" | 15 | 15 | import { z } from "zod" | 16 | 16 | import { testEffect } from "./lib/effect" | | 17 | +import { permissionLayer } from "./lib/permission" | 17 | 18 |
| 18 | 19 | const imageStore = Layer.mock(Image.Service, { | 19 | 20 | normalize: (resource, content) => { | @@ -39,6 +40,7 @@ const imageStore = Layer.mock(Image.Service, { | 39 | 40 | }) | 40 | 41 | const registryLayer = AppNodeBuilder.build(LayerNode.group([Tool.node, PluginHooks.node]), [ | 41 | 42 | Image.node.replace(imageStore), | | 43 | + Permission.node.replace(permissionLayer()), | 42 | 44 | ]) | 43 | 45 | const it = testEffect(registryLayer) | 44 | 46 | const identity = { | @@ -719,10 +721,7 @@ describe("Tool", () => { | 719 | 721 | expect(snapshot.codeModeCatalog).toBeUndefined() | 720 | 722 | expect((yield* snapshot.execute(call("mcp_lookup"))).output).toEqual({ text: "mcp_lookup" }) | 721 | 723 |
| 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" }]) | 726 | 725 | expect(hidden.definitions.map((tool) => tool.name)).toEqual(["bash"]) | 727 | 726 | expect(yield* hidden.execute(call("mcp_lookup")).pipe(Effect.flip)).toBeInstanceOf(Tool.Error) | 728 | 727 | }), | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/test/tool-todo.test.ts +4-1Lines changed: 4 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -3,6 +3,7 @@ import { Effect, Layer, Stream } from "effect" | 3 | 3 | import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" | 4 | 4 | import { Config } from "@opencode/core/config" | 5 | 5 | import { Image } from "@opencode/core/image" | | 6 | +import { Permission } from "@opencode/core/permission" | 6 | 7 | import { Session } from "@opencode/core/session" | 7 | 8 | import { Tool } from "@opencode/core/tool" | 8 | 9 | import { TodoTool } from "@opencode/core/tool/plugin/todo" | @@ -22,7 +23,9 @@ const todos = [ | 22 | 23 | { content: "Rewrite everything", status: "cancelled" }, | 23 | 24 | ] as const | 24 | 25 |
| 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 | +) | 26 | 29 |
| 27 | 30 | const setup = (experimental: ConfigExperimental.Info | undefined) => | 28 | 31 | Effect.gen(function* () { | |
|