Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/core/src/file-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export function externalDirectoryRequest(targets: readonly Target[]) {
export const key = (target: { readonly absolute: string; readonly environment: { readonly id: Environment.ID } }) =>
`${target.environment.id.length}:${target.environment.id}:${target.absolute}`

/** The rule "always" saves for a file action: every file on the target's machine, which only that machine's rules allow. */
/** The rule "always" saves for a file action: every file on the target's machine. */
export const always = (target: Target) => (target.machine ? `${target.machine}:*` : "*")

export type Invocation = Pick<Tool.Context, "sessionID" | "agent" | "messageID" | "id">
Expand Down
11 changes: 1 addition & 10 deletions packages/core/src/permission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { Agent } from "./agent.js"
import { SessionErrors } from "./session/error.js"
import { SessionSchema } from "./session/schema.js"
import { SessionStore } from "./session/store.js"
import { MachinePath } from "./machine/path.js"
import { Wildcard } from "./util/wildcard.js"
import { PermissionSaved } from "./permission/saved.js"
import { PluginHooks } from "./plugin/hooks.js"
Expand Down Expand Up @@ -102,19 +101,11 @@ export function ignoresCase(action: string) {

export function evaluate(action: string, resource: string, ...rulesets: Permission.Ruleset[]): Permission.Rule {
const ignoreCase = ignoresCase(action)
// Only a rule that names a machine allows that machine's files, so `*` saved on this computer never reaches another.
// Denies and asks still apply everywhere.
const machine = pathActions.some((item) => item === action) ? MachinePath.parse(resource)?.machine : undefined
return (
rulesets
.flat()
.findLast(
(rule) =>
Wildcard.match(action, rule.action) &&
(machine === undefined ||
rule.effect !== "allow" ||
Wildcard.match(rule.resource.slice(0, machine.length + 1), `${machine}:`, ignoreCase)) &&
Wildcard.match(resource, rule.resource, ignoreCase),
(rule) => Wildcard.match(action, rule.action) && Wildcard.match(resource, rule.resource, ignoreCase),
) ?? {
action,
resource: "*",
Expand Down
102 changes: 93 additions & 9 deletions packages/core/test/machine-path.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import fs from "fs/promises"
import path from "path"
import { describe, expect, test } from "bun:test"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { Agent } from "@opencode/core/agent"
import { Bus } from "@opencode/core/bus"
import { Database } from "@opencode/core/database/database"
import { AppProcess } from "@opencode/util/process"
import { Config } from "@opencode/core/config"
import { Environment } from "@opencode/core/environment/index"
Expand All @@ -20,9 +23,12 @@ import { Machines } from "@opencode/core/machine/machines"
import { Permission } from "@opencode/core/permission"
import { PersistentPty } from "@opencode/core/persistent-pty"
import { PluginHooks } from "@opencode/core/plugin/hooks"
import { Project } from "@opencode/core/project"
import { ProjectTable } from "@opencode/core/project/sql"
import { Ripgrep } from "@opencode/core/ripgrep"
import { AbsolutePath } from "@opencode/core/schema"
import { Session } from "@opencode/core/session"
import { SessionTable } from "@opencode/core/session/sql"
import { SessionInstructions } from "@opencode/core/session/instructions"
import { Shell } from "@opencode/core/shell"
import { ShellSelect } from "@opencode/core/shell/select"
Expand Down Expand Up @@ -107,9 +113,13 @@ interface Fixture {
readonly processes: ChildProcess.Command[]
}

const graph = (fixture: Fixture) =>
const graph = (fixture: Fixture, realPermissions = false) =>
AppNodeBuilder.build(
LayerNode.group([
Agent.node,
Bus.node,
Database.node,
Permission.node,
Tool.node,
toolPlugins,
FileAccess.node,
Expand Down Expand Up @@ -143,11 +153,15 @@ const graph = (fixture: Fixture) =>
}),
).pipe(Layer.provide(LayerNode.compile(AppProcess.node))),
),
Permission.node.replace(
permissionLayer({
assert: (input) => Effect.sync(() => void fixture.assertions.push(input)),
}),
),
...(realPermissions
? []
: [
Permission.node.replace(
permissionLayer({
assert: (input) => Effect.sync(() => void fixture.assertions.push(input)),
}),
),
]),
PersistentPty.node.replace(disabledPersistentPtyLayer),
Session.node.replace(Layer.mock(Session.Service, { revert })),
Config.node.replace(Config.testLayer()),
Expand Down Expand Up @@ -178,6 +192,69 @@ const slash = (value: string) => value.replaceAll("\\", "/")
const on = testEffect(Layer.succeed(Flag.Overrides, "machines"))
const off = testEffect(Layer.succeed(Flag.Overrides, "-machines"))

on.live("reads, writes and runs commands on a paired machine without requesting approval under default rules", () =>
withTempDir((tmp) =>
Effect.gen(function* () {
const database = yield* Database.Service
yield* database.db
.insert(ProjectTable)
.values({ id: Project.ID.global, worktree: AbsolutePath.make(tmp.path), sandboxes: [] })
.run()
.pipe(Effect.orDie)
yield* database.db
.insert(SessionTable)
.values({
id: sessionID,
project_id: Project.ID.global,
directory: tmp.path,
slug: "test",
version: "test",
agent: toolIdentity.agent,
})
.run()
.pipe(Effect.orDie)
const agents = yield* Agent.Service
yield* agents.transform((editor) => editor.update(toolIdentity.agent, () => {}))
const bus = yield* Bus.Service
const prompts: string[] = []
const unsubscribe = yield* bus.listen((event) =>
Effect.sync(() => {
if (event.type === Permission.Event.Asked.type) prompts.push(event.type)
}),
)
yield* Effect.addFinalizer(() => unsubscribe)
const machines = yield* Machines.Service
const { id, worker } = yield* connected(machines, "gpu")
const machine = yield* machines.get(id)
yield* machine.files.mkdir("/work")
yield* machine.files.write("/work/a.txt", bytes("before\n"))
const registry = yield* Tool.Service
expect(yield* executeTool(registry, call("read", { path: "gpu:/work/a.txt" }))).toMatchObject({
status: "completed",
output: { type: "text", content: "before\n" },
})
expect(
yield* executeTool(registry, call("write", { path: "gpu:/work/a.txt", content: "after\n" })),
).toMatchObject({ status: "completed" })
expect(text((yield* machine.files.read("/work/a.txt")).bytes)).toBe("after\n")
const running = yield* Effect.forkChild(
executeTool(registry, call("shell", { command: "pwd", workdir: "gpu:/work" })),
{ startImmediately: true },
)
while (worker.runs.length === 0) yield* Effect.yieldNow
yield* worker.runs[0].print("/work\n")
yield* worker.runs[0].exit(0)
expect(yield* Fiber.join(running)).toMatchObject({
status: "completed",
output: { exitCode: 0, output: "/work\n" },
})
const permission = yield* Permission.Service
expect(yield* permission.list()).toEqual([])
expect(prompts).toEqual([])
}).pipe(Effect.provide(graph(fixture(tmp.path), true))),
),
)

describe("MachinePath", () => {
const machinePaths: ReadonlyArray<readonly [string, { machine: string; path: string } | undefined]> = [
["gpu:/work/train.py", { machine: "gpu", path: "/work/train.py" }],
Expand Down Expand Up @@ -390,7 +467,7 @@ on.effect("reads a recovered filename on the machine, not this server's disk", (
}),
)

on.effect("uses a rule for the machine's path, never one for the same path without the machine", () =>
on.effect("matches machine-qualified paths and keeps machine-specific saved rules", () =>
withTempDir((tmp) => {
const tools = fixture(tmp.path)
return Effect.gen(function* () {
Expand All @@ -408,7 +485,7 @@ on.effect("uses a rule for the machine's path, never one for the same path witho
const allow = (resource: string) => [{ action: "read" as const, resource, effect: "allow" as const }]
expect(Permission.evaluate("read", "gpu:/work/a.txt", allow("gpu:*")).effect).toBe("allow")
expect(Permission.evaluate("read", "cpu:/work/a.txt", allow("gpu:*")).effect).toBe("ask")
expect(Permission.evaluate("read", "gpu:/work/a.txt", allow("*")).effect).toBe("ask")
expect(Permission.evaluate("read", "gpu:/work/a.txt", allow("*")).effect).toBe("allow")
expect(Permission.evaluate("read", "gpu:/work/a.txt", allow("/work/*")).effect).toBe("ask")
expect(Permission.evaluate("read", "gpu:/work/a.txt", allow("gpu:/work/*")).effect).toBe("allow")
const external = (resource: string) => [
Expand Down Expand Up @@ -673,13 +750,20 @@ off.effect("resolves a directory a command names against its working directory",
}),
)

on.effect("refuses a machine it does not know with the list's message", () =>
on.effect("refuses unknown and removed machines with the list's message", () =>
withTempDir((tmp) => {
const tools = fixture(tmp.path)
return Effect.gen(function* () {
const result = yield* executeTool(yield* Tool.Service, call("read", { path: "gpu:/work/a.txt" }))
expect(result.status).toBe("error")
expect(result.error?.message).toContain('No machine named "gpu".')
const machines = yield* Machines.Service
const { id } = yield* connected(machines, "gpu")
yield* machines.remove(id)
const removed = yield* executeTool(yield* Tool.Service, call("read", { path: "gpu:/work/a.txt" }))
expect(removed.status).toBe("error")
expect(removed.error?.message).toContain('No machine named "gpu".')
expect(tools.assertions).toEqual([])
}).pipe(Effect.provide(graph(tools)))
}),
)
Expand Down
97 changes: 86 additions & 11 deletions packages/core/test/permission.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,11 @@ describe("Permission", () => {
expect(Permission.evaluate("external_directory", "C:/Users/x/other/*", rules).effect).toBe("ask")
})

test("allows a machine's files only by a rule that names the machine", () => {
test("matches machine paths with the same rules as local paths", () => {
const allow = (resource: string): Permission.Ruleset => [{ action: "read", resource, effect: "allow" }]
const files = process.platform === "darwin" || process.platform === "win32"
expect(Permission.evaluate("read", "gpu:/work/a", allow("*")).effect).toBe("ask")
expect(Permission.evaluate("read", "gpu:/work/a", allow("**/work/*")).effect).toBe("ask")
expect(Permission.evaluate("read", "gpu:/work/a", allow("*")).effect).toBe("allow")
expect(Permission.evaluate("read", "gpu:/work/a", allow("**/work/*")).effect).toBe("allow")
expect(Permission.evaluate("read", "gpu:/work/a", allow("gpu:/work/*")).effect).toBe("allow")
expect(Permission.evaluate("read", "gpu:/work/a", allow("gpu:*")).effect).toBe("allow")
expect(Permission.evaluate("read", "cpu:/work/a", allow("gpu:/work/*")).effect).toBe("ask")
Expand Down Expand Up @@ -225,6 +225,87 @@ describe("Permission", () => {
expect(Wildcard.match(".OPENCODE/x", ".opencode/*")).toBe(process.platform === "win32")
})

for (const action of ["read", "edit", "external_directory"]) {
it.effect(`asks for machine-specific ${action} rules`, () =>
Effect.gen(function* () {
yield* setup([
...Agent.Info.default(Agent.ID.make("test")).permissions,
{ action, resource: "gpu:*", effect: "ask" },
])
const { service, fiber, request } = yield* waitForRequest({ action, resources: ["gpu:/work/a"] })
expect(request.resources).toEqual(["gpu:/work/a"])
expect(yield* service.list()).toHaveLength(1)
yield* service.reply({ requestID: request.id, reply: "once" })
yield* Fiber.join(fiber)
}),
)

it.effect(`refuses machine-specific ${action} rules`, () =>
Effect.gen(function* () {
yield* setup([
...Agent.Info.default(Agent.ID.make("test")).permissions,
{ action, resource: "gpu:*", effect: "deny" },
])
const service = yield* Permission.Service
expect(
yield* service.assert(assertion({ action, resources: ["gpu:/work/a"] })).pipe(Effect.flip),
).toBeInstanceOf(Permission.BlockedError)
expect(yield* service.list()).toEqual([])
}),
)
}

it.effect("applies default environment-file exceptions equally to local and machine paths", () =>
Effect.gen(function* () {
yield* setup(Agent.Info.default(Agent.ID.make("test")).permissions)
const service = yield* Permission.Service
for (const prefix of ["", "gpu:/work/"]) {
expect(yield* service.ask(assertion({ resources: [`${prefix}.env.production`] }))).toMatchObject({
effect: "ask",
})
yield* service.reply({ requestID: Permission.ID.create("per_test"), reply: "once" })
expect(yield* service.ask(assertion({ resources: [`${prefix}.env.example`] }))).toMatchObject({
effect: "allow",
})
}
expect(yield* service.list()).toEqual([])
}),
)

for (const [action, resource] of [
["edit", "gpu:/work/a"],
["shell", "pwd"],
])
it.effect(`preserves global ${action} asks and denies`, () =>
Effect.gen(function* () {
yield* setup([
...Agent.Info.default(Agent.ID.make("test")).permissions,
{ action, resource: "*", effect: "ask" },
])
const { service, fiber, request } = yield* waitForRequest({ action, resources: [resource] })
expect(request.action).toBe(action)
yield* service.reply({ requestID: request.id, reply: "once" })
yield* Fiber.join(fiber)
yield* setRules([{ action, resource: "*", effect: "deny" }])
expect(yield* service.assert(assertion({ action, resources: [resource] })).pipe(Effect.flip)).toBeInstanceOf(
Permission.BlockedError,
)
}),
)

it.effect("applies saved broad approvals to machine paths with normal configured deny precedence", () =>
Effect.gen(function* () {
yield* setup([{ action: "read", resource: "gpu:*", effect: "ask" }])
const saved = yield* PermissionSaved.Service
yield* saved.add({ projectID: Project.ID.global, action: "read", resources: ["*"] })
const service = yield* Permission.Service
expect(yield* service.ask(assertion({ resources: ["gpu:/work/a"] }))).toMatchObject({ effect: "allow" })
yield* setRules([{ action: "read", resource: "gpu:*", effect: "deny" }])
expect(yield* service.ask(assertion({ resources: ["gpu:/work/a"] }))).toMatchObject({ effect: "deny" })
expect(yield* service.list()).toEqual([])
}),
)

it.effect("allows managed output reads without granting external directory access", () =>
Effect.gen(function* () {
yield* setup([
Expand Down Expand Up @@ -843,10 +924,7 @@ describe("shell scanner permission impact", () => {
name: "assignment redirect prefix",
shell: "bash",
command: "FOO=bar > output; printf done",
grants: [
["printf *"],
["FOO=bar > *", "printf *"],
],
grants: [["printf *"], ["FOO=bar > *", "printf *"]],
repeat: [
["ask", "allow"],
["ask", "allow"],
Expand All @@ -858,10 +936,7 @@ describe("shell scanner permission impact", () => {
name: "PowerShell method prefix",
shell: "pwsh",
command: '[IO.File]::Delete("C:\\first")',
grants: [
["[IO.File]::Delete(*"],
["[IO.File]::Delete(*"],
],
grants: [["[IO.File]::Delete(*"], ["[IO.File]::Delete(*"]],
repeat: [
["allow", "allow"],
["allow", "allow"],
Expand Down
Loading