diff --git a/packages/core/test/browser-permission.test.ts b/packages/core/test/browser-permission.test.ts index 409610e3b77..d40fe37ba0b 100644 --- a/packages/core/test/browser-permission.test.ts +++ b/packages/core/test/browser-permission.test.ts @@ -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 }) + }), +) diff --git a/packages/plugin-browser/src/connection.ts b/packages/plugin-browser/src/connection.ts index d6307b11c30..8c7f73234e0 100644 --- a/packages/plugin-browser/src/connection.ts +++ b/packages/plugin-browser/src/connection.ts @@ -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> +/** The server process that wrote a session's grant, stored as `grant:` 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 + readonly storage: Pick + readonly location: Pick +}) { + 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 => + 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, + ctx: Pick, ) { // Each agent's rules from config and its definition, which an attachment's grant must not override. const configured = new Map() @@ -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) => - 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 = 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 }, + 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" + } +}