Skip to content
This repository was archived by the owner on Nov 7, 2026. It is now read-only.

Commit 17837a2

Browse files
authored
fix(core): apply webfetch URL rules to redirect targets (anomalyco#59748)
1 parent 2ed5743 commit 17837a2

6 files changed

Lines changed: 134 additions & 10 deletions

File tree

‎packages/core/src/permission.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ export interface Interface {
9191
readonly close: Effect.Effect<void>
9292
readonly ask: (input: AssertInput) => Effect.Effect<AskResult, SessionErrors.NotFoundError>
9393
readonly assert: (input: AssertInput) => Effect.Effect<void, Error | SessionErrors.NotFoundError>
94+
/** Fails only when the rules deny the request; never asks the user. */
95+
readonly assertNotDenied: (input: AssertInput) => Effect.Effect<void, BlockedError | SessionErrors.NotFoundError>
9496
readonly reply: (input: ReplyInput) => Effect.Effect<void, NotFoundError>
9597
readonly get: (id: ID) => Effect.Effect<Request | undefined>
9698
readonly forSession: (sessionID: SessionSchema.ID) => Effect.Effect<ReadonlyArray<Request>>
@@ -253,6 +255,17 @@ const layer = Layer.effect(
253255
}),
254256
)
255257

258+
const assertNotDenied = Effect.fn("Permission.assertNotDenied")(function* (input: AssertInput) {
259+
const result = yield* evaluateInput(input)
260+
if (result.effect !== "deny") return
261+
return yield* new BlockedError({
262+
rules: relevant(input, result.rules),
263+
permission: input.action,
264+
resources: input.resources,
265+
reason: result.message,
266+
})
267+
})
268+
256269
const reply = Effect.fn("Permission.reply")((input: ReplyInput) =>
257270
Effect.uninterruptible(
258271
Effect.gen(function* () {
@@ -327,7 +340,7 @@ const layer = Layer.effect(
327340
return Array.from(pending.values(), (item) => item.request).filter((request) => request.sessionID === sessionID)
328341
})
329342

330-
return Service.of({ ask, assert, reply, get, forSession, list, close })
343+
return Service.of({ ask, assert, assertNotDenied, reply, get, forSession, list, close })
331344
}),
332345
)
333346

‎packages/core/src/tool/plugin/webfetch.ts‎

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ export * as WebFetchTool from "./webfetch.js"
33
import type { Context } from "@opencode/plugin/effect/plugin"
44
import { ToolFailure } from "@opencode/ai/effect"
55
import { Duration, Effect, Schema } from "effect"
6-
import { HttpClient, type HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"
6+
import { FetchHttpClient, HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"
77
import { Parser } from "htmlparser2"
88
import { Mime } from "../../mime.js"
99
import { Permission } from "../../permission.js"
@@ -59,8 +59,8 @@ const headers = (format: Format, userAgent: string) => ({
5959
const openCodeUserAgent =
6060
"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OpenCode-User/1.0; +https://opencode.ai"
6161

62-
const isCloudflareChallenge = (error: HttpClientError.HttpClientError) => {
63-
if (error.reason._tag !== "StatusCodeError") return false
62+
const isCloudflareChallenge = (error: unknown) => {
63+
if (!HttpClientError.isHttpClientError(error) || error.reason._tag !== "StatusCodeError") return false
6464
const response = error.reason.response
6565
return response.status === 403 && response.headers["cf-mitigated"] === "challenge"
6666
}
@@ -72,8 +72,38 @@ const assertHttpUrl = (url: URL) => {
7272
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("URL must use http:// or https://")
7373
}
7474

75-
const execute = (http: HttpClient.HttpClient, url: string, format: Format, userAgent = openCodeUserAgent) =>
76-
http.execute(request(url, format, userAgent)).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk))
75+
export const MAX_REDIRECTS = 10
76+
const redirectStatuses = new Set([301, 302, 303, 307, 308])
77+
78+
// Follows redirects here instead of in fetch so each new URL is checked against the permission rules first.
79+
const execute = (
80+
http: HttpClient.HttpClient,
81+
check: (url: string) => Effect.Effect<void, Error>,
82+
url: string,
83+
format: Format,
84+
userAgent = openCodeUserAgent,
85+
redirects = 0,
86+
): Effect.Effect<HttpClientResponse.HttpClientResponse, Error> =>
87+
http.execute(request(url, format, userAgent)).pipe(
88+
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
89+
Effect.flatMap((response) => {
90+
const location = response.headers.location
91+
if (!redirectStatuses.has(response.status) || !location) return HttpClientResponse.filterStatusOk(response)
92+
if (redirects >= MAX_REDIRECTS) return Effect.fail(new Error(`Too many redirects (more than ${MAX_REDIRECTS})`))
93+
return Effect.gen(function* () {
94+
const next = yield* Effect.try({
95+
try: () => {
96+
const target = new URL(location, url)
97+
assertHttpUrl(target)
98+
return target.href
99+
},
100+
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
101+
})
102+
yield* check(next)
103+
return yield* execute(http, check, next, format, userAgent, redirects + 1)
104+
})
105+
}),
106+
)
77107

78108
const collectBody = (response: HttpClientResponse.HttpClientResponse) =>
79109
collectBoundedResponseBody(
@@ -124,8 +154,19 @@ export const Plugin = {
124154
})
125155

126156
const { body, contentType } = yield* Effect.gen(function* () {
127-
const response = yield* execute(http, input.url, input.format).pipe(
128-
Effect.catchIf(isCloudflareChallenge, () => execute(http, input.url, input.format, "opencode")),
157+
const check = (url: string) =>
158+
permission.assertNotDenied({
159+
action: name,
160+
resources: [url],
161+
metadata: { ...input, url },
162+
sessionID: context.sessionID,
163+
agent: context.agent,
164+
source: { type: "tool", messageID: context.messageID, id: context.id },
165+
})
166+
const response = yield* execute(http, check, input.url, input.format).pipe(
167+
Effect.catchIf(isCloudflareChallenge, () =>
168+
execute(http, check, input.url, input.format, "opencode"),
169+
),
129170
)
130171
const contentType = response.headers["content-type"] || ""
131172
const mime = mimeFrom(contentType)

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,17 @@ describe("Permission", () => {
148148
}),
149149
)
150150

151+
it.effect("checks for a deny without asking", () =>
152+
Effect.gen(function* () {
153+
yield* setup([])
154+
const service = yield* Permission.Service
155+
yield* service.assertNotDenied(assertion())
156+
expect(yield* service.list()).toEqual([])
157+
yield* setRules([{ action: "read", resource: "*", effect: "deny" }])
158+
expect(yield* service.assertNotDenied(assertion()).pipe(Effect.flip)).toBeInstanceOf(Permission.BlockedError)
159+
}),
160+
)
161+
151162
test("matches Windows rule resources against slash-normalized file access resources", () => {
152163
const rules: Permission.Ruleset = [
153164
{ action: "external_directory", resource: "C:\\Users\\x\\proj\\*", effect: "allow" },

‎packages/core/test/plugin/fixture.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ const permissionLayer = Layer.succeed(
7070
close: Effect.void,
7171
ask: (input) => Effect.succeed({ id: input.id ?? Permission.ID.create(), effect: "ask" }),
7272
assert: () => Effect.void,
73+
assertNotDenied: () => Effect.void,
7374
reply: () => Effect.void,
7475
get: () => Effect.succeed(undefined),
7576
forSession: () => Effect.succeed([]),

‎packages/core/test/plugin/permission-assert.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ const permission = Layer.succeed(
2626
if (input.action === "declined") return Effect.die(new Permission.DeclinedError())
2727
return Effect.void
2828
},
29+
assertNotDenied: () => Effect.void,
2930
reply: () => Effect.void,
3031
get: () => Effect.succeed(undefined),
3132
forSession: () => Effect.succeed([]),

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

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ const webFetchUserAgent =
2727
"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OpenCode-User/1.0; +https://opencode.ai"
2828
const requests: Array<{ readonly url: string; readonly headers: Record<string, string> }> = []
2929
const assertions: Permission.AssertInput[] = []
30+
const checks: Permission.AssertInput[] = []
31+
const denied = new Set<string>()
3032
let respond = (_request: HttpClientRequest.HttpClientRequest) =>
3133
Effect.succeed(new Response("hello", { headers: { "content-type": "text/plain" } }))
3234

@@ -39,7 +41,19 @@ const http = Layer.succeed(
3941
),
4042
),
4143
)
42-
const permission = permissionLayer({ assert: (input) => Effect.sync(() => assertions.push(input)) })
44+
const permission = permissionLayer({
45+
assert: (input) => Effect.sync(() => assertions.push(input)),
46+
assertNotDenied: (input) =>
47+
Effect.sync(() => checks.push(input)).pipe(
48+
Effect.andThen(
49+
input.resources.some((resource) => denied.has(resource))
50+
? Effect.fail(
51+
new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources }),
52+
)
53+
: Effect.void,
54+
),
55+
),
56+
})
4357
const toolLayer = (replacements: LayerNode.Replacements = []) =>
4458
AppNodeBuilder.build(LayerNode.group([Tool.node, webFetchToolNode]), [
4559
Permission.node.replace(permission),
@@ -52,6 +66,8 @@ const live = testEffect(toolLayer())
5266
const reset = () => {
5367
requests.length = 0
5468
assertions.length = 0
69+
checks.length = 0
70+
denied.clear()
5571
respond = () => Effect.succeed(new Response("hello", { headers: { "content-type": "text/plain" } }))
5672
}
5773

@@ -456,7 +472,7 @@ describe("WebFetchTool registration", () => {
456472
}),
457473
)
458474

459-
live.effect("follows redirects while approving only the requested URL", () => {
475+
live.effect("follows redirects, checking each target against the rules without asking", () => {
460476
const received: Array<Record<string, string | null>> = []
461477
return Effect.acquireUseRelease(
462478
Effect.sync(() =>
@@ -488,6 +504,8 @@ describe("WebFetchTool registration", () => {
488504
expect(assertions).toMatchObject([
489505
{ sessionID, action: "webfetch", resources: [url], save: ["*"], metadata: { url, format: "text" } },
490506
])
507+
const target = new URL("/target", server.url).toString()
508+
expect(checks).toMatchObject([{ sessionID, action: "webfetch", resources: [target] }])
491509
expect(received).toEqual(
492510
Array.from({ length: 2 }, () => ({
493511
accept: "text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1",
@@ -501,6 +519,45 @@ describe("WebFetchTool registration", () => {
501519
)
502520
})
503521

522+
it.effect("stops at a redirect target the rules deny", () =>
523+
Effect.gen(function* () {
524+
reset()
525+
const registry = yield* Tool.Service
526+
const url = "https://example.com/start"
527+
const target = "http://169.254.169.254/latest/meta-data"
528+
denied.add(target)
529+
respond = () => Effect.succeed(new Response("", { status: 302, headers: { location: target } }))
530+
531+
expect(yield* executeTool(registry, call({ url, format: "text" }))).toMatchObject({
532+
status: "error",
533+
error: { message: "Permission denied: webfetch" },
534+
})
535+
expect(checks.map((check) => check.resources)).toEqual([[target]])
536+
expect(requests.map((request) => request.url)).toEqual([url])
537+
}),
538+
)
539+
540+
it.effect("rejects redirects to non-HTTP schemes and endless redirect chains", () =>
541+
Effect.gen(function* () {
542+
reset()
543+
const registry = yield* Tool.Service
544+
respond = () => Effect.succeed(new Response("", { status: 301, headers: { location: "file:///etc/passwd" } }))
545+
expect(yield* executeTool(registry, call({ url: "https://example.com/a", format: "text" }))).toMatchObject({
546+
status: "error",
547+
error: { message: "URL must use http:// or https://" },
548+
})
549+
expect(checks).toEqual([])
550+
551+
reset()
552+
respond = (request) => Effect.succeed(new Response("", { status: 307, headers: { location: `${request.url}x` } }))
553+
expect(yield* executeTool(registry, call({ url: "https://example.com/a", format: "text" }))).toMatchObject({
554+
status: "error",
555+
error: { message: `Too many redirects (more than ${WebFetchTool.MAX_REDIRECTS})` },
556+
})
557+
expect(requests).toHaveLength(WebFetchTool.MAX_REDIRECTS + 1)
558+
}),
559+
)
560+
504561
it.effect("rejects non-HTTP schemes before permission or transport", () =>
505562
Effect.gen(function* () {
506563
reset()

0 commit comments

Comments
 (0)