Skip to content

Commit c4e4f16

Browse files
author
Instinct Agent
committed
fix(core): mediate CodeMode fetch through the webfetch permission action
CodeMode executions previously called global fetch directly, bypassing permission rules. The execute tool now provides a per-execution guard built from the calling session permission service: interactive approval for the initial URL and a non-interactive check per redirect hop (manual following, 10-hop cap). Executions without a guard fail closed. The registry captures the permission service at layer construction like plugin tools do, and docs/openhands-integration.md records the state.
1 parent 3156186 commit c4e4f16

10 files changed

Lines changed: 301 additions & 41 deletions

File tree

‎docs/openhands-integration.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ Full caller ordering was inspected, not just permission call names:
9898
| Schedules | Registry/CodeMode forwards to schedule leaf. Mutation leaf now asserts create/pause/resume/delete after enabled/ownership checks, before service mutation | Focused direct+CodeMode deny/pending/cancel regression tested. Real scheduler recovery/background execution and authenticated UI still need acceptance |
9999
| Session rename/move and worktree create | Local follow-up adds leaf Permission.assert before host effects, with caller session and exact operation input | Focused real-registry/CodeMode deny regressions pass; baseline fails without checks. Permission is not filesystem containment or cross-session authorization |
100100
| Browser | Catalog visibility uses `browser` permission; execution selects desktop connection/tab and sends RPC | Visibility is not execution approval. Final per-action/URL review layer not established by this work; do not activate |
101-
| CodeMode fetch | CodeModeWeb calls global fetch with timeout; registry catalog filtering is not per-request authorization | Strict marker is not universal egress control. Must disable or mediate before guarded connection activation |
101+
| CodeMode fetch | Local follow-up mediates CodeModeWeb fetch per request through the webfetch permission action: interactive approval for the initial URL, non-interactive check per redirect hop (manual following, 10-hop cap); executions without a guard fail closed | Unit tests cover deny-before-egress, per-hop checks, fail-closed default, and a real-registry deny through the execute tool. Authenticated UI prompt flow, DNS/IP pinning and response size limits beyond the 30s timeout remain open |
102102
| Main LLM/title/compaction/plugin hooks | Model request preparation and plugin hooks have their own effect paths | Tool approval is not spending permission. No real provider was called; provider choice/budget and plugin trust require separate verified controls |
103103

104104
A default-deny launch profile is not offered until these caller paths, authenticated UI presence/disconnect, cancellation/recovery, workspace binding and the actual pinned Canvas/SDK workflow are tested together. No new generic registry authorization was added: the repository's tool architecture leaves resolution and side-effect ordering with leaves. Root marker lifecycle is not yet immutable, although an already-pending guarded request remains one-time even if metadata changes before its reply.

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,13 @@ const description = [
7777
"Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.",
7878
].join("\n")
7979

80+
const unavailable = () =>
81+
Effect.fail(new globalThis.Error("fetch is unavailable: no permission guard for this execution"))
82+
8083
export const create = (
8184
inventory: Inventory,
8285
executeTool: (name: string, tool: Info, input: unknown, context: ToolContext) => Effect.Effect<Result, Error>,
86+
guard?: (context: ToolContext) => CodeModeWeb.GuardService,
8387
) => {
8488
return {
8589
name: "execute",
@@ -117,6 +121,11 @@ export const create = (
117121
}),
118122
hooks: progressHooks(record),
119123
}),
124+
// Model-written fetch goes through the per-execution guard; without one it fails closed.
125+
Effect.provideService(
126+
CodeModeWeb.Guard,
127+
guard ? guard(context) : { approve: unavailable, check: unavailable },
128+
),
120129
)
121130
const toolCalls = yield* Ref.get(calls)
122131
const collected = (yield* Ref.get(files))
@@ -232,7 +241,7 @@ function renderCatalog(root: CatalogNode): ReadonlyArray<CodeModeCatalog.Tool |
232241

233242
// Inventories are immutable snapshots, so tool definitions, schemas, and the search index are built
234243
// once per inventory and shared by its catalog and every execution.
235-
const runtimes = new WeakMap<Inventory, CodeMode.Runtime<Run>>()
244+
const runtimes = new WeakMap<Inventory, CodeMode.Runtime<Run | CodeModeWeb.Guard>>()
236245

237246
function runtime(inventory: Inventory) {
238247
const cached = runtimes.get(inventory)

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

Lines changed: 87 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,44 +2,104 @@ export * as CodeModeWeb from "./web.js"
22

33
import { Extension } from "@harishcode/codemode"
44
import { isRecord } from "@harishcode/util/record"
5+
import { Context, Effect } from "effect"
56

67
const TIMEOUT_MS = 30_000
8+
const MAX_REDIRECTS = 10
9+
const redirectStatuses = new Set([301, 302, 303, 307, 308])
710

811
type Init = {
912
readonly method?: string
1013
readonly headers?: Record<string, string> | Array<[string, string]>
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 response = await globalThis.fetch(input, {
18-
method: init.method,
19-
headers: init.headers,
20-
body: init.body,
21-
signal: AbortSignal.timeout(TIMEOUT_MS),
22-
})
23-
const bytes = await response.bytes()
24-
const headers = Object.fromEntries(response.headers)
25-
const text = () => new TextDecoder().decode(bytes)
26-
return {
27-
url: response.url,
28-
status: response.status,
29-
statusText: response.statusText,
30-
ok: response.ok,
31-
redirected: response.redirected,
32-
headers: {
33-
get: (name: string) => headers[name.toLowerCase()] ?? null,
34-
has: (name: string) => name.toLowerCase() in headers,
35-
entries: () => Object.entries(headers),
36-
},
37-
text: async () => text(),
38-
json: async () => JSON.parse(text()) as unknown,
39-
bytes: async () => bytes,
40-
}
17+
/** Per-request mediation for model-written fetch calls. */
18+
export type GuardService = {
19+
/** Interactive approval for the initial request URL. */
20+
readonly approve: (url: string, method: string) => Effect.Effect<void, Error>
21+
/** Non-interactive check for each redirect target; a denied target fails the request. */
22+
readonly check: (url: string) => Effect.Effect<void, Error>
4123
}
4224

25+
/**
26+
* Per-execution mediation for model-written fetch calls. The execute tool provides this from the calling
27+
* session's permission service; it is deliberately not a global, so no module import can install a bypass.
28+
*/
29+
export class Guard extends Context.Service<Guard, GuardService>()("@harishcode/CodeModeWeb/Guard") {}
30+
31+
type Fetched = {
32+
readonly response: globalThis.Response
33+
readonly url: string
34+
readonly redirected: boolean
35+
}
36+
37+
const hop = (url: string, init: Init) =>
38+
Effect.tryPromise({
39+
try: () =>
40+
globalThis.fetch(url, {
41+
method: init.method,
42+
headers: init.headers,
43+
body: init.body,
44+
redirect: "manual",
45+
signal: AbortSignal.timeout(TIMEOUT_MS),
46+
}),
47+
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
48+
})
49+
50+
// Redirects are followed here instead of in fetch so each new URL is checked against the permission rules first.
51+
const request = (url: string, init: Init, redirects: number): Effect.Effect<Fetched, Error, Guard> =>
52+
Effect.gen(function* () {
53+
const response = yield* hop(url, init)
54+
const location = response.headers.get("location")
55+
if (!redirectStatuses.has(response.status) || !location) return { response, url, redirected: redirects > 0 }
56+
if (redirects >= MAX_REDIRECTS)
57+
return yield* Effect.fail(new Error(`Too many redirects (more than ${MAX_REDIRECTS})`))
58+
const target = yield* Effect.try({
59+
try: () => new URL(location, url),
60+
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
61+
})
62+
if (target.protocol !== "http:" && target.protocol !== "https:")
63+
return yield* Effect.fail(new Error("Redirect target must use http:// or https://"))
64+
yield* (yield* Guard).check(target.href)
65+
// 301/302/303 downgrade to GET without a body; 307/308 preserve method and body.
66+
const method = (init.method ?? "GET").toUpperCase()
67+
const downgrade = response.status !== 307 && response.status !== 308 && method !== "GET" && method !== "HEAD"
68+
return yield* request(target.href, downgrade ? { headers: init.headers } : init, redirects + 1)
69+
})
70+
71+
const fetch = Extension.async((input: string | URL, init: Init = {}) =>
72+
Effect.gen(function* () {
73+
if (URL.parse(String(input))?.protocol === "file:")
74+
return yield* Effect.fail(new Error("fetch cannot be used for filesystem access."))
75+
const guard = yield* Guard
76+
const method = typeof init.method === "string" ? init.method.toUpperCase() : "GET"
77+
yield* guard.approve(String(input), method)
78+
const { response, url, redirected } = yield* request(String(input), init, 0)
79+
const bytes = yield* Effect.tryPromise({
80+
try: () => response.bytes(),
81+
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
82+
})
83+
const headers = Object.fromEntries(response.headers)
84+
const text = () => new TextDecoder().decode(bytes)
85+
return {
86+
url,
87+
status: response.status,
88+
statusText: response.statusText,
89+
ok: response.ok,
90+
redirected,
91+
headers: {
92+
get: (name: string) => headers[name.toLowerCase()] ?? null,
93+
has: (name: string) => name.toLowerCase() in headers,
94+
entries: () => Object.entries(headers),
95+
},
96+
text: async () => text(),
97+
json: async () => JSON.parse(text()) as unknown,
98+
bytes: async () => bytes,
99+
}
100+
}),
101+
)
102+
43103
export const extension = Extension.make({ name: "web", globals: { fetch } })
44104

45105
/** What to show for a fetch call: its method and URL. */

‎packages/core/src/tool.ts‎

Lines changed: 31 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,35 @@ 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+
// CodeMode fetch egress uses the webfetch permission action: interactive approval for the
279+
// initial URL, non-interactive checks for redirect targets. Captured like plugin tools do.
280+
(context) => ({
281+
approve: (url, method) =>
282+
permission.assert({
283+
action: "webfetch",
284+
resources: [url],
285+
save: ["*"],
286+
metadata: { url, method },
287+
sessionID: context.sessionID,
288+
agent: context.agent,
289+
source: { type: "tool", messageID: context.messageID, id: context.id },
290+
}),
291+
check: (url) =>
292+
permission.assertNotDenied({
293+
action: "webfetch",
294+
resources: [url],
295+
metadata: { url },
296+
sessionID: context.sessionID,
297+
agent: context.agent,
298+
source: { type: "tool", messageID: context.messageID, id: context.id },
299+
}),
300+
}),
275301
)
276302
: undefined
277303
const codeModeCatalog = !codeModeEnabled
@@ -362,5 +388,5 @@ function namespaceError(name: string) {
362388
export const node = makeLocationNode({
363389
service: Service,
364390
layer,
365-
deps: [PluginHooks.node, Image.node],
391+
deps: [PluginHooks.node, Image.node, Permission.node],
366392
})

‎packages/core/test/codemode.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@ import { describe, expect } from "bun:test"
22
import { AppNodeBuilder } from "@harishcode/core/effect/app-node-builder"
33
import { Location } from "@harishcode/core/location"
44
import { AbsolutePath } from "@harishcode/core/schema"
5+
import { Permission } from "@harishcode/core/permission"
56
import { Tool } from "@harishcode/core/tool"
7+
import { permissionLayer } from "./lib/permission"
68
import { Effect, Schema } from "effect"
79
import type { Info } from "@harishcode/schema/tool"
810
import { it } from "./lib/effect"
911

1012
const toolNode = AppNodeBuilder.build(Tool.node, [
1113
Location.node.replace(Location.boundNode({ directory: AbsolutePath.make("/project") })),
14+
Permission.node.replace(permissionLayer()),
1215
])
1316

1417
describe("CodeMode", () => {

‎packages/core/test/codemode/instructions.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ import { CodeModeInstructions } from "@harishcode/core/codemode/instructions"
44
import { AppNodeBuilder } from "@harishcode/core/effect/app-node-builder"
55
import { Location } from "@harishcode/core/location"
66
import { AbsolutePath } from "@harishcode/core/schema"
7+
import { Permission } from "@harishcode/core/permission"
78
import { Tool } from "@harishcode/core/tool"
9+
import { permissionLayer } from "../lib/permission"
810
import { Effect, Schema } from "effect"
911
import { it } from "../lib/effect"
1012
import { readInitial, readUpdate } from "../lib/instructions"
@@ -88,6 +90,7 @@ describe("CodeModeInstructions", () => {
8890
}
8991
const layer = AppNodeBuilder.build(Tool.node, [
9092
Location.node.replace(Location.boundNode({ directory: AbsolutePath.make("/project") })),
93+
Permission.node.replace(permissionLayer()),
9194
])
9295

9396
return Effect.gen(function* () {

0 commit comments

Comments
 (0)