mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(browser): honour per-operation browser denies and configured asks over the grant
The deny check only refused a call when the last rule for `browser` denied every operation. A deny on one operation (for example `browser` on `tabs.open` or `files.*`) and a configured `ask` still went through: the permission check evaluates the session's `browser:* allow` grant after them, so the grant won and answered silently. The plugin now registers a `permission.evaluate` hook for the `browser` action. It picks the rule for the call's operation from the agent's configured rules and the session's rules without the grant, the way core's Permission.evaluate picks it (last match on action and resource patterns). A deny refuses the call with `[browser.denied]`, naming the operation when the deny is for one operation. An ask makes the permission check prompt as it would without the grant. No matching rule leaves the call allowed by the grant with no prompt. Later hooks such as tool.use policies still apply. The matcher copies core's Wildcard.match; a core test checks both pick the same rule. Tool listing is unchanged.
This commit is contained in:
parent
be740a5d01
commit
fbd7c7ed93
4 changed files with 188 additions and 51 deletions
|
|
@ -1,7 +1,7 @@
|
|||
import { expect } from "bun:test"
|
||||
import { expect, test } from "bun:test"
|
||||
import { hostname } from "os"
|
||||
import path from "path"
|
||||
import { Context, Deferred, Effect, Stream } from "effect"
|
||||
import { Context, Deferred, Effect, Fiber, Schedule, Stream } from "effect"
|
||||
import { Browser } from "@opencode/plugin-browser/rpc"
|
||||
import { SessionMessage } from "@opencode/schema/session-message"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
|
|
@ -13,13 +13,16 @@ import { Database } from "@opencode/core/database/database"
|
|||
import { KV } from "@opencode/core/kv"
|
||||
import { Location } from "@opencode/core/location"
|
||||
import { LocationServiceMap } from "@opencode/core/location-services"
|
||||
import { Permission } from "@opencode/core/permission"
|
||||
import { Plugin } from "@opencode/core/plugin"
|
||||
import { PluginHost } from "@opencode/core/plugin/host"
|
||||
import { Rpc } from "@opencode/core/rpc"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
import { Wildcard } from "@opencode/core/util/wildcard"
|
||||
import { BrowserConnection } from "../../plugin-browser/src/connection"
|
||||
import { BrowserMachine } from "../../plugin-browser/src/machine"
|
||||
import { tempGlobalLayer } from "./fixture/global"
|
||||
import { offlineModels } from "./fixture/models"
|
||||
import { tmpdirScoped } from "./fixture/tmpdir"
|
||||
|
|
@ -37,6 +40,16 @@ const grant = [
|
|||
{ action: "skill", resource: "browser", effect: "allow" },
|
||||
] as const
|
||||
|
||||
const tab = {
|
||||
id: Browser.TabID.make(`tab_${crypto.randomUUID()}`),
|
||||
url: "https://example.com/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
generation: 1,
|
||||
}
|
||||
|
||||
// A location with `config` as its opencode.json and one session, plus a stand-in desktop that attaches to that
|
||||
// session and answers every browser command with an empty tab list.
|
||||
const setup = (config: object) =>
|
||||
|
|
@ -74,31 +87,36 @@ const setup = (config: object) =>
|
|||
attachments.set(connectionID, { sessionID, attached })
|
||||
yield* rpc.attach({ sessionID, connectionID, version: 4 }).pipe(Effect.forkScoped)
|
||||
yield* Deferred.await(attached).pipe(Effect.timeout("10 seconds"))
|
||||
// One open tab, so operations that target a tab get past tab selection to the permission check.
|
||||
yield* rpc.state({ sessionID, connectionID, state: { tabs: [tab], focusedTabID: tab.id } })
|
||||
})
|
||||
yield* attach(session.id)
|
||||
const list = (yield* Context.get(context, Tool.Service).list()).find(
|
||||
(tool) => tool.name === "list" && tool.options?.namespace === "browser.tabs",
|
||||
)
|
||||
if (!list) return yield* Effect.die(new Error("browser.tabs.list is not registered"))
|
||||
const tools = yield* Context.get(context, Tool.Service).list()
|
||||
// Runs browser.<operation> as `agent` would, through the plugin's executor and the real permission service.
|
||||
const run = (operation: string, input: object, agent = "build", sessionID = session.id) => {
|
||||
const separator = operation.lastIndexOf(".")
|
||||
const namespace = separator < 0 ? "browser" : `browser.${operation.slice(0, separator)}`
|
||||
const tool = tools.find(
|
||||
(tool) => tool.name === operation.slice(separator + 1) && tool.options?.namespace === namespace,
|
||||
)
|
||||
if (!tool) return Effect.die(new Error(`browser.${operation} is not registered`))
|
||||
return tool.execute(input, {
|
||||
sessionID,
|
||||
agent: Agent.ID.make(agent),
|
||||
messageID: SessionMessage.ID.create(),
|
||||
id: Tool.CallID.make(`call_${crypto.randomUUID()}`),
|
||||
progress: () => Effect.void,
|
||||
})
|
||||
}
|
||||
return {
|
||||
context,
|
||||
ref,
|
||||
session,
|
||||
commands,
|
||||
attach,
|
||||
run,
|
||||
permissions: (sessionID = session.id) => Effect.map(sessions.get(sessionID), (info) => info.permissions ?? []),
|
||||
// Runs browser.tabs.list as `agent` would, through the plugin's executor and the real permission service.
|
||||
call: (agent = "build", sessionID = session.id) =>
|
||||
list.execute(
|
||||
{},
|
||||
{
|
||||
sessionID,
|
||||
agent: Agent.ID.make(agent),
|
||||
messageID: SessionMessage.ID.create(),
|
||||
id: Tool.CallID.make(`call_${crypto.randomUUID()}`),
|
||||
progress: () => Effect.void,
|
||||
},
|
||||
),
|
||||
call: (agent = "build", sessionID = session.id) => run("tabs.list", {}, agent, sessionID),
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -232,3 +250,87 @@ it.live("another server's startup leaves a live attachment's grant in place", ()
|
|||
expect((yield* browser.call()).output).toEqual({ tabs: [], focusedTabID: null })
|
||||
}),
|
||||
)
|
||||
|
||||
const rule = (resource: string, effect: "allow" | "deny" | "ask", action = "browser") => ({ action, resource, effect })
|
||||
|
||||
it.live("a deny on one browser operation refuses that operation and still allows the others", () =>
|
||||
Effect.gen(function* () {
|
||||
const browser = yield* setup({ permissions: [rule("tabs.open", "deny")] })
|
||||
expect((yield* browser.run("tabs.open", {}).pipe(Effect.flip)).message).toStartWith(
|
||||
"[browser.denied] browser.tabs.open",
|
||||
)
|
||||
expect(browser.commands.count).toBe(0)
|
||||
expect((yield* browser.call()).output).toEqual({ tabs: [], focusedTabID: null })
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("a wildcard resource pattern in a browser deny is honoured", () =>
|
||||
Effect.gen(function* () {
|
||||
const browser = yield* setup({ permissions: [rule("files.*", "deny")] })
|
||||
expect((yield* browser.run("files.list", { tabID: tab.id }).pipe(Effect.flip)).message).toStartWith(
|
||||
"[browser.denied] browser.files.list",
|
||||
)
|
||||
expect(browser.commands.count).toBe(0)
|
||||
expect((yield* browser.call()).output).toEqual({ tabs: [], focusedTabID: null })
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("an allow for one operation after a whole-browser deny wins, as the last matching rule", () =>
|
||||
Effect.gen(function* () {
|
||||
const browser = yield* setup({ permissions: [rule("*", "deny"), rule("tabs.list", "allow")] })
|
||||
expect((yield* browser.call()).output).toEqual({ tabs: [], focusedTabID: null })
|
||||
expect((yield* browser.run("tabs.open", {}).pipe(Effect.flip)).message).toStartWith("[browser.denied]")
|
||||
expect(browser.commands.count).toBe(1)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("a configured browser ask prompts for the call instead of being answered by the grant", () =>
|
||||
Effect.gen(function* () {
|
||||
const browser = yield* setup({ permissions: [rule("tabs.list", "ask")] })
|
||||
const permissions = Context.get(browser.context, Permission.Service)
|
||||
const call = yield* browser.call().pipe(Effect.forkScoped)
|
||||
const request = yield* permissions.list().pipe(
|
||||
Effect.flatMap((requests) => (requests[0] ? Effect.succeed(requests[0]) : Effect.fail("not asked yet"))),
|
||||
Effect.retry(Schedule.spaced("10 millis")),
|
||||
Effect.timeout("5 seconds"),
|
||||
)
|
||||
expect(request).toMatchObject({ sessionID: browser.session.id, action: "browser", resources: ["tabs.list"] })
|
||||
expect(browser.commands.count).toBe(0)
|
||||
|
||||
yield* permissions.reply({ requestID: request.id, reply: "once" })
|
||||
expect((yield* Fiber.join(call)).output).toEqual({ tabs: [], focusedTabID: null })
|
||||
expect(browser.commands.count).toBe(1)
|
||||
}),
|
||||
)
|
||||
|
||||
test("the plugin picks the same browser rule as core's permission evaluation", () => {
|
||||
const patterns = [
|
||||
"*",
|
||||
"browser",
|
||||
"brow*",
|
||||
"b?owser",
|
||||
"browser.*",
|
||||
"Browser",
|
||||
"files.*",
|
||||
"tabs.list",
|
||||
"b.owser",
|
||||
"browser *",
|
||||
"*.list",
|
||||
"a\\b",
|
||||
]
|
||||
const inputs = ["browser", "tabs.list", "files.upload", "evaluate", "browser.x", "a/b"]
|
||||
for (const input of inputs)
|
||||
for (const pattern of patterns) expect(BrowserMachine.match(input, pattern)).toBe(Wildcard.match(input, pattern))
|
||||
// Each pattern once as an action (any resource) and once as a resource of `browser`, with varying effects.
|
||||
const rules = patterns.flatMap((pattern, index) => [
|
||||
rule("*", index % 3 === 0 ? "deny" : index % 3 === 1 ? "allow" : "ask", pattern),
|
||||
rule(pattern, index % 2 === 0 ? "ask" : "deny"),
|
||||
])
|
||||
for (const operation of inputs)
|
||||
for (const end of rules.keys()) {
|
||||
const slice = rules.slice(0, end + 1)
|
||||
// Core returns the rule it picked, or a fresh default `ask` rule when none matches.
|
||||
const picked = Permission.evaluate("browser", operation, slice)
|
||||
expect(BrowserMachine.selectBrowserRule(slice, operation)).toBe(slice.includes(picked) ? picked : undefined)
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -74,6 +74,47 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
|
|||
agent.permissions.push(...BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "deny" as const })))
|
||||
})
|
||||
})
|
||||
// The attachment's grant is a session rule, evaluated after every agent rule, so core resolves every browser call to
|
||||
// allow. The rules from config, the agent's definition and the session itself decide instead: a deny refuses the
|
||||
// call, and an ask makes the permission check prompt as it would without the grant. No matching rule leaves it
|
||||
// allowed.
|
||||
yield* ctx.permission.hook("evaluate", (event) =>
|
||||
event.action !== "browser" || event.effect === "deny"
|
||||
? Effect.void
|
||||
: ctx.session.get({ sessionID: event.sessionID }).pipe(
|
||||
Effect.map((session) => {
|
||||
const rules = [
|
||||
...(configured.get(event.agent ?? session.agent ?? "") ?? []),
|
||||
...(session.permissions ?? []).filter((rule) => !BrowserMachine.isGrant(rule)),
|
||||
]
|
||||
const decided = event.resources.map((operation) => ({
|
||||
operation,
|
||||
rule: BrowserMachine.selectBrowserRule(rules, operation),
|
||||
}))
|
||||
const denied = decided.find((item) => item.rule?.effect === "deny")
|
||||
if (denied) {
|
||||
event.effect = "deny"
|
||||
event.message =
|
||||
denied.rule?.resource === "*"
|
||||
? "[browser.denied] Browser tools are denied for this agent by configuration; no action ran. Do not retry browser tools."
|
||||
: `[browser.denied] browser.${denied.operation} is denied for this agent by configuration; no action ran. Do not retry it.`
|
||||
return
|
||||
}
|
||||
if (decided.some((item) => item.rule?.effect === "ask")) event.effect = "ask"
|
||||
}),
|
||||
// Without the rules, the grant must not decide alone.
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Browser permission evaluation failed", cause).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
event.effect = "deny"
|
||||
event.message = "Browser permissions could not be read; no action ran."
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
// Permission syncs run here. Registered first, so it closes last: after disposal has drained the revokes.
|
||||
const work = yield* Scope.make()
|
||||
yield* Effect.addFinalizer((exit) => Scope.close(work, exit))
|
||||
|
|
@ -333,23 +374,10 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
|
|||
|
||||
return {
|
||||
/**
|
||||
* The attachment's grant is a session rule, evaluated after every agent rule, so it would override a `browser` deny
|
||||
* from config or the agent's definition. Such a deny, or one in the session's own rules, refuses the call. The
|
||||
* permission check then runs `permission.evaluate` hooks such as `tool.use` policies.
|
||||
* The permission check for one call, with the operation as its resource. Its `permission.evaluate` hooks decide it:
|
||||
* this plugin's (configured denies and asks win over the grant) and others such as `tool.use` policies.
|
||||
*/
|
||||
authorize: Effect.fn("BrowserConnection.authorize")(function* (tool: Tool.Context, operation: Browser.Method) {
|
||||
const session = yield* ctx.session
|
||||
.get({ sessionID: tool.sessionID })
|
||||
.pipe(Effect.mapError((error) => new Tool.Error({ message: `Session not found: ${tool.sessionID}`, error })))
|
||||
const rules = [
|
||||
...(configured.get(tool.agent) ?? []),
|
||||
...(session.permissions ?? []).filter((rule) => !BrowserMachine.isGrant(rule)),
|
||||
]
|
||||
if (BrowserMachine.deniesBrowser(rules))
|
||||
return yield* new Tool.Error({
|
||||
message:
|
||||
"[browser.denied] Browser tools are denied for this agent by configuration; no action ran. Do not retry browser tools.",
|
||||
})
|
||||
yield* ctx.permission.assert({
|
||||
sessionID: tool.sessionID,
|
||||
agent: tool.agent,
|
||||
|
|
|
|||
|
|
@ -570,21 +570,23 @@ export function isGrant(rule: Permission.Rule) {
|
|||
)
|
||||
}
|
||||
|
||||
/** Whether the rules deny every browser tool, decided as core's tool filter does: the last rule for `browser` wins. */
|
||||
export function deniesBrowser(rules: readonly Permission.Rule[]) {
|
||||
const rule = rules.findLast((rule) => matchesBrowser(rule.action))
|
||||
return rule?.resource === "*" && rule.effect === "deny"
|
||||
/**
|
||||
* The rule that decides `browser` on `operation`, picked as core's `Permission.evaluate` picks it: the last rule whose
|
||||
* action and resource patterns both match. Undefined when none matches.
|
||||
*/
|
||||
export function selectBrowserRule(rules: readonly Permission.Rule[], operation: string) {
|
||||
return rules.findLast((rule) => match("browser", rule.action) && match(operation, rule.resource))
|
||||
}
|
||||
|
||||
// Core's `Wildcard.match("browser", pattern)`, which plugins cannot import.
|
||||
function matchesBrowser(pattern: string) {
|
||||
/** Core's `Wildcard.match`, which plugins cannot import. A core test checks the two agree. */
|
||||
export function match(input: string, pattern: string) {
|
||||
const escaped = pattern
|
||||
.replaceAll("\\", "/")
|
||||
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
||||
.replace(/\*/g, ".*")
|
||||
.replace(/\?/g, ".")
|
||||
const source = escaped.endsWith(" .*") ? escaped.slice(0, -3) + "( .*)?" : escaped
|
||||
return new RegExp("^" + source + "$", process.platform === "win32" ? "si" : "s").test("browser")
|
||||
return new RegExp("^" + source + "$", process.platform === "win32" ? "si" : "s").test(input.replaceAll("\\", "/"))
|
||||
}
|
||||
|
||||
export function isConnectionDisposed(state: ConnectionState) {
|
||||
|
|
|
|||
|
|
@ -276,24 +276,29 @@ describe("reconcileBrowserPermissions", () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe("deniesBrowser", () => {
|
||||
describe("selectBrowserRule", () => {
|
||||
const rule = (action: string, effect: "allow" | "deny" | "ask", resource = "*") => ({ action, resource, effect })
|
||||
const effect = (rules: ReturnType<typeof rule>[], operation: string) =>
|
||||
BrowserMachine.selectBrowserRule(rules, operation)?.effect
|
||||
|
||||
test("the last rule whose action matches browser decides, as core's tool filter does", () => {
|
||||
expect(BrowserMachine.deniesBrowser([rule("browser", "deny")])).toBe(true)
|
||||
expect(BrowserMachine.deniesBrowser([rule("*", "deny"), rule("read", "allow")])).toBe(true)
|
||||
expect(BrowserMachine.deniesBrowser([rule("brow*", "deny")])).toBe(true)
|
||||
expect(BrowserMachine.deniesBrowser([rule("browser", "deny"), rule("*", "ask")])).toBe(false)
|
||||
expect(BrowserMachine.deniesBrowser([rule("*", "deny"), rule("browser", "allow")])).toBe(false)
|
||||
expect(BrowserMachine.deniesBrowser([])).toBe(false)
|
||||
test("the last rule whose action and resource match decides", () => {
|
||||
expect(effect([rule("browser", "deny")], "tabs.list")).toBe("deny")
|
||||
expect(effect([rule("*", "deny"), rule("read", "allow")], "tabs.list")).toBe("deny")
|
||||
expect(effect([rule("brow*", "deny")], "tabs.list")).toBe("deny")
|
||||
expect(effect([rule("browser", "deny"), rule("*", "ask")], "tabs.list")).toBe("ask")
|
||||
expect(effect([rule("browser", "deny"), rule("browser", "allow", "tabs.list")], "tabs.list")).toBe("allow")
|
||||
expect(effect([rule("browser", "deny"), rule("browser", "allow", "tabs.list")], "evaluate")).toBe("deny")
|
||||
expect(effect([], "tabs.list")).toBeUndefined()
|
||||
})
|
||||
|
||||
test("a deny limited to some resources does not deny the browser", () => {
|
||||
expect(BrowserMachine.deniesBrowser([rule("browser", "deny", "https://bank.example/*")])).toBe(false)
|
||||
test("resource patterns name operations", () => {
|
||||
expect(effect([rule("browser", "deny", "files.*")], "files.upload")).toBe("deny")
|
||||
expect(effect([rule("browser", "deny", "files.*")], "tabs.list")).toBeUndefined()
|
||||
expect(effect([rule("browser", "deny", "https://bank.example/*")], "tabs.list")).toBeUndefined()
|
||||
})
|
||||
|
||||
test("other actions and literal regex characters do not match", () => {
|
||||
expect(BrowserMachine.deniesBrowser([rule("browsers", "deny"), rule("b.owser", "deny")])).toBe(false)
|
||||
expect(effect([rule("browsers", "deny"), rule("b.owser", "deny")], "tabs.list")).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue