fix(browser): revoke attach grants left behind by a server that was killed

The attach grant is a stored session rule, but its revoke runs only from the
plugin's finalizer. After SIGKILL, a crash or a stop timeout, the session kept
browser:* and skill:browser allows with no attachment behind them, so the next
server listed the browser tools and every call failed with
[browser.disconnected].

Each grant is now recorded in plugin storage with the server process that wrote
it (host and process ID) and its location, before the grant is written; a
successful revoke removes the record. When the plugin starts for a location, and
before it registers the browser RPC so no attach can race it, it revokes the
grants recorded for that location by a process that no longer runs.

Several server processes can share one database (a desktop's server and a
manual `opencode serve` both use opencode.db), so a sweep of every session in
the location could revoke another server's live grant. The sweep skips records
of a running process and of another host, which cannot be checked. Grants
written before this change have no record and are left alone; the next attach
and detach of their session removes them.

The startup sweep before RPC registration, its location scoping and ignoring
per-session failures come from #61639.

Fixes #61609

Co-authored-by: Chen Yufeiyang <fei76161@gmail.com>
This commit is contained in:
Luke Parker 2026-11-13 08:23:13 +10:00
parent 5778f64f3d
commit be740a5d01
2 changed files with 149 additions and 12 deletions

View file

@ -1,4 +1,5 @@
import { expect } from "bun:test"
import { hostname } from "os"
import path from "path"
import { Context, Deferred, Effect, Stream } from "effect"
import { Browser } from "@opencode/plugin-browser/rpc"
@ -9,20 +10,23 @@ import { Global } from "@opencode/util/global"
import { Agent } from "@opencode/core/agent"
import { Bus } from "@opencode/core/bus"
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 { 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 { BrowserConnection } from "../../plugin-browser/src/connection"
import { tempGlobalLayer } from "./fixture/global"
import { offlineModels } from "./fixture/models"
import { tmpdirScoped } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
const it = testEffect(
AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node, Session.node, LocationServiceMap.node]), [
AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node, KV.node, Session.node, LocationServiceMap.node]), [
Global.node.replace(tempGlobalLayer),
offlineModels,
]),
@ -77,6 +81,8 @@ const setup = (config: object) =>
)
if (!list) return yield* Effect.die(new Error("browser.tabs.list is not registered"))
return {
context,
ref,
session,
commands,
attach,
@ -174,3 +180,55 @@ it.live("a subagent whose agent denies the browser stays denied, even with a bro
expect(browser.commands.count).toBe(0)
}),
)
// No process has this ID: it is odd, so not a Windows process ID, and above Linux's and macOS's limits.
const exited = 4_194_305
const owner = (directory: string, pid: number, host = hostname()) => ({ host, pid, location: { directory } })
it.live("startup revokes a grant whose server no longer runs", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
const ref = Location.Ref.make({ directory: AbsolutePath.make(dir.path) })
const storage = PluginHost.storage(yield* KV.Service, "opencode.browser")
const sessionID = Session.ID.create()
// What a server killed while attached leaves behind: the grant and the record of the process that wrote it.
yield* storage.set(`grant:${sessionID}`, owner(ref.directory, exited))
const sessions = yield* Session.Service
yield* sessions.create({ id: sessionID, location: ref, permissions: [...grant] })
const locations = yield* LocationServiceMap.Service
yield* Plugin.awaitActivation.pipe(Effect.provideContext(yield* locations.contextEffect(ref).pipe(Effect.scoped)))
expect((yield* sessions.get(sessionID)).permissions).toEqual([])
expect(yield* storage.get(`grant:${sessionID}`)).toBeUndefined()
}),
)
it.live("another server's startup leaves a live attachment's grant in place", () =>
Effect.gen(function* () {
const browser = yield* setup({})
const sessions = yield* Session.Service
const storage = PluginHost.storage(yield* KV.Service, "opencode.browser")
const stale = yield* sessions.create({ location: browser.ref, permissions: [...grant] })
yield* storage.set(`grant:${stale.id}`, owner(browser.ref.directory, exited))
const remote = yield* sessions.create({ location: browser.ref, permissions: [...grant] })
yield* storage.set(`grant:${remote.id}`, owner(browser.ref.directory, exited, "other-host"))
// A second server for this location, sharing the database, starts and sweeps.
yield* BrowserConnection.reconcileStaleGrants({
session: {
get: (input) => sessions.get(input.sessionID),
update: (input) =>
sessions.setPermissions({ sessionID: input.sessionID, permissions: input.permissions ?? [] }),
},
storage,
location: browser.ref,
})
// The live grant is recorded with this process, which still runs.
expect(yield* storage.get(`grant:${browser.session.id}`)).toEqual(owner(browser.ref.directory, process.pid))
expect(yield* browser.permissions()).toEqual([...grant])
expect(yield* browser.permissions(stale.id)).toEqual([])
expect(yield* browser.permissions(remote.id)).toEqual([...grant])
expect((yield* browser.call()).output).toEqual({ tabs: [], focusedTabID: null })
}),
)

View file

@ -1,9 +1,11 @@
export * as BrowserConnection from "./connection.js"
import { hostname } from "node:os"
import type { Context } from "@opencode/plugin/effect/plugin"
import type { RpcRegistration } from "@opencode/plugin/effect/rpc"
import { Location } from "@opencode/schema/location"
import type { Permission } from "@opencode/schema/permission"
import type { Session } from "@opencode/schema/session"
import { Session } from "@opencode/schema/session"
import { Tool } from "@opencode/schema/tool"
import { Cause, Deferred, Duration, Effect, Exit, Option, Schema, Scope, Semaphore, Stream } from "effect"
import { BrowserMachine } from "./machine.js"
@ -17,8 +19,50 @@ type Attachment = {
export type Connection = Effect.Success<ReturnType<typeof make>>
/** The server process that wrote a session's grant, stored as `grant:<sessionID>` until its revoke succeeds. */
const GrantOwner = Schema.Struct({ host: Schema.String, pid: Schema.Number, location: Location.Ref })
const GRANT_PREFIX = "grant:"
/**
* A crash or SIGKILL skips the revokes, so a session keeps its grant with no attachment behind it. Revokes the grants
* this location's servers recorded, except those of a process that still runs: several servers can share one
* database, and another one's attachment may be live. Runs before the RPC registers, so no attach here can race it.
*/
export const reconcileStaleGrants = Effect.fn("BrowserConnection.reconcileStaleGrants")(function* (ctx: {
readonly session: Pick<Context["session"], "get" | "update">
readonly storage: Pick<Context["storage"], "scan" | "remove">
readonly location: Pick<Context["location"], "directory" | "workspaceID">
}) {
const revoke = (entry: { readonly key: string; readonly value: Schema.Json }) => {
const owner = Schema.decodeUnknownOption(GrantOwner)(entry.value)
if (
Option.isNone(owner) ||
owner.value.location.directory !== ctx.location.directory ||
owner.value.location.workspaceID !== ctx.location.workspaceID ||
running(owner.value)
)
return Effect.void
return writePermissions(ctx, Session.ID.make(entry.key.slice(GRANT_PREFIX.length)), false).pipe(
Effect.ignore,
Effect.andThen(ctx.storage.remove(entry.key)),
)
}
const page = (after?: string): Effect.Effect<void> =>
ctx.storage
.scan({ prefix: GRANT_PREFIX, after })
.pipe(
Effect.flatMap((result) =>
Effect.forEach(result.entries, revoke, { discard: true }).pipe(
Effect.andThen(result.next === undefined ? Effect.void : page(result.next)),
),
),
)
yield* page()
})
export const make = Effect.fn("BrowserConnection.make")(function* (
ctx: Pick<Context, "agent" | "rpc" | "session" | "location" | "event" | "permission">,
ctx: Pick<Context, "agent" | "rpc" | "session" | "location" | "event" | "permission" | "storage">,
) {
// Each agent's rules from config and its definition, which an attachment's grant must not override.
const configured = new Map<string, readonly Permission.Rule[]>()
@ -86,15 +130,24 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
if (effect.type === "warn") return Effect.logWarning(effect.message, effect.error)
return Deferred.done(drained, Exit.void).pipe(Effect.asVoid)
}
const writePermissions = (sessionID: Session.ID, allow: boolean) =>
ctx.session.get({ sessionID }).pipe(
Effect.flatMap((session) => {
const permissions = BrowserMachine.reconcileBrowserPermissions(session.permissions, allow)
return permissions ? ctx.session.update({ sessionID, permissions }) : Effect.void
}),
)
const owner: typeof GrantOwner.Encoded = {
host: hostname(),
pid: process.pid,
location: {
directory: ctx.location.directory,
...(ctx.location.workspaceID === undefined ? {} : { workspaceID: ctx.location.workspaceID }),
},
}
const syncPermissions = (effect: Extract<BrowserMachine.ConnectionEffect, { readonly type: "sync-permissions" }>) =>
writePermissions(effect.sessionID, effect.allow).pipe(
// The owner is recorded before the grant and forgotten after the revoke, so a stored grant always has one.
(effect.allow
? ctx.storage
.set(GRANT_PREFIX + effect.sessionID, owner)
.pipe(Effect.andThen(writePermissions(ctx, effect.sessionID, true)))
: writePermissions(ctx, effect.sessionID, false).pipe(
Effect.andThen(ctx.storage.remove(GRANT_PREFIX + effect.sessionID)),
)
).pipe(
Effect.timeoutOption(Duration.millis(BrowserMachine.PERMISSION_SYNC_TIMEOUT_MS)),
Effect.matchCauseEffect({
onSuccess: (done) =>
@ -122,6 +175,7 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
? Effect.succeed(attachment.tunnels)
: Effect.fail(new Error("Browser attachment is unavailable; its network connections were closed."))
}
yield* reconcileStaleGrants(ctx)
const rpc: RpcRegistration<typeof Browser.Definition> = yield* ctx.rpc
.register(Browser.Definition, {
attach: (input, call) =>
@ -226,7 +280,7 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
Effect.suspend(() =>
BrowserMachine.hasSession(machine.state, session.id)
? Effect.void
: writePermissions(session.id, false),
: writePermissions(ctx, session.id, false),
),
),
),
@ -330,3 +384,28 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
}),
}
})
function writePermissions(
ctx: { readonly session: Pick<Context["session"], "get" | "update"> },
sessionID: Session.ID,
allow: boolean,
) {
return ctx.session.get({ sessionID }).pipe(
Effect.flatMap((session) => {
const permissions = BrowserMachine.reconcileBrowserPermissions(session.permissions, allow)
return permissions ? ctx.session.update({ sessionID, permissions }) : Effect.void
}),
)
}
// A process on another host, such as another container on a shared volume, cannot be checked; its grants count as live.
// A reused process ID also counts as live, which only leaves a stale grant in place.
function running(owner: typeof GrantOwner.Type) {
if (owner.host !== hostname()) return true
try {
process.kill(owner.pid, 0)
return true
} catch (error) {
return error instanceof Error && "code" in error && error.code === "EPERM"
}
}