diff --git a/packages/core/src/codemode/bun.ts b/packages/core/src/codemode/bun.ts index e1c5399bb5e4..3f1b34b5649c 100644 --- a/packages/core/src/codemode/bun.ts +++ b/packages/core/src/codemode/bun.ts @@ -55,6 +55,14 @@ const call = (syscall: string, name: string, body: (host: Host) => Effect. }) }).pipe(Effect.mapError((error) => nodeError(error, syscall, name))) +const unscoped = Effect.fnUntraced(function* (host: Host, target: FileAccess.Target, action: "read" | "write") { + if (!(yield* host.access.scope(target, host.context, action)).workspace) return target + return yield* new Environment.Failed({ + path: target.absolute, + cause: "Scoped Code Mode Bun file operation is unsupported", + }) +}) + // `Bun.file` asks read permission, and external-directory approval outside the project, once: the file's own reads // don't ask again, and its writes ask only edit. Bun reads `size` and `lastModified` when a program asks for them. A // program's copy of the file can't ask later, so they are read here. A missing file has Bun's values for one. @@ -63,7 +71,8 @@ const open = (input: string | URL, options?: { readonly type?: string }) => { const name = toPath(input) return call("stat", name, (host) => Effect.gen(function* () { - const target = yield* host.access.authorizeRead(name, host.context) + const target = yield* host.access.authorizeRead(name, host.context, { workspaceScope: true }) + yield* unscoped(host, target, "read") const info = yield* followed(target.environment.files, target.absolute).pipe( Effect.catchTag("Environment.NotFound", () => Effect.undefined), ) @@ -132,34 +141,40 @@ const file = (handle: Handle, type: string, size: number, lastModified: number) } const read = (handle: Handle) => - call("open", handle.name, () => - Effect.map( - handle.target.environment.files.read(handle.target.absolute, handle.range), - // A plain Uint8Array over the same memory: a driver may give a Buffer, which Bun's `bytes()` never does. - (result) => new Uint8Array(result.bytes.buffer, result.bytes.byteOffset, result.bytes.byteLength), - ), + call("open", handle.name, (host) => + Effect.gen(function* () { + yield* unscoped(host, handle.target, "read") + const result = yield* handle.target.environment.files.read(handle.target.absolute, handle.range) + return new Uint8Array(result.bytes.buffer, result.bytes.byteOffset, result.bytes.byteLength) + }), ) // As in Bun, only a file exists: a directory doesn't. const exists = (handle: Handle) => - call("access", handle.name, () => - Environment.typeFollowing(handle.target.environment.files, handle.target.absolute).pipe( - Effect.map((type) => type === "file"), - Effect.catchTag("Environment.NotFound", () => Effect.succeed(false)), - ), + call("access", handle.name, (host) => + Effect.gen(function* () { + yield* unscoped(host, handle.target, "read") + return yield* Environment.typeFollowing(handle.target.environment.files, handle.target.absolute).pipe( + Effect.map((type) => type === "file"), + Effect.catchTag("Environment.NotFound", () => Effect.succeed(false)), + ) + }), ) // The part of Node's Stats that the file's environment can tell. const stat = (handle: Handle) => - call("stat", handle.name, () => - Effect.map(followed(handle.target.environment.files, handle.target.absolute), (info) => ({ - size: info.size, - mtimeMs: info.mtimeMs, - mtime: new Date(info.mtimeMs), - isFile: () => info.type === "file", - isDirectory: () => info.type === "directory", - isSymbolicLink: () => info.type === "symlink", - })), + call("stat", handle.name, (host) => + Effect.gen(function* () { + yield* unscoped(host, handle.target, "read") + return yield* Effect.map(followed(handle.target.environment.files, handle.target.absolute), (info) => ({ + size: info.size, + mtimeMs: info.mtimeMs, + mtime: new Date(info.mtimeMs), + isFile: () => info.type === "file", + isDirectory: () => info.type === "directory", + isSymbolicLink: () => info.type === "symlink", + })) + }), ) // What a path leads to, through a symlink: reading zero bytes resolves one. A directory behind a link keeps the @@ -179,6 +194,7 @@ const followed = (files: Environment.Files, absolute: string) => const remove = (handle: Handle) => call("unlink", handle.name, (host) => Effect.gen(function* () { + yield* unscoped(host, handle.target, "write") const info = yield* handle.target.environment.files.stat(handle.target.absolute) if (info.type === "directory") return yield* new Environment.WrongKind({ path: handle.target.absolute, actual: info.type }) @@ -218,6 +234,7 @@ const put = ( call("open", typeof to === "string" ? to : to.name, (host) => Effect.gen(function* () { const target = typeof to === "string" ? yield* host.fileWrite.target(to, host.context) : to.target + yield* unscoped(host, target, "write") return yield* Effect.gen(function* () { const type = yield* typeOf(target.environment.files, target.absolute) if (type === "directory") return yield* new Environment.WrongKind({ path: target.absolute, actual: type }) diff --git a/packages/core/src/environment/guarded-mutation.ts b/packages/core/src/environment/guarded-mutation.ts new file mode 100644 index 000000000000..74ae71c442de --- /dev/null +++ b/packages/core/src/environment/guarded-mutation.ts @@ -0,0 +1,94 @@ +import { constants } from "node:fs" +import { lstat, mkdir, open, realpath, rename, unlink } from "node:fs/promises" +import { randomUUID } from "node:crypto" +import path from "node:path" +import { openWorkspaceDirectory, openWorkspaceFile } from "./guarded-read.js" + +const segments = (relative: string) => { + const parts = relative.split("/") + if (parts.some((part) => !part || part === "." || part === ".." || part.includes("\0"))) + throw new Error("Invalid workspace mutation path") + if (parts.includes(".git")) throw new Error("Workspace Git metadata cannot be mutated") + return parts +} + +export async function readWorkspaceBytes(root: string, relative: string) { + const file = await openWorkspaceFile(root, relative) + try { + if ((await file.stat()).size > 64 * 1024 * 1024) throw new Error("Workspace file exceeds 64 MiB read limit") + return await file.readFile() + } finally { + await file.close() + } +} + +/** Publish bytes via an anchored parent descriptor. Existing inodes are never modified in place. */ +export async function replaceWorkspaceFile( + root: string, + relative: string, + bytes: Uint8Array, + verify: () => Promise, +) { + const parts = segments(relative) + await verify() + for (let index = 0; index < parts.length - 1; index++) { + const parent = await openWorkspaceDirectory(root, parts.slice(0, index).join("/")) + try { + await verify() + await mkdir(path.join(parent.childPath, parts[index])).catch((error: NodeJS.ErrnoException) => { + if (error.code !== "EEXIST") throw error + }) + } finally { + await parent.close() + } + const directory = await openWorkspaceDirectory(root, parts.slice(0, index + 1).join("/")) + await directory.close() + } + const parentRelative = parts.slice(0, -1).join("/") + const parent = await openWorkspaceDirectory(root, parentRelative) + const destination = path.join(parent.childPath, parts.at(-1)!) + const temporary = path.join(parent.childPath, `.opencode-${randomUUID()}.tmp`) + try { + const before = await lstat(destination).catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return undefined + throw error + }) + if (before && (!before.isFile() || before.nlink !== 1)) + throw new Error("Workspace target is not a single-link regular file") + await verify() + const file = await open( + temporary, + constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, + 0o600, + ) + try { + await file.writeFile(bytes) + if (before) { + if (before.uid !== process.getuid?.() || before.gid !== process.getgid?.()) + throw new Error("Workspace target owner differs from current process") + await file.chmod(before.mode & 0o777) + } else { + await file.chmod(0o666 & ~process.umask()) + } + await file.sync() + } finally { + await file.close() + } + await verify() + if ((await realpath(parent.childPath)) !== path.join(root, parentRelative)) + throw new Error("Workspace parent changed before publication") + const current = await lstat(destination).catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return undefined + throw error + }) + if (before?.dev !== current?.dev || before?.ino !== current?.ino) + throw new Error("Workspace target changed before publication") + await rename(temporary, destination) + return { existed: before !== undefined } + } finally { + await unlink(temporary).catch((error: NodeJS.ErrnoException) => { + if (error.code !== "ENOENT") throw error + }) + await parent.close() + } +} diff --git a/packages/core/src/environment/guarded-read.ts b/packages/core/src/environment/guarded-read.ts new file mode 100644 index 000000000000..ee0e3236d130 --- /dev/null +++ b/packages/core/src/environment/guarded-read.ts @@ -0,0 +1,118 @@ +import { constants, type Dirent } from "node:fs" +import { open, readdir, realpath, type FileHandle } from "node:fs/promises" +import { isAbsolute, join } from "node:path" + +/** Opens a regular file below a trusted physical root without following child symlinks. */ +export async function openWorkspaceFile(root: string, relative: string): Promise { + childSegments(relative) + const entry = await openWorkspaceEntry(root, relative) + if (entry.type === "file") return entry.file + await entry.directory.close() + throw new Error("Workspace path is not a regular file") +} + +/** Opens either supported entry kind without a separate pathname lookup. */ +export async function openWorkspaceEntry(root: string, relative: string) { + if (!relative) return { type: "directory" as const, directory: await openWorkspaceDirectory(root, relative) } + const segments = childSegments(relative) + const expected = join(root, ...segments) + + const parent = await openDirectory(root, segments.slice(0, -1)) + try { + await requireIdentity(parent, join(root, ...segments.slice(0, -1))) + const file = await open( + `/proc/self/fd/${parent.fd}/${segments[segments.length - 1]}`, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK | constants.O_NOCTTY, + ) + try { + const kind = await file.stat() + await requireIdentity(file, expected) + if (kind.isFile()) return { type: "file" as const, file } + if (kind.isDirectory()) return { type: "directory" as const, directory: directoryLease(file, expected) } + throw new Error("Workspace path is not a regular file or directory") + } catch (error) { + await file.close() + throw error + } + } finally { + await parent.close() + } +} + +/** A directory descriptor retained for enumeration and a child-process anchor. */ +export async function openWorkspaceDirectory(root: string, relative: string) { + const segments = childSegments(relative, true) + const directory = await openDirectory(root, segments) + return directoryLease(directory, join(root, ...segments)) +} + +function directoryLease(directory: FileHandle, expected: string) { + let closed = false + const pending = new Set>() + + return { + /** Valid until close(); callers must constrain child traversal separately and await child exit first. */ + childPath: `/proc/${process.pid}/fd/${directory.fd}`, + async readEntries(): Promise { + if (closed) throw new Error("Workspace directory is closed") + const read = (async () => { + await requireIdentity(directory, expected) + return readdir(`/proc/self/fd/${directory.fd}`, { withFileTypes: true }) + })() + pending.add(read) + try { + return await read + } finally { + pending.delete(read) + } + }, + async close() { + if (closed) return + closed = true + await Promise.allSettled([...pending]) + await directory.close() + }, + } +} + +function childSegments(relative: string, allowRoot = false) { + if (allowRoot && relative === "") return [] + const segments = relative.split("/") + if (segments.some((segment) => !segment || segment === "." || segment === ".." || segment.includes("\0"))) { + throw new Error("Workspace path must contain only relative child segments") + } + return segments +} + +async function openDirectory(root: string, segments: string[]) { + if (process.platform !== "linux") throw new Error("Guarded workspace reads require Linux") + if (!isAbsolute(root) || (await realpath(root)) !== root) throw new Error("Workspace root must be canonical") + + let parent = await open(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW) + try { + await requireIdentity(parent, root) + for (const [index, segment] of segments.entries()) { + await requireIdentity(parent, join(root, ...segments.slice(0, index))) + const next = await open( + `/proc/self/fd/${parent.fd}/${segment}`, + constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW, + ) + try { + await requireIdentity(next, join(root, ...segments.slice(0, index + 1))) + } catch (error) { + await next.close() + throw error + } + await parent.close() + parent = next + } + return parent + } catch (error) { + await parent.close() + throw error + } +} + +async function requireIdentity(handle: FileHandle, expected: string) { + if ((await realpath(`/proc/self/fd/${handle.fd}`)) !== expected) throw new Error("Workspace path changed during open") +} diff --git a/packages/core/src/file-access.ts b/packages/core/src/file-access.ts index b8d2f61bdfec..3791bdf5c33f 100644 --- a/packages/core/src/file-access.ts +++ b/packages/core/src/file-access.ts @@ -11,6 +11,7 @@ import { EnvironmentPath } from "./environment/path.js" import { Flag } from "./flag.js" import { Location } from "./location.js" import { Permission } from "./permission.js" +import { PluginHooks } from "./plugin/hooks.js" import { Project } from "./project.js" import { AbsolutePath } from "./schema.js" import type { SessionErrors } from "./session/error.js" @@ -50,6 +51,15 @@ export interface Target { readonly environment: Environment.Interface /** The machine the file is on, when it is not on this server. */ readonly machine?: Environment.ID + readonly workspace?: WorkspaceTarget +} + +export interface WorkspaceTarget { + readonly root: string + readonly relative: string + readonly absolute: AbsolutePath + readonly resources: readonly string[] + readonly verify: () => Effect.Effect } export function externalDirectoryRequest(targets: readonly Target[]) { @@ -79,7 +89,9 @@ export type Invocation = Pick Effect.Effect /** Resolve a lexical path and its permission resources, without requesting approval. */ readonly resolve: (input: ResolveInput) => Effect.Effect + /** Verify membership for this invocation. Only consume the result through a guarded operation. */ + readonly scope: ( + target: Target, + context: Invocation, + action: "read" | "write" | "shell-cwd", + ) => Effect.Effect /** Approve external directories in one batch, preserving first-seen resource order. */ readonly authorizeExternal: ( targets: readonly Target[], @@ -130,6 +148,7 @@ const layer = Layer.effect( const location = yield* Location.Service const currentWorkingDirectory = yield* Environment.workingDirectoryResolver const permission = yield* Permission.Service + const hooks = yield* PluginHooks.Service const flags = yield* Flag.Service const environments = yield* Environments.Service @@ -309,6 +328,105 @@ const layer = Layer.effect( }) }) + const scope = Effect.fn("FileAccess.scope")(function* ( + target: Target, + context: Invocation, + action: "read" | "write" | "shell-cwd", + ) { + if ( + process.platform !== "linux" || + target.environment.id !== Environment.localID || + !(yield* flags.enabled("workspace_read_scope")) + ) + return target + + const assignment = Effect.fnUntraced(function* () { + const result = yield* hooks.trigger("permission", "experimental.workspace.readScope", { + ...Permission.invocation(context), + directory: location.directory, + action, + scopes: [], + }) + if (result.scopes.length === 0) return + const scope = result.scopes[0] + if ( + result.scopes.length !== 1 || + !scope || + scope.members.length === 0 || + scope.members.some( + (member) => + !path.isAbsolute(member.physical) || + member.physical === "/" || + path.resolve(member.physical) !== member.physical || + path.resolve(member.logical) !== member.logical || + member.logical === location.directory || + !FSUtil.contains(location.directory, member.logical) || + member.protectedPaths?.some( + (protectedPath) => + !protectedPath || + protectedPath + .split("/") + .some( + (segment) => + !segment || + segment === "." || + segment === ".." || + segment.includes("\\") || + segment.includes("\0"), + ), + ), + ) + ) + return yield* new Environment.Failed({ path: target.absolute, cause: "Unverified workspace assignment" }) + + const members = scope.members.filter( + (member) => + FSUtil.contains(member.physical, target.absolute) || FSUtil.contains(member.logical, target.absolute), + ) + if (members.length > 1) + return yield* new Environment.Failed({ path: target.absolute, cause: "Ambiguous workspace assignment" }) + const member = members[0] + if (!member) return + return member + }) + const member = yield* assignment() + if (!member) return target + const selectedRoot = FSUtil.contains(member.physical, target.absolute) ? member.physical : member.logical + const relative = path.relative(selectedRoot, target.absolute) + if ( + action === "write" && + member.protectedPaths?.some( + (protectedPath) => relative === protectedPath || relative.startsWith(`${protectedPath}/`), + ) + ) + return yield* new Environment.Failed({ path: target.absolute, cause: "Protected workspace path" }) + const absolute = AbsolutePath.make(path.join(member.physical, relative)) + const resource = slash(path.relative(location.directory, path.join(member.logical, relative))) + const verify = Effect.fnUntraced(function* () { + const current = yield* assignment() + if ( + current?.physical !== member.physical || + current.logical !== member.logical || + JSON.stringify(current.protectedPaths ?? []) !== JSON.stringify(member.protectedPaths ?? []) + ) + return yield* new Environment.Failed({ + path: target.absolute, + cause: "Workspace assignment or policy changed", + }) + }) + return { + ...target, + resource, + workspace: { + root: member.physical, + absolute, + relative, + resources: [resource, slash(absolute)], + verify, + }, + } + }) + const authorizeRead = Effect.fn("FileAccess.authorizeRead")(function* ( file: string, context: Invocation, @@ -316,19 +434,40 @@ const layer = Layer.effect( ) { // A local sibling keeps the Location's resolution exactly as without recovery; a machine's candidate has no // Location to resolve against, so it takes the machine and the sibling's directory. - const siblingPath = options?.siblingOf.environment.path ?? path + const siblingOf = options?.siblingOf + const siblingPath = siblingOf?.environment.path ?? path const base = - options === undefined || options.siblingOf.environment.id === environment.id + siblingOf === undefined || siblingOf.environment.id === environment.id ? undefined : { - absolute: AbsolutePath.make(siblingPath.dirname(options.siblingOf.absolute)), - environment: options.siblingOf.environment, + absolute: AbsolutePath.make(siblingPath.dirname(siblingOf.absolute)), + environment: siblingOf.environment, } - const target = yield* resolve({ path: file, base, kind: options ? "file" : undefined }) + const target: Target = yield* resolve({ path: file, base, kind: siblingOf ? "file" : undefined }) + const scoped = options?.workspaceScope ? yield* scope(target, context, "read") : target + if (scoped.workspace) { + const physical = + target.absolute === scoped.workspace.absolute ? target : yield* resolve({ path: scoped.workspace.absolute }) + const external = externalDirectoryRequest([target, physical]) + if (external) + yield* permission.assertNotDenied({ + action: external.action, + resources: external.resources, + ...Permission.invocation(context), + }) + const resources = scoped.workspace.resources + yield* permission.assert({ + action: "read", + resources, + verifiedWorkspace: true, + ...Permission.invocation(context), + }) + return scoped + } const sibling = - options !== undefined && - target.environment.id === options.siblingOf.environment.id && - (target.environment.path ?? path).dirname(target.absolute) === siblingPath.dirname(options.siblingOf.absolute) + siblingOf !== undefined && + target.environment.id === siblingOf.environment.id && + (target.environment.path ?? path).dirname(target.absolute) === siblingPath.dirname(siblingOf.absolute) // Filename recovery shares the directory approval, but checks the recovered file's own read rules. if (!sibling) yield* authorizeExternal([target], context) @@ -341,12 +480,12 @@ const layer = Layer.effect( return target }) - return Service.of({ locate, resolve, authorizeExternal, authorizeRead }) + return Service.of({ locate, resolve, scope, authorizeExternal, authorizeRead }) }), ) export const node = makeLocationNode({ service: Service, layer, - deps: [Environment.node, Environments.node, Flag.node, Location.node, Permission.node], + deps: [Environment.node, Environments.node, Flag.node, Location.node, Permission.node, PluginHooks.node], }) diff --git a/packages/core/src/file-mutation.ts b/packages/core/src/file-mutation.ts index ab868d86b3c8..0914a6a34e39 100644 --- a/packages/core/src/file-mutation.ts +++ b/packages/core/src/file-mutation.ts @@ -10,6 +10,7 @@ import { Environment } from "./environment/index.js" import type { Files } from "./environment/index.js" import { FileAccess } from "./file-access.js" import { AbsolutePath } from "./schema.js" +import { readWorkspaceBytes, replaceWorkspaceFile } from "./environment/guarded-mutation.js" export type Target = Pick @@ -77,6 +78,85 @@ export const readOptionalText = Effect.fn("FileMutation.readOptionalText")(funct return result ? Bom.decodeBytes(result.bytes) : undefined }) +export const readScopedOptionalText = Effect.fn("FileMutation.readScopedOptionalText")(function* ( + target: FileAccess.Target, +) { + if (!target.workspace) throw new Error("Expected a scoped target") + yield* target.workspace.verify() + const bytes = yield* Effect.tryPromise({ + try: () => readWorkspaceBytes(target.workspace!.root, target.workspace!.relative), + catch: (cause) => new Environment.Failed({ path: target.absolute, cause }), + }).pipe( + Effect.catchIf( + (error) => (error.cause as NodeJS.ErrnoException)?.code === "ENOENT", + () => Effect.undefined, + ), + ) + return bytes ? Bom.decodeBytes(bytes) : undefined +}) + +export const readScopedEditableText = Effect.fn("FileMutation.readScopedEditableText")(function* ( + target: FileAccess.Target, +) { + if (!target.workspace) throw new Error("Expected a scoped target") + yield* target.workspace.verify() + const bytes = yield* Effect.tryPromise({ + try: () => readWorkspaceBytes(target.workspace!.root, target.workspace!.relative), + catch: (cause) => new Environment.Failed({ path: target.absolute, cause }), + }).pipe( + Effect.catchIf( + (error) => (error.cause as NodeJS.ErrnoException)?.code === "ENOENT", + () => Effect.fail(new Environment.NotFound({ path: target.absolute })), + ), + ) + if (!isUtf8(bytes)) return yield* new InvalidUtf8Error({ path: target.absolute }) + return Bom.decodeBytes(bytes) +}) + +export const writeScopedTextPreservingBom = Effect.fn("FileMutation.writeScopedTextPreservingBom")(function* ( + target: FileAccess.Target, + content: string, +) { + if (!target.workspace) throw new Error("Expected a scoped target") + yield* target.workspace.verify() + const current = yield* readScopedOptionalText(target) + const next = Bom.split(content) + const bom = Boolean(current?.bom) || next.bom + const result = yield* Effect.tryPromise({ + try: () => + replaceWorkspaceFile( + target.workspace!.root, + target.workspace!.relative, + new TextEncoder().encode(Bom.join(next.text, bom)), + () => Effect.runPromise(target.workspace!.verify()), + ), + catch: (cause) => new Environment.Failed({ path: target.absolute, cause }), + }) + return { + operation: "write" as const, + target: target.workspace.absolute, + resource: target.resource, + existed: result.existed, + bom, + } +}) + +/** Commit patch text exactly; patch derivation already owns its BOM decision. */ +export const writeScopedExactText = Effect.fn("FileMutation.writeScopedExactText")(function* ( + target: FileAccess.Target, + content: string, +) { + if (!target.workspace) throw new Error("Expected a scoped target") + yield* target.workspace.verify() + return yield* Effect.tryPromise({ + try: () => + replaceWorkspaceFile(target.workspace!.root, target.workspace!.relative, new TextEncoder().encode(content), () => + Effect.runPromise(target.workspace!.verify()), + ), + catch: (cause) => new Environment.Failed({ path: target.absolute, cause }), + }) +}) + export const syncTextBom = Effect.fn("FileMutation.syncTextBom")(function* ( files: Files, target: string, diff --git a/packages/core/src/file-write.ts b/packages/core/src/file-write.ts index 2e743b1dc719..fe709da5ebdb 100644 --- a/packages/core/src/file-write.ts +++ b/packages/core/src/file-write.ts @@ -61,6 +61,13 @@ const layer = Layer.effect( const target = Effect.fn("FileWrite.target")(function* (file: string, context: FileAccess.Invocation) { const target = yield* access.resolve({ path: file, kind: "file" }) + const scoped = yield* access.scope(target, context, "write") + if (scoped.workspace) { + const physical = yield* access.resolve({ path: scoped.workspace.absolute, kind: "file" }) + const external = FileAccess.externalDirectoryRequest([target, physical]) + if (external) yield* permission.assertNotDenied({ ...external, ...Permission.invocation(context) }) + return scoped + } yield* access.authorizeExternal([target], context) return target }) @@ -72,14 +79,16 @@ const layer = Layer.effect( ) { yield* permission.assert({ action: "edit", - resources: [target.resource], - save: [FileAccess.always(target)], + resources: target.workspace?.resources ?? [target.resource], + ...(target.workspace ? { verifiedWorkspace: true as const } : {}), + ...(target.workspace ? {} : { save: [FileAccess.always(target)] }), metadata: preview ? { files: [preview] } : undefined, ...Permission.invocation(context), }) }) const commit = Effect.fn("FileWrite.commit")(function* (target: FileAccess.Target, content: string) { + if (target.workspace) return yield* FileMutation.writeScopedTextPreservingBom(target, content) const written = yield* fileMutation.writeTextPreservingBom({ target, content }) if (!(yield* formatter.file(target))) return written return { @@ -90,13 +99,30 @@ const layer = Layer.effect( const write = Effect.fn("FileWrite.write")(function* (input: WriteInput, context: FileAccess.Invocation) { const resolved = yield* target(input.path, context) - const current = yield* FileMutation.readOptionalText(resolved.environment.files, resolved.absolute) - yield* authorize( - resolved, - context, - fileDiff(resolved.resource, current?.text ?? "", Bom.split(input.content).text, current ? "modified" : "added"), + return yield* fileMutation.withLock([resolved.workspace?.absolute ?? resolved.absolute])( + Effect.gen(function* () { + if (resolved.workspace) + yield* permission.assertNotDenied({ + action: "read", + resources: resolved.workspace.resources, + ...Permission.invocation(context), + }) + const current = resolved.workspace + ? yield* FileMutation.readScopedOptionalText(resolved) + : yield* FileMutation.readOptionalText(resolved.environment.files, resolved.absolute) + yield* authorize( + resolved, + context, + fileDiff( + resolved.resource, + current?.text ?? "", + Bom.split(input.content).text, + current ? "modified" : "added", + ), + ) + return yield* commit(resolved, input.content) + }), ) - return yield* commit(resolved, input.content) }) return Service.of({ target, authorize, commit, write }) diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index 196c7f210432..6800e6f0d896 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -35,6 +35,8 @@ export type Reply = typeof Reply.Type export interface AssertInput extends Omit { readonly id?: ID readonly agent?: Agent.ID + /** Internal provenance for a native guarded workspace file operation; never persisted on a Request. */ + readonly verifiedWorkspace?: true } /** The requester fields of a permission request made by a tool call. */ @@ -217,6 +219,7 @@ const layer = Layer.effect( action: input.action, resources: input.resources, metadata: input.metadata, + verifiedWorkspace: input.verifiedWorkspace, source: row(input.source), effect, }) diff --git a/packages/core/src/persistent-pty/daemon.ts b/packages/core/src/persistent-pty/daemon.ts index 09649b37e287..6ab59b2202ca 100644 --- a/packages/core/src/persistent-pty/daemon.ts +++ b/packages/core/src/persistent-pty/daemon.ts @@ -186,7 +186,11 @@ export class DaemonError extends Data.TaggedError("PersistentPty.DaemonError")<{ }> {} export interface DaemonTransport { - readonly request: (value: object, start?: boolean) => Effect.Effect + readonly request: ( + value: object, + start?: boolean, + requiredFeature?: string, + ) => Effect.Effect readonly requestIfRunning: (value: object) => Effect.Effect /** Waits on its own connection, with no timeout, until the pipe process exits. Never starts the daemon. */ readonly wait: (id: number) => Effect.Effect @@ -372,18 +376,32 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport" ) }) - const attempt = Effect.fn("PersistentPty.daemon.request-attempt")((value: object, shouldStart: boolean) => - withRegistration(shouldStart, (current) => oneShot(current, value)), + const attempt = Effect.fn("PersistentPty.daemon.request-attempt")( + (value: object, shouldStart: boolean, requiredFeature?: string) => + withRegistration(shouldStart, (current) => + requiredFeature && !current.features.includes(requiredFeature) + ? Effect.fail( + new DaemonError({ + kind: "protocol", + message: `opencode-pty does not support required feature: ${requiredFeature}`, + }), + ) + : oneShot(current, value), + ), ) - const request = Effect.fn("PersistentPty.daemon.request")(function* (value: object, shouldStart = false) { - return yield* attempt(value, shouldStart).pipe( + const request = Effect.fn("PersistentPty.daemon.request")(function* ( + value: object, + shouldStart = false, + requiredFeature?: string, + ) { + return yield* attempt(value, shouldStart, requiredFeature).pipe( Effect.catch((error) => { - if (error.kind === "registration") return attempt(value, shouldStart) + if (error.kind === "registration") return attempt(value, shouldStart, requiredFeature) if (error.kind !== "connect") return Effect.fail(error) registration = undefined if (!shouldStart) return Effect.fail(error) - return attempt(value, true) + return attempt(value, true, requiredFeature) }), ) }) diff --git a/packages/core/src/persistent-pty/index.ts b/packages/core/src/persistent-pty/index.ts index ac3db0abeb61..d025362bed08 100644 --- a/packages/core/src/persistent-pty/index.ts +++ b/packages/core/src/persistent-pty/index.ts @@ -118,6 +118,8 @@ export type CreatePipeInput = { readonly args: readonly string[] /** Absolute. */ readonly cwd: string + /** Verified by the caller; the daemon opens this cwd beneath its physical root at launch. Linux only. */ + readonly guardedCwd?: { readonly root: string; readonly relative: string } /** The child's whole environment; the daemon's own is not inherited. */ readonly env: Readonly> readonly groupID: string @@ -464,12 +466,14 @@ const makeLayer = (options: Options = {}) => program: input.program, args: input.args, cwd: input.cwd, + ...(input.guardedCwd ? { guarded_cwd: input.guardedCwd } : {}), env: input.env, group_id: input.groupID, output_path: input.outputPath, metadata: input.metadata, }, true, + input.guardedCwd ? "guarded_cwd" : undefined, ) .pipe(Effect.mapError(pipeError)) if (response.type !== "created") return yield* unexpectedPipe(response) diff --git a/packages/core/src/ripgrep.ts b/packages/core/src/ripgrep.ts index 2e53c334a814..cda019099cbb 100644 --- a/packages/core/src/ripgrep.ts +++ b/packages/core/src/ripgrep.ts @@ -84,6 +84,10 @@ export interface GrepInput { readonly cwd: string readonly pattern: string readonly file?: string + /** Stable result name for a guarded descriptor path passed as `file`. */ + readonly displayFile?: string + /** Guarded descriptor paths held open until this grep process exits. */ + readonly files?: readonly { readonly path: string; readonly display: string }[] readonly include?: string readonly literal?: boolean readonly caseSensitive?: boolean @@ -92,6 +96,12 @@ export interface GrepInput { } export interface Interface { + /** Validate a native rg glob without searching a workspace pathname. */ + readonly validateGlob: (input: { + readonly environment: Environment.Interface + readonly cwd: string + readonly pattern: string + }) => Effect.Effect readonly find: (input: FindInput) => Effect.Effect readonly glob: (input: GlobInput) => Effect.Effect readonly grep: (input: GrepInput) => Effect.Effect @@ -184,6 +194,17 @@ const layer = Layer.effect( } return Service.of({ + validateGlob: (input) => + run({ + environment: input.environment, + cwd: input.cwd, + limit: 1, + args: ["--no-config", "--files", `--glob=${input.pattern}`, "/dev/null"], + parse: () => Effect.undefined, + }).pipe( + Effect.asVoid, + Effect.catchTag("Ripgrep.InvalidPatternError", (cause) => Effect.fail(failure(cause.message, cause))), + ), glob: (input) => run({ environment: input.environment, @@ -248,13 +269,14 @@ const layer = Layer.effect( "--json", "--hidden", "--no-messages", + ...(input.displayFile || input.files ? ["--no-ignore"] : []), ...(input.literal ? ["--fixed-strings"] : []), ...(input.caseSensitive === false ? ["--ignore-case"] : []), ...(input.include ? [`--glob=${input.include}`] : []), "--glob=!**/.git/**", "--", input.pattern, - input.file ?? ".", + ...(input.files ? input.files.map((file) => file.path) : [input.file ?? "."]), ], parse: (line) => decodeJsonRecord(line).pipe( @@ -263,22 +285,22 @@ const layer = Layer.effect( if (!json || typeof json !== "object" || !("type" in json) || json.type !== "match") return Effect.undefined return Schema.decodeUnknownEffect(RawMatch)(json).pipe( - Effect.map((match) => { + Effect.flatMap((match) => { const lines = rawText(match.data.lines) - return { + const observed = rawText(match.data.path) + const display = input.files?.find((file) => file.path === observed)?.display + if (input.files && !display) return Effect.fail(failure("Unknown guarded ripgrep result path")) + return Effect.succeed({ ...match.data, lines: { - text: - lines.length > MAX_LINE_CHARS - ? TextBoundary.head(lines, MAX_LINE_CHARS) + "..." - : lines, + text: lines.length > MAX_LINE_CHARS ? TextBoundary.head(lines, MAX_LINE_CHARS) + "..." : lines, }, - path: { text: normalizePath(rawText(match.data.path)) }, + path: { text: display ?? input.displayFile ?? normalizePath(observed) }, submatches: match.data.submatches.slice(0, MAX_SUBMATCHES).map((submatch) => ({ ...submatch, match: { text: rawText(submatch.match) }, })), - } + }) }), Effect.mapError((cause) => failure("Invalid ripgrep match output", cause)), ) diff --git a/packages/core/src/shell.ts b/packages/core/src/shell.ts index 6f853a08c1e5..1f5bef7e0569 100644 --- a/packages/core/src/shell.ts +++ b/packages/core/src/shell.ts @@ -26,6 +26,7 @@ import { FSUtil } from "@opencode/util/fs-util" import { TextBoundary } from "@opencode/util/text-boundary" import { Bus } from "./bus.js" import { Environment } from "./environment/index.js" +import type { FileAccess } from "./file-access.js" import { FileRetention } from "./file-retention.js" import { Location } from "./location.js" import { Global } from "@opencode/util/global" @@ -79,6 +80,7 @@ const Stored = Schema.Struct({ id: Shell.ID, command: Schema.String, shell: Schema.String, + cwd: Schema.optional(Schema.String), location: Schema.Struct({ directory: Schema.String, workspaceID: Schema.optionalKey(Schema.String) }), metadata: Shell.Metadata, toolCall: Schema.optional(ToolCall), @@ -152,7 +154,7 @@ type Ended = { export interface Interface { readonly create: ( input: CreateInput, - before?: (input: ShellCreateBefore) => Effect.Effect, + before?: (input: ShellCreateBefore) => Effect.Effect, ) => Effect.Effect // Currently running commands only; exited shells are retained for get/output but excluded here. readonly list: () => Effect.Effect @@ -252,6 +254,7 @@ interface Runs { readonly info: Info readonly args: readonly string[] readonly env: Readonly> + readonly workspace?: FileAccess.WorkspaceTarget readonly timeout: number readonly toolCall: ToolCall | undefined readonly waited: boolean @@ -301,6 +304,7 @@ type CommandCreate = { readonly cwd: string /** The command's whole environment. */ readonly env: Readonly> + readonly workspace?: FileAccess.WorkspaceTarget readonly projectID: string readonly outputPath: string readonly metadata: Stored @@ -358,6 +362,7 @@ const commandRuns = (host: CommandHost) => id: run.info.id, command: run.info.command, shell: run.info.shell, + cwd: run.info.cwd, location: { directory: location.directory, ...(location.workspaceID !== undefined ? { workspaceID: location.workspaceID } : {}), @@ -514,7 +519,8 @@ const commandRuns = (host: CommandHost) => const created = yield* host.create({ program: input.info.shell, args: input.args, - cwd: input.info.cwd, + cwd: input.workspace?.absolute ?? input.info.cwd, + workspace: input.workspace, env: input.env, projectID: location.project.id, outputPath: input.info.file, @@ -566,7 +572,7 @@ const commandRuns = (host: CommandHost) => id: stored.id, status, command: stored.command, - cwd: process.cwd, + cwd: stored.cwd ?? process.cwd, shell: stored.shell, file: process.outputPath, ...(process.pid !== undefined ? { pid: process.pid } : {}), @@ -655,7 +661,16 @@ const daemonLayer = Layer.effect( remove: () => pty.terminatePipe(info.id), }) const runs = yield* commandRuns({ - create: (input) => pty.createPipe({ ...input, groupID: input.projectID }).pipe(Effect.map(pipe)), + create: (input) => + pty + .createPipe({ + ...input, + groupID: input.projectID, + guardedCwd: input.workspace + ? { root: input.workspace.root, relative: input.workspace.relative } + : undefined, + }) + .pipe(Effect.map(pipe)), list: () => pty.listPipes().pipe(Effect.map((items) => items.map(pipe))), lost: "Command was killed: the process daemon stopped", }) @@ -961,7 +976,7 @@ const layer = () => const create = Effect.fn("Shell.create")(function* ( input: CreateInput, - before?: (input: ShellCreateBefore) => Effect.Effect, + before?: (input: ShellCreateBefore) => Effect.Effect, ) { const sessionID = input.metadata?.sessionID const workingDirectory = yield* currentWorkingDirectory @@ -985,9 +1000,15 @@ const layer = () => }, } yield* hooks.trigger("shell", "create.before", invocation) - if (before) yield* before(invocation) + const workspace = (before ? yield* before(invocation) : undefined) ?? undefined // Absolute for the server's own commands, so the command reports the same cwd wherever it runs. if (target.local) invocation.cwd = path.resolve(workingDirectory.absolute, invocation.cwd) + // The permission wait can outlive the assignment or directory. Verify immediately before asking the + // daemon to open the cwd; the daemon separately anchors its lookup at launch time. + if (workspace) + yield* workspace + .verify() + .pipe(Effect.mapError((cause) => new AppProcess.AppProcessError({ command: invocation.command, cause }))) // Created per command: the directory can be removed while the Location stays open. yield* fs @@ -1010,10 +1031,18 @@ const layer = () => } yield* annotate(info) + if (workspace && (!runs || !target.local)) + return yield* Effect.fail( + new AppProcess.AppProcessError({ + command: invocation.command, + cause: new Error("Guarded workspace shell commands require a compatible local process daemon"), + }), + ) if (runs && target.local) { const created = yield* runs .create({ info, + workspace, args, // The daemon replaces the environment, so variables removed by hooks stay removed, like the spawner. env: Object.fromEntries( @@ -1027,9 +1056,18 @@ const layer = () => Effect.map(Option.some), Effect.catchTags({ "PersistentPty.UnavailableError": (error) => - Effect.logWarning("process daemon unavailable; spawning shell command instead", { - error: error.message, - }).pipe(Effect.as(Option.none())), + workspace + ? Effect.fail( + new AppProcess.AppProcessError({ + command: invocation.command, + cause: new Error( + `Guarded workspace shell command requires a compatible process daemon: ${error.message}`, + ), + }), + ) + : Effect.logWarning("process daemon unavailable; spawning shell command instead", { + error: error.message, + }).pipe(Effect.as(Option.none())), // The daemon may have run it: never run it again here. "PersistentPty.RequestError": (cause) => Effect.fail(new AppProcess.AppProcessError({ command: invocation.command, cause })), diff --git a/packages/core/src/shell/permissions.ts b/packages/core/src/shell/permissions.ts index ffee08495eb1..34bcfd6b1a20 100644 --- a/packages/core/src/shell/permissions.ts +++ b/packages/core/src/shell/permissions.ts @@ -24,8 +24,12 @@ export const requests = Effect.fnUntraced(function* ( readonly policy: Effect.Effect }, ) { + // Relative operands resolve from the directory the child will actually use. + const scanTarget = input.target.workspace + ? { ...input.target, absolute: input.target.workspace.absolute } + : input.target const scanned = yield* Effect.result( - ShellParse.scan(input.command, input.program, input.target.absolute, { + ShellParse.scan(input.command, input.program, scanTarget.absolute, { home: input.target.machine === undefined ? undefined : null, }), ) @@ -43,9 +47,12 @@ export const requests = Effect.fnUntraced(function* ( const parsed = scanned.success // Directory arguments are relative to the command's working directory on the same machine. const directories = yield* Effect.forEach(parsed.directories, (directory) => - access.resolve({ path: directory, base: input.target, kind: "directory" }), + access.resolve({ path: directory, base: scanTarget, kind: "directory" }), ) - const external = FileAccess.externalDirectoryRequest([input.target, ...directories]) + const external = FileAccess.externalDirectoryRequest([ + ...(input.target.workspace ? [] : [input.target]), + ...directories, + ]) const command = parsed.commands.length > 0 || input.once ? { diff --git a/packages/core/src/tool/plugin/edit.ts b/packages/core/src/tool/plugin/edit.ts index 1523916fab53..83badbab925b 100644 --- a/packages/core/src/tool/plugin/edit.ts +++ b/packages/core/src/tool/plugin/edit.ts @@ -297,72 +297,96 @@ export const Plugin = { } const target = yield* fileWrite.target(input.path, context) + return yield* fileMutation.withLock([target.workspace?.absolute ?? target.absolute])( + Effect.gen(function* () { + if (target.workspace) + yield* permission.assertNotDenied({ + action: "read", + resources: target.workspace.resources, + ...Permission.invocation(context), + }) - const original = yield* FileMutation.readEditableText(target.environment.files, target.absolute).pipe( - Effect.catchTag("Environment.NotFound", () => - Effect.fail(new ToolFailure({ message: `File not found: ${input.path}` })), - ), - Effect.catchTag("FileMutation.InvalidUtf8Error", (error) => - Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}: ${error.message}` })), - ), - Effect.catchTag("Environment.WrongKind", (error) => - error.actual === "directory" - ? Effect.fail(new ToolFailure({ message: `Path is a directory, not a file: ${input.path}` })) - : Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}`, error })), - ), + const original = yield* ( + target.workspace + ? FileMutation.readScopedEditableText(target) + : FileMutation.readEditableText(target.environment.files, target.absolute) + ).pipe( + Effect.catchTag("Environment.NotFound", () => + Effect.fail(new ToolFailure({ message: `File not found: ${input.path}` })), + ), + Effect.catchTag("FileMutation.InvalidUtf8Error", (error) => + Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}: ${error.message}` })), + ), + Effect.catchTag("Environment.WrongKind", (error) => + error.actual === "directory" + ? Effect.fail(new ToolFailure({ message: `Path is a directory, not a file: ${input.path}` })) + : Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}`, error })), + ), + ) + const source = original.text + // Strings that differ only in \r ask to change line endings themselves, so they apply to the exact + // bytes. Every other edit matches the LF view Read shows the model and keeps the file's endings. + const endingsOnly = input.oldString.replaceAll("\r", "") === input.newString.replaceAll("\r", "") + const { matches, replace } = endingsOnly + ? { matches: findOccurrences(source, input.oldString), replace: () => input.newString } + : matchView(source, input.oldString, input.newString) + const replacements = matches.length + const replaced = (input.replaceAll === true ? matches : matches.slice(0, 1)) + .toReversed() + .reduce( + (content, match) => + `${content.slice(0, match.start)}${replace(match)}${content.slice(match.end)}`, + source, + ) + const preview = + replacements > 0 && (replacements === 1 || input.replaceAll === true) + ? fileDiff(target.resource, source, replaced) + : undefined + yield* fileWrite.authorize(target, context, preview) + if (replacements === 0) { + // The hint shows file contents, so only when reading this file is already allowed. + const readable = yield* permission.allows({ + action: "read", + resources: target.workspace?.resources ?? [target.resource], + save: ["*"], + ...Permission.invocation(context), + }) + const hint = readable ? missHint(source, input.oldString, input.newString) : undefined + return yield* new ToolFailure({ + message: `Could not find oldString in ${input.path}. It must match exactly, including whitespace and indentation.${hint ? `\n\n${hint}` : ""}`, + }) + } + if (replacements > 1 && input.replaceAll !== true) { + return yield* new ToolFailure({ + message: `Found ${replacements} matches for oldString, but expected exactly one. Add more surrounding context to make oldString unique, or set replaceAll to true to replace every occurrence.`, + }) + } + if (replaced === source) { + return yield* new ToolFailure({ + message: endingsOnly + ? `No changes to apply: ${input.path} already has those line endings.` + : `No changes to apply: the edit leaves ${input.path} unchanged. Line endings follow the file; to change them, write \\r explicitly in oldString or newString.`, + }) + } + const result = yield* fileWrite.commit(target, replaced) + if (target.workspace) + yield* permission.assertNotDenied({ + action: "read", + resources: target.workspace.resources, + ...Permission.invocation(context), + }) + const formatted = + result.formatted ?? + (target.workspace + ? (yield* FileMutation.readScopedEditableText(target)).text + : (yield* FileMutation.readText(target.environment.files, target.absolute)).text) + return { + output: `Edited ${result.resource} (${replacements} replacement${replacements === 1 ? "" : "s"})`, + metadata: { files: [fileDiff(result.resource, source, formatted)] }, + } + }), ) - const source = original.text - // Strings that differ only in \r ask to change line endings themselves, so they apply to the exact - // bytes. Every other edit matches the LF view Read shows the model and keeps the file's endings. - const endingsOnly = input.oldString.replaceAll("\r", "") === input.newString.replaceAll("\r", "") - const { matches, replace } = endingsOnly - ? { matches: findOccurrences(source, input.oldString), replace: () => input.newString } - : matchView(source, input.oldString, input.newString) - const replacements = matches.length - const replaced = (input.replaceAll === true ? matches : matches.slice(0, 1)) - .toReversed() - .reduce( - (content, match) => `${content.slice(0, match.start)}${replace(match)}${content.slice(match.end)}`, - source, - ) - const preview = - replacements > 0 && (replacements === 1 || input.replaceAll === true) - ? fileDiff(target.resource, source, replaced) - : undefined - yield* fileWrite.authorize(target, context, preview) - if (replacements === 0) { - // The hint shows file contents, so only when reading this file is already allowed. - const readable = yield* permission.allows({ - action: "read", - resources: [target.resource], - save: ["*"], - ...Permission.invocation(context), - }) - const hint = readable ? missHint(source, input.oldString, input.newString) : undefined - return yield* new ToolFailure({ - message: `Could not find oldString in ${input.path}. It must match exactly, including whitespace and indentation.${hint ? `\n\n${hint}` : ""}`, - }) - } - if (replacements > 1 && input.replaceAll !== true) { - return yield* new ToolFailure({ - message: `Found ${replacements} matches for oldString, but expected exactly one. Add more surrounding context to make oldString unique, or set replaceAll to true to replace every occurrence.`, - }) - } - if (replaced === source) { - return yield* new ToolFailure({ - message: endingsOnly - ? `No changes to apply: ${input.path} already has those line endings.` - : `No changes to apply: the edit leaves ${input.path} unchanged. Line endings follow the file; to change them, write \\r explicitly in oldString or newString.`, - }) - } - const result = yield* fileWrite.commit(target, replaced) - const formatted = - result.formatted ?? (yield* FileMutation.readText(target.environment.files, target.absolute)).text - return { - output: `Edited ${result.resource} (${replacements} replacement${replacements === 1 ? "" : "s"})`, - metadata: { files: [fileDiff(result.resource, source, formatted)] }, - } - }).pipe(fileMutation.withLock([input.path]), Effect.mapError(toolFailure(`Unable to edit ${input.path}`))) + }).pipe(Effect.mapError(toolFailure(`Unable to edit ${input.path}`))) }, }), ) diff --git a/packages/core/src/tool/plugin/glob.ts b/packages/core/src/tool/plugin/glob.ts index 97a16643ba57..61454026b312 100644 --- a/packages/core/src/tool/plugin/glob.ts +++ b/packages/core/src/tool/plugin/glob.ts @@ -12,6 +12,7 @@ import { FileAccess } from "../../file-access.js" import { Ripgrep } from "../../ripgrep.js" import { RelativePath } from "../../schema.js" import { Permission } from "../../permission.js" +import { ScopedSearch } from "../scoped-search.js" export const name = "glob" @@ -62,9 +63,16 @@ export const Plugin = { execute: (input, context) => Effect.gen(function* () { const searchPath = input.path === "undefined" || input.path === "null" ? undefined : input.path - const target = yield* access.resolve({ path: searchPath ?? ".", kind: "directory" }) + const requested = searchPath ?? "." + const target = yield* access.resolve({ path: requested, kind: "directory" }) yield* ToolSearch.available(target.environment) - yield* access.authorizeExternal([target], context) + const candidate = yield* access.scope(target, context, "read") + const scoped = candidate.workspace + ? yield* access.authorizeRead(requested, context, { workspaceScope: true }) + : candidate + if (candidate.workspace && !scoped.workspace) + return yield* new ToolFailure({ message: `Workspace assignment changed during search: ${requested}` }) + if (!candidate.workspace) yield* access.authorizeExternal([target], context) yield* permission.assert({ action: name, resources: [input.pattern], @@ -77,20 +85,41 @@ export const Plugin = { }, ...Permission.invocation(context), }) - const type = yield* ToolSearch.pathType(target.environment.files, target.absolute, searchPath ?? ".") + const type = scoped.workspace + ? "directory" + : yield* ToolSearch.pathType(target.environment.files, target.absolute, requested) if (type !== "directory") return yield* Effect.fail( new ToolFailure({ message: `Search path is not a directory: ${searchPath ?? "."}` }), ) const root = target.absolute - const result = yield* ToolSearch.bounded(input.limit ?? FileSystem.DEFAULT_SEARCH_LIMIT, (limit) => - ripgrep.glob({ + if (scoped.workspace) + yield* ripgrep.validateGlob({ environment: target.environment, - cwd: root, + cwd: path.dirname(scoped.workspace.absolute), pattern: input.pattern, - hidden: input.hidden, - limit, - }), + }) + const result = yield* ToolSearch.bounded(input.limit ?? FileSystem.DEFAULT_SEARCH_LIMIT, (limit) => + scoped.workspace + ? ScopedSearch.files({ + workspace: scoped.workspace, + requested, + context, + access, + limit, + hidden: input.hidden ?? false, + directoryOnly: true, + file: (relative) => ScopedSearch.matches(input.pattern, relative), + onFile: (_, relative) => + Effect.succeed([FileSystem.Entry.make({ path: RelativePath.make(relative), type: "file" })]), + }) + : ripgrep.glob({ + environment: target.environment, + cwd: root, + pattern: input.pattern, + hidden: input.hidden, + limit, + }), ) return { entries: result.items.map((entry) => diff --git a/packages/core/src/tool/plugin/grep.ts b/packages/core/src/tool/plugin/grep.ts index aeb32da493eb..8a3d9df8c22c 100644 --- a/packages/core/src/tool/plugin/grep.ts +++ b/packages/core/src/tool/plugin/grep.ts @@ -11,6 +11,7 @@ import { Permission } from "../../permission.js" import { Ripgrep } from "../../ripgrep.js" import { RelativePath } from "../../schema.js" import { ToolSearch } from "../search.js" +import { ScopedSearch } from "../scoped-search.js" export const name = "grep" @@ -80,9 +81,16 @@ export const Plugin = { output: Output, execute: (input, context) => Effect.gen(function* () { - const target = yield* access.resolve({ path: input.path ?? "." }) + const requested = input.path ?? "." + const target = yield* access.resolve({ path: requested }) yield* ToolSearch.available(target.environment) - yield* access.authorizeExternal([target], context) + const candidate = yield* access.scope(target, context, "read") + const scoped = candidate.workspace + ? yield* access.authorizeRead(requested, context, { workspaceScope: true }) + : candidate + if (candidate.workspace && !scoped.workspace) + return yield* new ToolFailure({ message: `Workspace assignment changed during search: ${requested}` }) + if (!candidate.workspace) yield* access.authorizeExternal([target], context) yield* permission.assert({ action: name, resources: [input.pattern], @@ -98,19 +106,49 @@ export const Plugin = { ...Permission.invocation(context), }) const root = target.absolute - const type = yield* ToolSearch.pathType(target.environment.files, root, input.path ?? ".") - const cwd = type === "directory" ? root : path.dirname(root) + const type = scoped.workspace + ? undefined + : yield* ToolSearch.pathType(target.environment.files, root, requested) + const cwd = type === "directory" ? root : path.dirname(scoped.workspace?.absolute ?? root) + const workspace = scoped.workspace + const include = input.include + if (workspace && include) + yield* ripgrep.validateGlob({ environment: target.environment, cwd, pattern: include }) const result = yield* ToolSearch.bounded(input.limit ?? FileSystem.DEFAULT_SEARCH_LIMIT, (limit) => - ripgrep.grep({ - environment: target.environment, - cwd, - pattern: input.pattern, - file: type === "file" ? path.basename(root) : undefined, - include: input.include, - literal: input.literal, - caseSensitive: input.caseSensitive, - limit, - }), + workspace + ? ScopedSearch.files({ + workspace, + requested, + context, + access, + limit, + hidden: true, + file: include ? (relative) => ScopedSearch.matches(include, relative) : undefined, + onBatch: (batch, remaining) => + ripgrep.grep({ + environment: target.environment, + cwd, + pattern: input.pattern, + files: batch.map(({ file, relative }) => ({ + path: `/proc/${process.pid}/fd/${file.fd}`, + display: path.resolve(root, relative), + })), + include: input.include, + literal: input.literal, + caseSensitive: input.caseSensitive, + limit: remaining, + }), + }) + : ripgrep.grep({ + environment: target.environment, + cwd, + pattern: input.pattern, + file: type === "file" ? path.basename(root) : undefined, + include: input.include, + literal: input.literal, + caseSensitive: input.caseSensitive, + limit, + }), ) return { matches: result.items.map((match) => diff --git a/packages/core/src/tool/plugin/patch.ts b/packages/core/src/tool/plugin/patch.ts index 9aff3a280952..aeff8f0372e4 100644 --- a/packages/core/src/tool/plugin/patch.ts +++ b/packages/core/src/tool/plugin/patch.ts @@ -12,6 +12,7 @@ import { toolFailure } from "../runtime.js" import { Environment } from "../../environment/index.js" import { Formatter } from "../../formatter.js" import { FileMutation } from "../../file-mutation.js" +import { FileWrite } from "../../file-write.js" import { FileAccess } from "../../file-access.js" import { Patch } from "@opencode/util/patch" import { Permission } from "../../permission.js" @@ -54,6 +55,7 @@ export const Plugin = { effect: Effect.fn("PatchTool.Plugin")(function* (ctx: Context) { const access = yield* FileAccess.Service const fileMutation = yield* FileMutation.Service + const fileWrite = yield* FileWrite.Service const formatter = yield* Formatter.Service const permission = yield* Permission.Service const config = yield* Config.Service @@ -94,7 +96,7 @@ export const Plugin = { message: `${operation}: ${errorMessage(error)}${completed.length ? `. Completed before failure: ${completed.join(", ")}` : ""}`, }) } - return Effect.gen(function* () { + const stock = Effect.gen(function* () { if (!input.patchText) return yield* new ToolFailure({ message: "patchText is required" }) const hunks = yield* Effect.fromResult(parsed).pipe( Effect.mapError((error) => new ToolFailure({ message: `patch verification failed: ${error.message}` })), @@ -106,6 +108,13 @@ export const Plugin = { const updates = new Map() const resolveTarget = Effect.fnUntraced(function* (value: string) { const target = yield* access.resolve({ path: value, kind: "file" }) + // The stock path uses pathname IO. A managed physical member takes the guarded add/update route below; + // delete, move, and mixed patches remain unavailable there. + if ((yield* access.scope(target, context, "write")).workspace) + return yield* new Environment.Failed({ + path: target.absolute, + cause: "Scoped patch mutation is unsupported", + }) if (!target.externalDirectory) return target yield* access.authorizeExternal([target], context, { filepath: target.absolute, @@ -300,6 +309,111 @@ export const Plugin = { metadata: { files }, } }).pipe(fileMutation.withLock(lockTargets), Effect.mapError(toolFailure("Unable to apply patch"))) + return Effect.gen(function* () { + if (!input.patchText || !Result.isSuccess(parsed) || parsed.success.length === 0) return yield* stock + const candidates = yield* Effect.forEach(parsed.success, (hunk) => + Effect.gen(function* () { + const target = yield* access.scope( + yield* access.resolve({ path: hunk.path, kind: "file" }), + context, + "write", + ) + const move = + hunk.type === "update" && hunk.movePath + ? yield* access.scope( + yield* access.resolve({ path: hunk.movePath, kind: "file" }), + context, + "write", + ) + : undefined + return { hunk, target, move } + }), + ) + if (!candidates.some((item) => item.target.workspace || item.move?.workspace)) return yield* stock + if (candidates.some((item) => !item.target.workspace || item.hunk.type === "delete" || item.move)) + return yield* new ToolFailure({ + message: "Scoped patch supports only add and update hunks within one managed workspace", + }) + if (new Set(candidates.map((item) => item.target.workspace!.root)).size !== 1) + return yield* new ToolFailure({ message: "Scoped patch cannot span managed workspaces" }) + return yield* fileMutation.withLock(candidates.map((item) => item.target.workspace!.absolute))( + Effect.gen(function* () { + const prepared: Prepared[] = [] + const staged = new Map() + for (const item of candidates) { + const target = yield* fileWrite.target(item.hunk.path, context) + if ( + !target.workspace || + target.workspace.root !== item.target.workspace!.root || + target.workspace.absolute !== item.target.workspace!.absolute + ) + return yield* new Environment.Failed({ + path: target.absolute, + cause: "Workspace assignment changed", + }) + const file = FileAccess.key({ ...target, absolute: target.workspace.absolute }) + yield* permission.assertNotDenied({ + action: "read", + resources: target.workspace.resources, + ...Permission.invocation(context), + }) + if (item.hunk.type === "add") { + const content = + item.hunk.contents.endsWith("\n") || item.hunk.contents === "" + ? item.hunk.contents + : `${item.hunk.contents}\n` + prepared.push({ ...item.hunk, target, content, before: "", after: Bom.split(content).text }) + staged.set(file, content) + continue + } + if (item.hunk.type !== "update") + return yield* new ToolFailure({ message: "Scoped patch deletion is unsupported" }) + const hunk = item.hunk + const original = + staged.get(file) ?? + (yield* Effect.gen(function* () { + const current = yield* FileMutation.readScopedEditableText(target) + return Bom.join(current.text, current.bom) + })) + const update = yield* Effect.try({ + try: () => Patch.derive(hunk.path, hunk.chunks, original), + catch: (error) => + new ToolFailure({ message: `patch verification failed: ${errorMessage(error)}` }), + }) + const content = Patch.joinBom(update.content, update.bom) + prepared.push({ ...hunk, target, content, before: Bom.split(original).text, after: update.content }) + staged.set(file, content) + } + const patchFiles = prepared.map((change) => patchFile(change)) + const resources = [...new Set(prepared.flatMap((change) => change.target.workspace!.resources))] + yield* permission.assert({ + action: "edit", + resources, + metadata: { + filepath: prepared.map((change) => change.target.resource).join(", "), + diff: patchFiles.map((file) => `${file.patch}\n`).join(""), + files: patchFiles, + }, + ...Permission.invocation(context), + }) + for (const change of prepared) { + if (change.type === "delete") continue + yield* FileMutation.writeScopedExactText(change.target, change.content).pipe( + Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)), + ) + completed.push(change.target.resource) + } + return { + output: {}, + content: [ + "Success. Updated the following files:", + ...patchFiles.map((file) => `${file.status === "added" ? "A" : "M"} ${file.file}`), + ].join("\n"), + metadata: { files: patchFiles }, + } + }), + ) + }).pipe(Effect.mapError(toolFailure("Unable to apply patch"))) }, }), ) diff --git a/packages/core/src/tool/plugin/read.ts b/packages/core/src/tool/plugin/read.ts index a80cacacf66a..2743d29aaec3 100644 --- a/packages/core/src/tool/plugin/read.ts +++ b/packages/core/src/tool/plugin/read.ts @@ -124,22 +124,27 @@ export const Plugin = { return { output, path: input.path } } + const page = { offset: input.offset, limit: input.limit } const read = (target: FileAccess.Target) => - ReadToolFileSystem.read(target.environment.files, target.absolute, target.resource, { - offset: input.offset, - limit: input.limit, - }) + target.workspace + ? ReadToolFileSystem.readWorkspace(target.workspace, target.absolute, target.resource, page) + : ReadToolFileSystem.read(target.environment.files, target.absolute, target.resource, page) - const requested = yield* access.authorizeRead(input.path, context) + const requested = yield* access.authorizeRead(input.path, context, { workspaceScope: true }) const result = yield* read(requested).pipe( Effect.map((content) => ({ content, target: requested, path: input.path })), Effect.catchIf( (error) => error instanceof Environment.NotFound, () => Effect.gen(function* () { + if (requested.workspace) + return yield* new ToolFailure({ message: `File not found: ${input.path}` }) const alternate = yield* alternatePath(requested).pipe(Effect.orElseSucceed(() => undefined)) if (!alternate) return yield* missing({ input: input.path, requested, context }) - const target = yield* access.authorizeRead(alternate, context, { siblingOf: requested }) + const target = yield* access.authorizeRead(alternate, context, { + siblingOf: requested, + workspaceScope: true, + }) const content = yield* read(target).pipe( Effect.catchIf( (error) => error instanceof Environment.NotFound, @@ -161,7 +166,7 @@ export const Plugin = { // is discovered); for a file it starts at the file's dirname. External reads are // skipped, and discovery failures never fail the read. yield* Effect.gen(function* () { - if (result.target.externalDirectory !== undefined) return + if (result.target.externalDirectory !== undefined || result.target.workspace) return // Discovery walks this server's files, so it follows only a target on the Location's own environment. // A cwd on a paired machine brings its instructions with it in a later change. if (result.target.environment.id !== environment.id) return diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 09871a72de3e..7eeca3ae3158 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -340,11 +340,22 @@ export const Plugin = { kind: "directory", }) invocation.cwd = target.absolute + const scoped = yield* access.scope(target, context, "shell-cwd") + if (scoped.workspace) { + const physical = yield* access.resolve({ path: scoped.workspace.absolute, kind: "directory" }) + const external = FileAccess.externalDirectoryRequest([scoped, physical]) + if (external) yield* permission.assertNotDenied({ ...external, ...Permission.invocation(context) }) + yield* permission.assertNotDenied({ + action: "read", + resources: scoped.workspace.resources, + ...Permission.invocation(context), + }) + } const timeout = invocation.timeout const requests = yield* ShellPermissions.requests(access, { command: invocation.command, program: invocation.shell, - target, + target: scoped, policy: Effect.gen(function* () { const session = yield* sessions.get(context.sessionID) const agent = yield* agents.resolve(context.agent) @@ -357,6 +368,10 @@ export const Plugin = { { discard: true }, ) // Approval can outlive the directory, so validate immediately before spawning. + if (scoped.workspace) { + yield* scoped.workspace.verify() + return { timeout, workspace: scoped.workspace } + } const workdir = yield* Environment.typeFollowing(target.environment.files, target.absolute).pipe( Effect.catchTag("Environment.NotFound", () => Effect.fail( @@ -370,7 +385,7 @@ export const Plugin = { ) if (workdir !== "directory") return yield* Effect.fail(new Error(`Working directory is not a directory: ${target.absolute}`)) - return timeout + return { timeout, workspace: undefined } }) // Not in this Location's scope: a daemon command outlives a Location that closes while the server runs, and @@ -498,11 +513,13 @@ export const Plugin = { invocation.env.AI_AGENT ||= "opencode" invocation.env.OPENCODE_SESSION_ID = context.sessionID // Asking for permission can take a while; a stop then ends the call before any command starts. - finalTimeout = yield* restore( + const prepared = yield* restore( Effect.raceFirst(prepare(invocation, context, { cwd, target }), stoppedBeforeStart), ) + finalTimeout = prepared.timeout // A foreground timeout moves the command to the background instead of stopping it. if (timeoutBackgrounds) invocation.timeout = 0 + return prepared.workspace }), ) yield* context.progress({ shellID: info.id }) diff --git a/packages/core/src/tool/read-filesystem.ts b/packages/core/src/tool/read-filesystem.ts index 3c3ab2403c98..6fa14c5fe903 100644 --- a/packages/core/src/tool/read-filesystem.ts +++ b/packages/core/src/tool/read-filesystem.ts @@ -6,6 +6,8 @@ import { TextBoundary } from "@opencode/util/text-boundary" import { Effect, Schema } from "effect" import { Environment } from "../environment/index.js" import type { Files } from "../environment/index.js" +import { openWorkspaceEntry } from "../environment/guarded-read.js" +import type { FileAccess } from "../file-access.js" import { Mime } from "../mime.js" import { AbsolutePath, NonNegativeInt, PositiveInt } from "../schema.js" @@ -108,7 +110,7 @@ export type Output = typeof Output.Type export type Media = MediaContent & { readonly name: string; readonly bytes: Uint8Array } export const read = Effect.fn("ReadTool.read")(function* ( - files: Files, + files: Pick, input: AbsolutePath, resource: string, page: PageInput = {}, @@ -160,8 +162,76 @@ export const read = Effect.fn("ReadTool.read")(function* ( return yield* textPage(files, input, resource, first, page) }) +export const readWorkspace = ( + workspace: FileAccess.WorkspaceTarget, + input: AbsolutePath, + resource: string, + page: PageInput, +) => { + const attempt = (operation: () => Promise) => + Effect.tryPromise({ + try: operation, + catch: (cause) => + typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT" + ? new Environment.NotFound({ path: input }) + : new Environment.Failed({ path: input, cause }), + }) + + return Effect.acquireUseRelease( + workspace + .verify() + .pipe(Effect.flatMap(() => attempt(() => openWorkspaceEntry(workspace.root, workspace.relative)))), + (entry) => + Effect.gen(function* () { + if (entry.type === "file") { + const { file } = entry + return yield* read( + { + list: () => + Effect.fail(new Environment.Failed({ path: input, cause: "Expected a regular workspace file" })), + read: (_, range) => + attempt(async () => { + const stat = await file.stat() + if (range === undefined && stat.size > MAX_MEDIA_INGEST_BYTES) + throw new Error("Workspace file grew beyond the read limit") + const offset = range?.offset ?? 0 + const size = Math.max(0, stat.size - offset) + const buffer = Buffer.alloc(Math.min(range?.length ?? size, size)) + const { bytesRead } = await file.read(buffer, 0, buffer.length, offset) + return { + info: { type: "file", size: stat.size, mtimeMs: stat.mtimeMs }, + bytes: buffer.subarray(0, bytesRead), + } + }), + }, + input, + resource, + page, + ) + } + if (page.offset !== undefined && page.offset < 0) return yield* new DirectoryOffsetError({ resource }) + const entries = yield* attempt(() => entry.directory.readEntries()) + return list( + entries.map((entry) => ({ + name: entry.name, + type: entry.isDirectory() + ? "directory" + : entry.isFile() + ? "file" + : entry.isSymbolicLink() + ? "symlink" + : "other", + })), + page, + path.sep, + ) + }), + (entry) => attempt(() => (entry.type === "file" ? entry.file : entry.directory).close()).pipe(Effect.ignore), + ) +} + const readFile = ( - files: Files, + files: Pick, input: AbsolutePath, resource: string, range?: { readonly offset: number; readonly length: number }, @@ -176,7 +246,7 @@ const readFile = ( type Checkpoint = { byte: number; length: number; firstLine: number; start: number; lastLine: number } const textPage = Effect.fnUntraced(function* ( - files: Files, + files: Pick, input: AbsolutePath, resource: string, first: { bytes: Uint8Array; info: { size: number } }, diff --git a/packages/core/src/tool/scoped-search.ts b/packages/core/src/tool/scoped-search.ts new file mode 100644 index 000000000000..00fec7662aae --- /dev/null +++ b/packages/core/src/tool/scoped-search.ts @@ -0,0 +1,119 @@ +export * as ScopedSearch from "./scoped-search.js" + +import { Effect } from "effect" +import type { FileHandle } from "node:fs/promises" +import path from "path" +import { ToolFailure } from "@opencode/ai/effect" +import { Glob } from "@opencode/util/glob" +import { openWorkspaceEntry } from "../environment/guarded-read.js" +import { FileAccess } from "../file-access.js" + +// Descriptor traversal is deliberately bounded independently of the result limit. +const MAX_INSPECTED_ENTRIES = 20_000 +export const BATCH_SIZE = 32 + +export const matches = (pattern: string, relative: string) => + Glob.match(pattern, relative) || (!pattern.includes("/") && Glob.match(pattern, path.posix.basename(relative))) + +export const files = (input: { + readonly workspace: FileAccess.WorkspaceTarget + readonly requested: string + readonly context: FileAccess.Invocation + readonly access: FileAccess.Interface + readonly limit: number + readonly hidden: boolean + readonly directoryOnly?: boolean + readonly file?: (relative: string) => boolean + readonly onFile?: (file: FileHandle, relative: string, remaining: number) => Effect.Effect + readonly onBatch?: ( + batch: readonly { readonly file: FileHandle; readonly relative: string }[], + remaining: number, + ) => Effect.Effect +}) => + Effect.gen(function* () { + const found: A[] = [] + const pending: { file: FileHandle; relative: string }[] = [] + let inspected = 0 + + const flush = Effect.gen(function* () { + if (!input.onBatch || pending.length === 0) return + yield* input.workspace.verify() + const matches = yield* input.onBatch(pending, input.limit - found.length) + found.push(...matches) + yield* Effect.promise(() => Promise.allSettled(pending.map((entry) => entry.file.close()))) + pending.length = 0 + }) + + const visit = (relative: string): Effect.Effect => + Effect.gen(function* () { + const selected = relative + ? yield* input.access.authorizeRead(path.join(input.requested, relative), input.context, { + workspaceScope: true, + }) + : undefined + const workspace = selected?.workspace ?? input.workspace + const expected = path.join(input.workspace.root, input.workspace.relative, relative) + if ( + (selected && !selected.workspace) || + workspace.root !== input.workspace.root || + workspace.absolute !== expected + ) + return yield* new ToolFailure({ message: "Workspace assignment changed during search" }) + let retained = false + yield* Effect.acquireUseRelease( + Effect.gen(function* () { + yield* workspace.verify() + return yield* Effect.tryPromise(() => + openWorkspaceEntry( + input.workspace.root, + relative ? path.posix.join(input.workspace.relative, relative) : input.workspace.relative, + ), + ) + }), + (opened) => + Effect.gen(function* () { + if (opened.type === "file") { + if (!relative && input.directoryOnly) + return yield* new ToolFailure({ message: `Search path is not a directory: ${input.requested}` }) + if (relative && input.file && !input.file(relative)) return + if (input.onBatch) { + retained = true + pending.push({ file: opened.file, relative }) + if (pending.length === BATCH_SIZE) yield* flush + return + } + if (!input.onFile) return yield* new ToolFailure({ message: "Scoped search has no file consumer" }) + found.push(...(yield* input.onFile(opened.file, relative, input.limit - found.length))) + return + } + for (const child of yield* Effect.tryPromise(() => opened.directory.readEntries())) { + if (found.length >= input.limit) break + if (child.name === ".git" || (!input.hidden && child.name.startsWith("."))) continue + if (!child.isDirectory() && !child.isFile()) continue + const next = relative ? path.posix.join(relative, child.name) : child.name + if (child.isFile() && input.file && !input.file(next)) continue + if (++inspected > MAX_INSPECTED_ENTRIES) + return yield* new ToolFailure({ + message: `Scoped search inspected more than ${MAX_INSPECTED_ENTRIES} entries. Narrow the search path.`, + }) + yield* visit(next) + } + }), + (opened) => + retained + ? Effect.void + : Effect.promise(() => (opened.type === "file" ? opened.file : opened.directory).close()), + ) + }) + + return yield* Effect.acquireUseRelease( + Effect.void, + () => + Effect.gen(function* () { + yield* visit("") + yield* flush + return found + }), + () => Effect.promise(() => Promise.allSettled(pending.map((entry) => entry.file.close()))), + ) + }) diff --git a/packages/core/test/codemode-script-diffs.test.ts b/packages/core/test/codemode-script-diffs.test.ts index bf8fb9aca1f9..7afa83a39128 100644 --- a/packages/core/test/codemode-script-diffs.test.ts +++ b/packages/core/test/codemode-script-diffs.test.ts @@ -58,6 +58,7 @@ const patchNode = makeLocationNode({ Tool.node, FileAccess.node, FileMutation.node, + FileWrite.node, Environment.node, Formatter.node, Location.node, diff --git a/packages/core/test/environment/guarded-mutation.test.ts b/packages/core/test/environment/guarded-mutation.test.ts new file mode 100644 index 000000000000..6e1e7e619531 --- /dev/null +++ b/packages/core/test/environment/guarded-mutation.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, test } from "bun:test" +import fs from "node:fs/promises" +import path from "node:path" +import { tmpdir } from "../fixture/tmpdir" +import { readWorkspaceBytes, replaceWorkspaceFile } from "../../src/environment/guarded-mutation" + +describe.skipIf(process.platform !== "linux")("guarded workspace mutation", () => { + test("creates parents and atomically replaces an existing file", async () => { + await using directory = await tmpdir() + const first = await replaceWorkspaceFile( + directory.path, + "nested/file.txt", + new TextEncoder().encode("first"), + async () => {}, + ) + expect(first.existed).toBe(false) + expect((await fs.stat(path.join(directory.path, "nested/file.txt"))).mode & 0o777).toBe(0o666 & ~process.umask()) + const second = await replaceWorkspaceFile( + directory.path, + "nested/file.txt", + new TextEncoder().encode("second"), + async () => {}, + ) + expect(second.existed).toBe(true) + expect(new TextDecoder().decode(await readWorkspaceBytes(directory.path, "nested/file.txt"))).toBe("second") + await fs.chmod(path.join(directory.path, "nested/file.txt"), 0o755) + await replaceWorkspaceFile(directory.path, "nested/file.txt", new TextEncoder().encode("third"), async () => {}) + expect((await fs.stat(path.join(directory.path, "nested/file.txt"))).mode & 0o777).toBe(0o755) + }) + + test("refuses symlink traversal and leaves an outside file unchanged", async () => { + await using directory = await tmpdir() + await using outside = await tmpdir() + await fs.writeFile(path.join(outside.path, "victim"), "safe") + await fs.symlink(outside.path, path.join(directory.path, "alias")) + await expect( + replaceWorkspaceFile(directory.path, "alias/victim", new TextEncoder().encode("changed"), async () => {}), + ).rejects.toThrow() + expect(await fs.readFile(path.join(outside.path, "victim"), "utf8")).toBe("safe") + }) + + test("refuses hardlinked existing files without mutating their inode", async () => { + await using directory = await tmpdir() + await using outside = await tmpdir() + await fs.writeFile(path.join(outside.path, "victim"), "safe") + await fs.link(path.join(outside.path, "victim"), path.join(directory.path, "linked")) + await expect( + replaceWorkspaceFile(directory.path, "linked", new TextEncoder().encode("changed"), async () => {}), + ).rejects.toThrow() + expect(await fs.readFile(path.join(outside.path, "victim"), "utf8")).toBe("safe") + }) + + test("refuses Git metadata paths", async () => { + await using directory = await tmpdir() + await expect( + replaceWorkspaceFile(directory.path, ".git/config", new TextEncoder().encode("changed"), async () => {}), + ).rejects.toThrow() + await expect(fs.stat(path.join(directory.path, ".git"))).rejects.toThrow() + }) + + test("revoked assignment creates no parent directory", async () => { + await using directory = await tmpdir() + await expect( + replaceWorkspaceFile(directory.path, "nested/new.txt", new TextEncoder().encode("changed"), async () => { + throw new Error("assignment revoked") + }), + ).rejects.toThrow("assignment revoked") + await expect(fs.stat(path.join(directory.path, "nested"))).rejects.toThrow() + }) +}) diff --git a/packages/core/test/environment/guarded-read.test.ts b/packages/core/test/environment/guarded-read.test.ts new file mode 100644 index 000000000000..7fa80b6ede1d --- /dev/null +++ b/packages/core/test/environment/guarded-read.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, test } from "bun:test" +import { mkdir, rename, symlink, writeFile } from "node:fs/promises" +import { join } from "node:path" +import { openWorkspaceDirectory, openWorkspaceFile } from "../../src/environment/guarded-read" +import { tmpdir } from "../fixture/tmpdir" + +describe.skipIf(process.platform !== "linux")("openWorkspaceFile", () => { + test("opens an ordinary nested file", async () => { + await using tmp = await tmpdir() + await mkdir(join(tmp.path, "nested")) + await writeFile(join(tmp.path, "nested", "file.txt"), "hello") + + const file = await openWorkspaceFile(tmp.path, "nested/file.txt") + try { + expect(await file.readFile({ encoding: "utf8" })).toBe("hello") + } finally { + await file.close() + } + }) + + test("rejects symlinks in parent and leaf segments", async () => { + await using tmp = await tmpdir() + await mkdir(join(tmp.path, "actual")) + await writeFile(join(tmp.path, "actual", "file.txt"), "hello") + await symlink("actual", join(tmp.path, "linked-directory")) + await symlink("actual/file.txt", join(tmp.path, "linked-file")) + + await expect(openWorkspaceFile(tmp.path, "linked-directory/file.txt")).rejects.toThrow() + await expect(openWorkspaceFile(tmp.path, "linked-file")).rejects.toThrow() + }) + + test("rejects directories, missing files, and invalid relative paths", async () => { + await using tmp = await tmpdir() + await mkdir(join(tmp.path, "directory")) + + await expect(openWorkspaceFile(tmp.path, "directory")).rejects.toThrow("not a regular file") + await expect(openWorkspaceFile(tmp.path, "missing")).rejects.toThrow() + for (const relative of ["", "/directory", "directory/", "directory//file", ".", "../file", "directory/../file"]) { + await expect(openWorkspaceFile(tmp.path, relative)).rejects.toThrow("relative child segments") + } + }) + + test("requires a canonical physical root", async () => { + await using tmp = await tmpdir() + await writeFile(join(tmp.path, "file.txt"), "hello") + await symlink(".", join(tmp.path, "root-link")) + + await expect(openWorkspaceFile(join(tmp.path, "root-link"), "file.txt")).rejects.toThrow("canonical") + await expect(openWorkspaceFile(`${tmp.path}/`, "file.txt")).rejects.toThrow("canonical") + }) +}) + +describe.skipIf(process.platform !== "linux")("openWorkspaceDirectory", () => { + test("enumerates the root and a nested directory through retained descriptors", async () => { + await using tmp = await tmpdir() + await mkdir(join(tmp.path, "nested")) + await writeFile(join(tmp.path, "nested", "file.txt"), "hello") + await symlink("nested", join(tmp.path, "linked")) + + const root = await openWorkspaceDirectory(tmp.path, "") + const nested = await openWorkspaceDirectory(tmp.path, "nested") + try { + expect((await root.readEntries()).map((entry) => [entry.name, entry.isSymbolicLink()])).toEqual([ + ["linked", true], + ["nested", false], + ]) + expect((await nested.readEntries()).map((entry) => entry.name)).toEqual(["file.txt"]) + expect(nested.childPath).toMatch(new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`)) + const child = Bun.spawn([process.execPath, "-e", "console.log(require('node:fs').readdirSync(process.argv[1]).join(','))", nested.childPath], { + stdout: "pipe", + }) + expect(await new Response(child.stdout).text()).toBe("file.txt\n") + expect(await child.exited).toBe(0) + } finally { + await nested.close() + await root.close() + } + await expect(nested.readEntries()).rejects.toThrow("closed") + }) + + test("rejects symlink traversal, malformed paths, and noncanonical roots", async () => { + await using tmp = await tmpdir() + await mkdir(join(tmp.path, "actual")) + await symlink("actual", join(tmp.path, "linked")) + + await expect(openWorkspaceDirectory(tmp.path, "linked")).rejects.toThrow() + for (const relative of ["/actual", "actual/", "actual//child", ".", "..", "actual/../child", "actual\0bad"]) { + await expect(openWorkspaceDirectory(tmp.path, relative)).rejects.toThrow("relative child segments") + } + await expect(openWorkspaceDirectory(`${tmp.path}/`, "")).rejects.toThrow("canonical") + await expect(openWorkspaceDirectory(join(tmp.path, "linked"), "")).rejects.toThrow("canonical") + }) + + test("rejects enumeration after the opened directory moves", async () => { + await using tmp = await tmpdir() + await mkdir(join(tmp.path, "nested")) + const directory = await openWorkspaceDirectory(tmp.path, "nested") + try { + await rename(join(tmp.path, "nested"), join(tmp.path, "moved")) + await expect(directory.readEntries()).rejects.toThrow("changed during open") + } finally { + await directory.close() + } + }) +}) + +test.skipIf(process.platform === "linux")("guarded reads fail closed without Linux proc fds", async () => { + await using tmp = await tmpdir() + await writeFile(join(tmp.path, "file.txt"), "hello") + await expect(openWorkspaceFile(tmp.path, "file.txt")).rejects.toThrow("require Linux") +}) diff --git a/packages/core/test/file-access.test.ts b/packages/core/test/file-access.test.ts index 7d7497b434f9..77babdb2dcd9 100644 --- a/packages/core/test/file-access.test.ts +++ b/packages/core/test/file-access.test.ts @@ -3,13 +3,16 @@ import fs from "fs/promises" import path from "path" import { Effect } from "effect" import { FileAccess } from "@opencode/core/file-access" +import { Flag } from "@opencode/core/flag" import { Location } from "@opencode/core/location" import { Permission } from "@opencode/core/permission" +import { PluginHooks } from "@opencode/core/plugin/hooks" import { Session } from "@opencode/core/session" import { Tool } from "@opencode/core/tool" import { AbsolutePath } from "@opencode/core/schema" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { LayerNode } from "@opencode/util/effect/layer-node" +import { ReadToolFileSystem } from "../src/tool/read-filesystem" import { tempLocationLayer } from "./fixture/location" import { tmpdirScoped } from "./fixture/tmpdir" import { it } from "./lib/effect" @@ -23,12 +26,19 @@ const invocation = { } const slash = (file: string) => file.replaceAll("\\", "/") -function provide(requests: Permission.AssertInput[], denied?: string) { +function provide(requests: Permission.AssertInput[], denied?: string, flags?: string, deniedBoundary?: string) { return Effect.provide( - AppNodeBuilder.build(LayerNode.group([FileAccess.node, Location.node]), [ + AppNodeBuilder.build(LayerNode.group([FileAccess.node, Location.node, PluginHooks.node]), [ Location.node.replace(tempLocationLayer), + ...(flags ? [Flag.node.replace(Flag.testLayer([], { overrides: flags }))] : []), Permission.node.replace( permissionLayer({ + assertNotDenied: (input) => + deniedBoundary && input.resources.some((resource) => resource.endsWith(deniedBoundary)) + ? Effect.fail( + new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources }), + ) + : Effect.void, assert: (input) => Effect.gen(function* () { requests.push(input) @@ -46,6 +56,119 @@ function provide(requests: Permission.AssertInput[], denied?: string) { } describe("FileAccess.authorizeRead", () => { + // The guarded file uses Linux descriptor-relative traversal. + const scopedRead = process.platform === "linux" ? it.live : it.live.skip + + scopedRead("scopes a physical file to its native session and revalidates before reading", () => { + const requests: Permission.AssertInput[] = [] + return Effect.gen(function* () { + const access = yield* FileAccess.Service + const hooks = yield* PluginHooks.Service + const location = yield* Location.Service + const physical = yield* tmpdirScoped() + const file = path.join(physical.path, "scope.txt") + yield* Effect.promise(() => fs.writeFile(file, "bound workspace content")) + const logical = path.join(location.directory, "member") + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => { + if (event.sessionID === invocation.sessionID && event.directory === location.directory) + event.scopes.push({ members: [{ physical: physical.path, logical }] }) + }), + ) + const target = yield* access.authorizeRead(file, invocation, { workspaceScope: true }) + if (!target.workspace) throw new Error("Expected a guarded file") + expect(requests).toMatchObject([{ action: "read", resources: ["member/scope.txt", file] }]) + expect(requests[0]?.verifiedWorkspace).toBe(true) + expect(requests[0].save).toBeUndefined() + const output = yield* ReadToolFileSystem.readWorkspace(target.workspace, target.absolute, target.resource, {}) + expect(output).toMatchObject({ type: "text", content: "bound workspace content" }) + + yield* access.authorizeRead( + file, + { ...invocation, sessionID: Session.ID.make("ses_other") }, + { workspaceScope: true }, + ) + expect(requests.map((request) => request.action)).toEqual(["read", "external_directory", "read"]) + expect(requests[2]?.verifiedWorkspace).toBeUndefined() + + const nested = path.join(physical.path, "nested") + yield* Effect.promise(() => fs.mkdir(nested)) + yield* Effect.promise(() => fs.mkdir(path.join(nested, "subdirectory"))) + yield* Effect.promise(() => fs.writeFile(path.join(nested, "regular.txt"), "example")) + yield* Effect.promise(() => fs.symlink("regular.txt", path.join(nested, "alias"))) + const directory = yield* access.authorizeRead(nested, invocation, { workspaceScope: true }) + if (!directory.workspace) throw new Error("Expected a guarded directory") + expect(requests.at(-1)?.action).toBe("read") + const listing = yield* ReadToolFileSystem.readWorkspace( + directory.workspace, + directory.absolute, + directory.resource, + {}, + ) + expect(listing).toMatchObject({ type: "directory", entries: ["subdirectory/", "alias", "regular.txt"] }) + const logicalDirectory = yield* access.authorizeRead(path.join(logical, "nested"), invocation, { + workspaceScope: true, + }) + expect(logicalDirectory.workspace?.absolute).toBe(AbsolutePath.make(nested)) + + const outside = yield* tmpdirScoped() + const outsideFile = path.join(outside.path, "outside.txt") + yield* Effect.promise(() => fs.writeFile(outsideFile, "outside workspace")) + yield* Effect.promise(() => fs.rename(file, path.join(physical.path, "original.txt"))) + yield* Effect.promise(() => fs.symlink(outsideFile, file)) + const changed = yield* ReadToolFileSystem.readWorkspace( + target.workspace, + target.absolute, + target.resource, + {}, + ).pipe(Effect.flip) + expect(changed._tag).toBe("Environment.Failed") + + const missing = yield* access.authorizeRead(path.join(logical, "missing"), invocation, { workspaceScope: true }) + if (!missing.workspace) throw new Error("Expected a guarded file target") + const absent = yield* ReadToolFileSystem.readWorkspace( + missing.workspace, + missing.absolute, + missing.resource, + {}, + ).pipe(Effect.flip) + expect(absent._tag).toBe("Environment.NotFound") + + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => { + event.scopes.push(null) + }), + ) + const rejected = yield* ReadToolFileSystem.readWorkspace( + target.workspace, + target.absolute, + target.resource, + {}, + ).pipe(Effect.flip) + expect(rejected).toMatchObject({ _tag: "Environment.Failed", cause: "Unverified workspace assignment" }) + }).pipe(provide(requests, undefined, "workspace_read_scope")) + }) + + scopedRead("checks the native external deny when a logical path maps to a physical member", () => { + const requests: Permission.AssertInput[] = [] + return Effect.gen(function* () { + const access = yield* FileAccess.Service + const hooks = yield* PluginHooks.Service + const location = yield* Location.Service + const directory = yield* tmpdirScoped() + const physical = path.join(directory.path, "blocked-capsule") + const logical = path.join(location.directory, "member") + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => void event.scopes.push({ members: [{ logical, physical }] })), + ) + const blocked = yield* access + .authorizeRead(path.join(logical, "file.txt"), invocation, { workspaceScope: true }) + .pipe(Effect.flip) + expect(blocked._tag).toBe("Permission.BlockedError") + expect(requests).toEqual([]) + }).pipe(provide(requests, undefined, "workspace_read_scope", "/blocked-capsule/*")) + }) + it.live("returns an absolute target and preserves invocation identity on the read assertion", () => { const requests: Permission.AssertInput[] = [] return Effect.gen(function* () { @@ -176,3 +299,33 @@ describe("FileAccess.authorizeRead", () => { }).pipe(provide(requests)) }) }) + +describe("FileAccess.scope write", () => { + const scopedWrite = process.platform === "linux" ? it.live : it.live.skip + + scopedWrite("returns physical identity and denies protected descendants", () => + Effect.gen(function* () { + const access = yield* FileAccess.Service + const hooks = yield* PluginHooks.Service + const location = yield* Location.Service + const physical = yield* tmpdirScoped() + const logical = path.join(location.directory, "member") + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => { + if (event.action === "write") + event.scopes.push({ members: [{ physical: physical.path, logical, protectedPaths: [".git"] }] }) + }), + ) + const allowed = yield* access.scope( + yield* access.resolve({ path: path.join(logical, "file.txt") }), + invocation, + "write", + ) + expect(allowed.workspace?.absolute).toBe(AbsolutePath.make(path.join(physical.path, "file.txt"))) + const denied = yield* access + .scope(yield* access.resolve({ path: path.join(logical, ".git", "config") }), invocation, "write") + .pipe(Effect.flip) + expect(denied).toMatchObject({ _tag: "Environment.Failed", cause: "Protected workspace path" }) + }).pipe(provide([], undefined, "workspace_read_scope")), + ) +}) diff --git a/packages/core/test/filesystem/search.test.ts b/packages/core/test/filesystem/search.test.ts index 6db3e2e39b4a..7086a752fcb8 100644 --- a/packages/core/test/filesystem/search.test.ts +++ b/packages/core/test/filesystem/search.test.ts @@ -21,6 +21,7 @@ const ripgrepStub = (entry: string, onFind: (input: Ripgrep.FindInput) => void) Layer.succeed( Ripgrep.Service, Ripgrep.Service.of({ + validateGlob: () => Effect.void, find: (input) => Effect.gen(function* () { onFind(input) @@ -285,6 +286,7 @@ describe("FileSystemSearch", () => { Layer.succeed( Ripgrep.Service, Ripgrep.Service.of({ + validateGlob: () => Effect.void, find: (input) => Effect.gen(function* () { scans++ @@ -354,6 +356,7 @@ describe("FileSystemSearch", () => { Layer.succeed( Ripgrep.Service, Ripgrep.Service.of({ + validateGlob: () => Effect.void, find: (input) => Effect.gen(function* () { scans++ diff --git a/packages/core/test/permission.test.ts b/packages/core/test/permission.test.ts index 0dd03eaacd3a..5e998e62ac48 100644 --- a/packages/core/test/permission.test.ts +++ b/packages/core/test/permission.test.ts @@ -122,6 +122,25 @@ test("Permission.site saves a web URL's site as written, and only the URL itself expect(Permission.site(url)).toEqual([]) }) +it.live("honors a native read denial on either resource in a two-alias check", () => + Effect.gen(function* () { + const logical = "member/.env" + const physical = "/workspace/physical/.env" + const allowed = { action: "read", resource: "*", effect: "allow" } as const + yield* setup([allowed]) + const permission = yield* Permission.Service + const input = assertion({ resources: [logical, physical] }) + yield* permission.assert(input) + + for (const resource of [logical, physical, "*"]) { + yield* setRules([allowed, { action: "read", resource, effect: "deny" }]) + const rejected = yield* permission.assert(input).pipe(Effect.flip) + expect(rejected).toBeInstanceOf(Permission.BlockedError) + expect(yield* permission.list()).toHaveLength(0) + } + }), +) + describe("Permission.isActionDenied", () => { const rule = (action: string, resource: string, effect: Permission.Rule["effect"]): Permission.Rule => ({ action, @@ -265,6 +284,33 @@ describe("Permission.isActionDenied", () => { }) describe("Permission", () => { + it.effect("keeps verified workspace provenance in evaluation and configured denies first", () => + Effect.gen(function* () { + yield* setup([{ action: "read", resource: "*", effect: "deny" }]) + const service = yield* Permission.Service + const hooks = yield* PluginHooks.Service + const seen: Array = [] + yield* hooks.register("permission", "evaluate", (event) => + Effect.sync(() => { + seen.push(event.verifiedWorkspace) + }), + ) + const denied = yield* service.assert(assertion({ verifiedWorkspace: true })).pipe(Effect.flip) + expect(denied).toBeInstanceOf(Permission.BlockedError) + expect(seen).toEqual([]) + yield* setRules([{ action: "read", resource: "*", effect: "allow" }]) + yield* service.assert(assertion({ verifiedWorkspace: true })) + yield* service.assert(assertion({ id: Permission.ID.create("per_plain") })) + expect(seen).toEqual([true, undefined]) + yield* setRules([]) + const request = yield* service.ask( + assertion({ id: Permission.ID.create("per_guarded"), verifiedWorkspace: true }), + ) + expect(request.effect).toBe("ask") + expect(yield* service.get(request.id)).not.toHaveProperty("verifiedWorkspace") + }), + ) + it.effect("returns the evaluated effect and only queues prompts", () => Effect.gen(function* () { yield* setup([{ action: "read", resource: "*", effect: "allow" }]) diff --git a/packages/core/test/persistent-pty-daemon.test.ts b/packages/core/test/persistent-pty-daemon.test.ts index b5e61eda8640..478077fe9085 100644 --- a/packages/core/test/persistent-pty-daemon.test.ts +++ b/packages/core/test/persistent-pty-daemon.test.ts @@ -8,6 +8,24 @@ import { makeDaemonTransport } from "../src/persistent-pty/daemon" import { frame, listen, pong, temporaryDirectory, terminal, writeRegistration } from "./fixture/persistent-pty-daemon" import { it } from "./lib/effect" +it.live("refuses guarded cwd before sending to a daemon without the capability", () => + Effect.gen(function* () { + const { root, directory } = yield* temporaryRuntime() + const socketPath = path.join(directory, "daemon.sock") + let creates = 0 + yield* listen(socketPath, (_socket, request) => { + if (request.op === "ping") return pong + if (request.op === "create_pipe") creates++ + return { type: "ok" } + }) + yield* Effect.promise(() => writeRegistration(directory, socketPath)) + const daemon = yield* makeDaemonTransport(root, "daemon") + const error = yield* Effect.flip(daemon.request({ op: "create_pipe", guarded_cwd: {} }, true, "guarded_cwd")) + expect(error).toMatchObject({ kind: "protocol", message: expect.stringContaining("guarded_cwd") }) + expect(creates).toBe(0) + }), +) + it.live("rediscovers a same-protocol daemon after its registration rotates", () => Effect.gen(function* () { const { root, directory } = yield* temporaryRuntime() diff --git a/packages/core/test/tool-patch-target-environment.test.ts b/packages/core/test/tool-patch-target-environment.test.ts index 7df47765d459..9a6f7fa19cfc 100644 --- a/packages/core/test/tool-patch-target-environment.test.ts +++ b/packages/core/test/tool-patch-target-environment.test.ts @@ -9,6 +9,7 @@ import { Config } from "@opencode/core/config" import { Environment } from "@opencode/core/environment/index" import { FileAccess } from "@opencode/core/file-access" import { FileMutation } from "@opencode/core/file-mutation" +import { FileWrite } from "@opencode/core/file-write" import { Flag } from "@opencode/core/flag" import { Formatter } from "@opencode/core/formatter" import { Location } from "@opencode/core/location" @@ -29,6 +30,7 @@ const patchToolNode = makeLocationNode({ Tool.node, FileAccess.node, FileMutation.node, + FileWrite.node, Environment.node, Formatter.node, Location.node, diff --git a/packages/core/test/tool-patch.test.ts b/packages/core/test/tool-patch.test.ts index ec0d93095797..b832836ebb20 100644 --- a/packages/core/test/tool-patch.test.ts +++ b/packages/core/test/tool-patch.test.ts @@ -9,8 +9,10 @@ import { Config } from "@opencode/core/config" import { Flag } from "@opencode/core/flag" import { Formatter } from "@opencode/core/formatter" import { FileMutation } from "@opencode/core/file-mutation" +import { FileWrite } from "@opencode/core/file-write" import { Location } from "@opencode/core/location" import { FileAccess } from "@opencode/core/file-access" +import { PluginHooks } from "@opencode/core/plugin/hooks" import { Permission } from "@opencode/core/permission" import { AbsolutePath } from "@opencode/core/schema" import { Session } from "@opencode/core/session" @@ -31,6 +33,7 @@ const patchToolNode = makeLocationNode({ Tool.node, FileAccess.node, FileMutation.node, + FileWrite.node, Environment.node, Formatter.node, Location.node, @@ -52,6 +55,10 @@ let afterEditApproval = (): Effect.Effect => Effect.void let formatFile = (_target: string): Effect.Effect => Effect.succeed(false) const permission = permissionLayer({ + assertNotDenied: (input) => + input.action === denyAction + ? Effect.fail(new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources })) + : Effect.void, assert: (input) => Effect.sync(() => { assertions.push(input) @@ -92,6 +99,7 @@ const withTool = ( directory: string, body: (registry: Tool.Interface) => Effect.Effect, projectDirectory = directory, + scoped = false, ) => { const activeLocation = Layer.succeed( Location.Service, @@ -103,32 +111,38 @@ const withTool = ( return yield* body(yield* Tool.Service) }).pipe( Effect.provide( - AppNodeBuilder.build(LayerNode.group([Tool.node, FileAccess.node, FileMutation.node, patchToolNode]), [ - Environment.node.replace( - transformEnvironmentFiles((files) => ({ - read: (target, range) => - Effect.sync(() => { - if (!editApproved) readsBeforeEditApproval++ - }).pipe(Effect.andThen(files.read(target, range))), - remove: (target) => { - if (failRemoveTarget && path.basename(target) === failRemoveTarget) - return Effect.die("forced remove failure") - if (failRemoveErrorTarget && path.basename(target) === failRemoveErrorTarget) - return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced remove failure") })) - return files.remove(target) - }, - write: (target, content) => { - if (failWriteTarget && path.basename(target) === failWriteTarget) - return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced write failure") })) - return files.write(target, content) - }, - })), - ), - Location.node.replace(activeLocation), - Formatter.node.replace(formatter), - Permission.node.replace(permission), - Config.node.replace(Config.testLayer()), - ]), + AppNodeBuilder.build( + LayerNode.group([Tool.node, FileAccess.node, FileMutation.node, PluginHooks.node, patchToolNode]), + [ + Environment.node.replace( + transformEnvironmentFiles((files) => ({ + read: (target, range) => + Effect.sync(() => { + if (!editApproved) readsBeforeEditApproval++ + }).pipe(Effect.andThen(files.read(target, range))), + remove: (target) => { + if (failRemoveTarget && path.basename(target) === failRemoveTarget) + return Effect.die("forced remove failure") + if (failRemoveErrorTarget && path.basename(target) === failRemoveErrorTarget) + return Effect.fail( + new Environment.Failed({ path: target, cause: new Error("forced remove failure") }), + ) + return files.remove(target) + }, + write: (target, content) => { + if (failWriteTarget && path.basename(target) === failWriteTarget) + return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced write failure") })) + return files.write(target, content) + }, + })), + ), + Location.node.replace(activeLocation), + Formatter.node.replace(formatter), + Permission.node.replace(permission), + Config.node.replace(Config.testLayer()), + ...(scoped ? [Flag.node.replace(Flag.testLayer([], { overrides: "workspace_read_scope" }))] : []), + ], + ), ), ) } @@ -154,6 +168,147 @@ const withTempTool = (body: (directory: string, registry: Tool.Interfac }) describe("PatchTool", () => { + const scopedPatch = process.platform === "linux" ? it.live : it.live.skip + + scopedPatch("adds and updates a managed member through both aliases while rejecting unsupported hunks", () => + withTempDir((logical) => + withTempDir((physical) => { + reset() + return withTool( + logical.path, + (registry) => + Effect.gen(function* () { + const hooks = yield* PluginHooks.Service + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => { + if (event.sessionID === sessionID && event.action === "write") + event.scopes.push({ + members: [ + { + logical: path.join(logical.path, "member"), + physical: physical.path, + protectedPaths: [".git"], + }, + ], + }) + }), + ) + expect( + yield* executeTool( + registry, + call("*** Begin Patch\n*** Add File: member/new.txt\n+before\n*** End Patch"), + ), + ).toMatchObject({ + status: "completed", + }) + expect(yield* Effect.promise(() => fs.readFile(path.join(physical.path, "new.txt"), "utf8"))).toBe( + "before\n", + ) + expect(assertions).toMatchObject([ + { + action: "edit", + resources: ["member/new.txt", path.join(physical.path, "new.txt")], + }, + ]) + expect(assertions[0]?.verifiedWorkspace).toBeUndefined() + expect( + yield* executeTool( + registry, + call( + `*** Begin Patch\n*** Update File: ${path.join(physical.path, "new.txt")}\n@@\n-before\n+after\n*** End Patch`, + "call-physical", + ), + ), + ).toMatchObject({ status: "completed" }) + expect(yield* Effect.promise(() => fs.readFile(path.join(physical.path, "new.txt"), "utf8"))).toBe( + "after\n", + ) + denyAction = "read" + expect( + yield* executeTool( + registry, + call( + "*** Begin Patch\n*** Update File: member/new.txt\n@@\n-after\n+denied\n*** End Patch", + "call-denied", + ), + ), + ).toMatchObject({ status: "error" }) + denyAction = undefined + expect(yield* Effect.promise(() => fs.readFile(path.join(physical.path, "new.txt"), "utf8"))).toBe( + "after\n", + ) + denyAction = "edit" + expect( + yield* executeTool( + registry, + call( + "*** Begin Patch\n*** Update File: member/new.txt\n@@\n-after\n+denied\n*** End Patch", + "call-edit-denied", + ), + ), + ).toMatchObject({ status: "error" }) + denyAction = undefined + expect(yield* Effect.promise(() => fs.readFile(path.join(physical.path, "new.txt"), "utf8"))).toBe( + "after\n", + ) + expect( + yield* executeTool( + registry, + call( + "*** Begin Patch\n*** Add File: member/other.txt\n+other\n*** Delete File: member/new.txt\n*** End Patch", + "call-delete", + ), + ), + ).toMatchObject({ status: "error" }) + expect(yield* exists(path.join(physical.path, "other.txt"))).toBe(false) + expect( + yield* executeTool( + registry, + call( + "*** Begin Patch\n*** Update File: member/new.txt\n*** Move to: member/moved.txt\n@@\n-after\n+after\n*** End Patch", + "call-move", + ), + ), + ).toMatchObject({ status: "error" }) + expect(yield* exists(path.join(physical.path, "moved.txt"))).toBe(false) + expect( + yield* executeTool( + registry, + call( + "*** Begin Patch\n*** Add File: member/staged.txt\n+first\n*** Update File: member/staged.txt\n@@\n-first\n+second\n*** End Patch", + "call-staged", + ), + ), + ).toMatchObject({ status: "completed" }) + expect(yield* Effect.promise(() => fs.readFile(path.join(physical.path, "staged.txt"), "utf8"))).toBe( + "second\n", + ) + expect( + yield* executeTool( + registry, + call( + "*** Begin Patch\n*** Add File: member/mixed.txt\n+blocked\n*** Add File: outside.txt\n+blocked\n*** End Patch", + "call-mixed", + ), + ), + ).toMatchObject({ status: "error" }) + expect(yield* exists(path.join(physical.path, "mixed.txt"))).toBe(false) + expect(yield* exists(path.join(logical.path, "outside.txt"))).toBe(false) + expect( + yield* executeTool( + registry, + call("*** Begin Patch\n*** Add File: member/.git/config\n+blocked\n*** End Patch", "call-git"), + ), + ).toMatchObject({ status: "error" }) + expect(yield* exists(path.join(physical.path, ".git"))).toBe(false) + }), + logical.path, + true, + ) + }), + ), + ) + it.live("registers and sequentially applies add, update, and delete hunks", () => withTempDir((tmp) => { reset() @@ -450,7 +605,10 @@ describe("PatchTool", () => { expect(yield* Effect.promise(() => fs.readFile(latin1))).toEqual(bytes) // Deleting does not rewrite the bytes, so it stays allowed. expect( - yield* executeTool(registry, call("*** Begin Patch\n*** Delete File: Old.java\n*** End Patch", "call-delete")), + yield* executeTool( + registry, + call("*** Begin Patch\n*** Delete File: Old.java\n*** End Patch", "call-delete"), + ), ).toMatchObject({ status: "completed" }) expect(yield* exists(doomed)).toBe(false) }), @@ -464,7 +622,9 @@ describe("PatchTool", () => { expect( yield* executeTool( registry, - call("*** Begin Patch\n*** Update File: same.txt\n*** Move to: Same.txt\n@@\n-before\n+after\n*** End Patch"), + call( + "*** Begin Patch\n*** Update File: same.txt\n*** Move to: Same.txt\n@@\n-before\n+after\n*** End Patch", + ), ), ).toMatchObject({ status: "completed" }) expect(yield* Effect.promise(() => fs.readdir(directory))).toEqual(["Same.txt"]) @@ -483,7 +643,9 @@ describe("PatchTool", () => { expect( yield* executeTool( registry, - call("*** Begin Patch\n*** Update File: Foo/a.txt\n*** Move to: foo/a.txt\n@@\n-before\n+after\n*** End Patch"), + call( + "*** Begin Patch\n*** Update File: Foo/a.txt\n*** Move to: foo/a.txt\n@@\n-before\n+after\n*** End Patch", + ), ), ).toMatchObject({ status: "completed" }) expect(yield* Effect.promise(() => fs.readFile(path.join(directory, "foo", "a.txt"), "utf8"))).toBe("after\n") diff --git a/packages/core/test/tool-search.test.ts b/packages/core/test/tool-search.test.ts index bd946a418eb8..547d350dac28 100644 --- a/packages/core/test/tool-search.test.ts +++ b/packages/core/test/tool-search.test.ts @@ -1,7 +1,8 @@ import { describe, expect } from "bun:test" import fs from "fs/promises" +import type { FileHandle } from "node:fs/promises" import path from "path" -import { Effect, Layer } from "effect" +import { Deferred, Effect, Fiber, Layer } from "effect" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { Config } from "@opencode/core/config" import { makeLocationNode } from "@opencode/util/effect/app-node" @@ -12,7 +13,9 @@ import { Flag } from "@opencode/core/flag" import { Location } from "@opencode/core/location" import { FileAccess } from "@opencode/core/file-access" import { Permission } from "@opencode/core/permission" +import { PluginHooks } from "@opencode/core/plugin/hooks" import { Ripgrep } from "@opencode/core/ripgrep" +import { ScopedSearch } from "@opencode/core/tool/scoped-search" import { AbsolutePath } from "@opencode/core/schema" import { Session } from "@opencode/core/session" import { GlobTool } from "@opencode/core/tool/plugin/glob" @@ -44,19 +47,28 @@ const withTools = ( directory: string, body: (registry: Tool.Interface) => Effect.Effect, assertions?: Permission.AssertInput[], + scoped = false, + deniedBoundary?: string, ) => Effect.gen(function* () { const registry = yield* Tool.Service return yield* body(registry) }).pipe( Effect.provide( - AppNodeBuilder.build(LayerNode.group([Tool.node, searchToolsNode]), [ + AppNodeBuilder.build(LayerNode.group([Tool.node, searchToolsNode, PluginHooks.node, FileAccess.node]), [ Config.node.replace(Config.testLayer()), + ...(scoped ? [Flag.node.replace(Flag.testLayer([], { overrides: "workspace_read_scope" }))] : []), Location.node.replace( Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make(directory) }))), ), Permission.node.replace( permissionLayer({ + assertNotDenied: (input) => + deniedBoundary && input.resources.some((resource) => resource.endsWith(deniedBoundary)) + ? Effect.fail( + new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources }), + ) + : Effect.void, assert: (input) => Effect.sync(() => { assertions?.push(input) @@ -307,6 +319,302 @@ describe("search tools", () => { ), ) + const scopedGrep = process.platform === "linux" ? it.live : it.live.skip + scopedGrep("searches a verified physical or logical file through its held descriptor", () => + Effect.gen(function* () { + const active = yield* tmpdirScoped() + const physical = yield* tmpdirScoped() + const outside = yield* tmpdirScoped() + const assertions: Permission.AssertInput[] = [] + const file = path.join(physical.path, "target.txt") + yield* Effect.promise(() => fs.writeFile(file, "needle\nneedle\n")) + yield* Effect.promise(() => fs.writeFile(path.join(outside.path, "outside.txt"), "needle\n")) + yield* withTools( + active.path, + (registry) => + Effect.gen(function* () { + const hooks = yield* PluginHooks.Service + const logical = path.join(active.path, "member") + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => { + if (event.sessionID === sessionID && event.directory === active.path) + event.scopes.push({ members: [{ physical: physical.path, logical }] }) + }), + ) + const physicalResult = yield* executeTool( + registry, + call("grep", { path: file, pattern: "needle", limit: 1 }), + ) + expect(physicalResult).toMatchObject({ + status: "completed", + output: [{ entry: { path: path.relative(active.path, file) }, line: 1 }], + metadata: { matches: 1, truncated: true }, + }) + const logicalResult = yield* executeTool( + registry, + call("grep", { path: path.join(logical, "target.txt"), pattern: "needle" }), + ) + expect(logicalResult).toMatchObject({ + status: "completed", + output: [ + { entry: { path: "member/target.txt" }, line: 1 }, + { entry: { path: "member/target.txt" }, line: 2 }, + ], + }) + expect(assertions.map((request) => request.action)).toEqual(["read", "grep", "read", "grep"]) + expect(assertions[0]).toMatchObject({ resources: ["member/target.txt", file] }) + + yield* Effect.promise(() => fs.rename(file, path.join(physical.path, "original.txt"))) + yield* Effect.promise(() => fs.symlink(path.join(outside.path, "outside.txt"), file)) + const changed = yield* executeTool(registry, call("grep", { path: file, pattern: "needle" })) + expect(changed.status).toBe("error") + const directory = yield* executeTool(registry, call("grep", { path: physical.path, pattern: "needle" })) + expect(directory).toMatchObject({ + status: "completed", + output: [ + { entry: { path: path.relative(active.path, path.join(physical.path, "original.txt")) }, line: 1 }, + { entry: { path: path.relative(active.path, path.join(physical.path, "original.txt")) }, line: 2 }, + ], + }) + expect(assertions.filter((request) => request.action === "external_directory")).toEqual([]) + }), + assertions, + true, + ) + }), + ) + + scopedGrep("keeps a native external-directory denial effective for a logical scoped file", () => + Effect.gen(function* () { + const active = yield* tmpdirScoped() + const physical = yield* tmpdirScoped() + const assertions: Permission.AssertInput[] = [] + yield* Effect.promise(() => fs.writeFile(path.join(physical.path, "target.txt"), "needle\n")) + yield* withTools( + active.path, + (registry) => + Effect.gen(function* () { + const hooks = yield* PluginHooks.Service + const logical = path.join(active.path, "member") + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => void event.scopes.push({ members: [{ physical: physical.path, logical }] })), + ) + const result = yield* executeTool( + registry, + call("grep", { path: path.join(logical, "target.txt"), pattern: "needle" }), + ) + expect(result.status).toBe("error") + expect(assertions).toEqual([]) + }), + assertions, + true, + `${path.basename(physical.path)}/*`, + ) + }), + ) + + scopedGrep("searches physical and logical directories without following child symlinks", () => + Effect.gen(function* () { + const active = yield* tmpdirScoped() + const physical = yield* tmpdirScoped() + const outside = yield* tmpdirScoped() + const assertions: Permission.AssertInput[] = [] + yield* Effect.promise(() => fs.mkdir(path.join(physical.path, ".ai"))) + yield* Effect.promise(() => fs.writeFile(path.join(physical.path, "visible.ts"), "needle\n")) + yield* Effect.promise(() => fs.writeFile(path.join(physical.path, ".ai", "nested.ts"), "needle\n")) + yield* Effect.promise(() => fs.writeFile(path.join(outside.path, "secret.ts"), "needle\n")) + yield* withTools( + active.path, + (registry) => + Effect.gen(function* () { + const hooks = yield* PluginHooks.Service + const logical = path.join(active.path, "member") + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => void event.scopes.push({ members: [{ physical: physical.path, logical }] })), + ) + const physicalGrep = yield* executeTool(registry, call("grep", { path: physical.path, pattern: "needle" })) + expect(physicalGrep.status).toBe("completed") + if (physicalGrep.status === "completed") { + expect(physicalGrep.output.map((match: { entry: { path: string } }) => match.entry.path).sort()).toEqual( + [path.join(physical.path, ".ai/nested.ts"), path.join(physical.path, "visible.ts")] + .map((file) => path.relative(active.path, file)) + .sort(), + ) + } + yield* Effect.promise(() => fs.symlink(outside.path, path.join(physical.path, "linked"))) + const logicalGrep = yield* executeTool( + registry, + call("grep", { path: path.join(logical, ".ai"), pattern: "needle" }), + ) + expect(logicalGrep).toMatchObject({ + status: "completed", + output: [{ entry: { path: "member/.ai/nested.ts" } }], + }) + const defaultGlob = yield* executeTool(registry, call("glob", { path: logical, pattern: "**/*.ts" })) + expect(defaultGlob).toMatchObject({ + status: "completed", + output: [{ path: "member/visible.ts" }], + }) + const hiddenGlob = yield* executeTool( + registry, + call("glob", { path: physical.path, pattern: "**/*.ts", hidden: true }), + ) + expect(hiddenGlob.status).toBe("completed") + if (hiddenGlob.status === "completed") + expect(hiddenGlob.output.map((entry: { path: string }) => entry.path).sort()).toEqual( + [path.join(physical.path, ".ai/nested.ts"), path.join(physical.path, "visible.ts")] + .map((file) => path.relative(active.path, file)) + .sort(), + ) + const invalidGlob = yield* executeTool(registry, call("glob", { path: logical, pattern: "[" })) + expect(invalidGlob).toMatchObject({ + status: "error", + error: { message: "Invalid glob in pattern '[': unclosed character class; missing ']'" }, + }) + const invalidInclude = yield* executeTool( + registry, + call("grep", { path: logical, pattern: "needle", include: "[" }), + ) + expect(invalidInclude).toMatchObject({ + status: "error", + error: { message: "Invalid glob in include '[': unclosed character class; missing ']'" }, + }) + expect(assertions.every((request) => request.action !== "external_directory")).toBe(true) + }), + assertions, + true, + ) + }), + ) + + scopedGrep("stops a directory search at a native denial on a nested directory", () => + Effect.gen(function* () { + const active = yield* tmpdirScoped() + const physical = yield* tmpdirScoped() + const assertions: Permission.AssertInput[] = [] + yield* Effect.promise(() => fs.mkdir(path.join(physical.path, "protected"))) + yield* Effect.promise(() => fs.writeFile(path.join(physical.path, "protected", "secret.ts"), "needle\n")) + yield* withTools( + active.path, + (registry) => + Effect.gen(function* () { + const hooks = yield* PluginHooks.Service + const logical = path.join(active.path, "member") + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => void event.scopes.push({ members: [{ physical: physical.path, logical }] })), + ) + const result = yield* executeTool(registry, call("grep", { path: logical, pattern: "needle" })) + expect(result.status).toBe("error") + expect(assertions.every((request) => request.action !== "external_directory")).toBe(true) + }), + assertions, + true, + "/protected/*", + ) + }), + ) + + scopedGrep("batches guarded descriptors and closes them after each search", () => + Effect.gen(function* () { + const active = yield* tmpdirScoped() + const physical = yield* tmpdirScoped() + const names = Array.from({ length: ScopedSearch.BATCH_SIZE + 1 }, (_, index) => `file-${index}.txt`) + yield* Effect.promise(() => + Promise.all(names.map((name) => fs.writeFile(path.join(physical.path, name), "needle\n"))), + ) + yield* withTools( + active.path, + (registry) => + Effect.gen(function* () { + const hooks = yield* PluginHooks.Service + const access = yield* FileAccess.Service + const logical = path.join(active.path, "member") + const context = { sessionID, ...toolIdentity, id: Tool.CallID.make("call-batch") } + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => void event.scopes.push({ members: [{ physical: physical.path, logical }] })), + ) + const target = yield* access.authorizeRead(physical.path, context, { workspaceScope: true }) + if (!target.workspace) throw new Error("Expected guarded workspace") + const sizes: number[] = [] + const handles: FileHandle[] = [] + const found = yield* ScopedSearch.files({ + workspace: target.workspace, + requested: physical.path, + context, + access, + limit: names.length, + hidden: true, + onBatch: (batch) => + Effect.gen(function* () { + sizes.push(batch.length) + handles.push(...batch.map((entry) => entry.file)) + yield* Effect.forEach(batch, (entry) => Effect.promise(() => entry.file.stat()), { discard: true }) + return batch.map((entry) => entry.relative) + }), + }) + expect(sizes).toEqual([ScopedSearch.BATCH_SIZE, 1]) + expect([...found].sort()).toEqual([...names].sort()) + expect( + (yield* Effect.promise(() => Promise.allSettled(handles.map((file) => file.stat())))).every( + (item) => item.status === "rejected", + ), + ).toBe(true) + const result = yield* executeTool(registry, call("grep", { path: physical.path, pattern: "needle" })) + expect(result).toMatchObject({ status: "completed", metadata: { matches: names.length, truncated: false } }) + if (result.status === "completed") + expect(result.output.map((match: { entry: { path: string } }) => match.entry.path).sort()).toEqual( + names.map((name) => path.relative(active.path, path.join(physical.path, name))).sort(), + ) + const failedHandles: FileHandle[] = [] + const failed = yield* ScopedSearch.files({ + workspace: target.workspace, + requested: physical.path, + context, + access, + limit: names.length, + hidden: true, + onBatch: (batch) => { + failedHandles.push(...batch.map((entry) => entry.file)) + return Effect.fail(new Error("batch failed")) + }, + }).pipe(Effect.flip) + expect(failed).toMatchObject({ message: "batch failed" }) + expect(failedHandles).toHaveLength(ScopedSearch.BATCH_SIZE) + expect( + (yield* Effect.promise(() => Promise.allSettled(failedHandles.map((file) => file.stat())))).every( + (item) => item.status === "rejected", + ), + ).toBe(true) + const started = yield* Deferred.make() + const cancelledHandles: FileHandle[] = [] + const pending = yield* ScopedSearch.files({ + workspace: target.workspace, + requested: physical.path, + context, + access, + limit: names.length, + hidden: true, + onBatch: (batch) => + Effect.sync(() => cancelledHandles.push(...batch.map((entry) => entry.file))).pipe( + Effect.andThen(Deferred.succeed(started, undefined)), + Effect.andThen(Effect.never), + ), + }).pipe(Effect.forkChild) + yield* Deferred.await(started) + yield* Fiber.interrupt(pending) + expect(cancelledHandles).toHaveLength(ScopedSearch.BATCH_SIZE) + expect( + (yield* Effect.promise(() => Promise.allSettled(cancelledHandles.map((file) => file.stat())))).every( + (item) => item.status === "rejected", + ), + ).toBe(true) + }), + undefined, + true, + ) + }), + ) + for (const name of ["glob", "grep"] as const) { it.live(`${name} reports a missing search path`, () => withTempDir((tmp) => diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 696f8d04268b..7723ff645087 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -62,22 +62,24 @@ const assertions: Permission.AssertInput[] = [] let denyAction: string | undefined let afterPermission = (_input: Permission.AssertInput): Effect.Effect => Effect.void -const permission = permissionLayer({ - assert: (input) => - Effect.sync(() => assertions.push(input)).pipe( - Effect.andThen(Effect.suspend(() => afterPermission(input))), - Effect.andThen( - input.action === denyAction - ? Effect.fail( - new Permission.BlockedError({ - rules: [], - permission: input.action, - resources: input.resources, - }), - ) - : Effect.void, - ), +const checkPermission = (input: Permission.AssertInput) => + Effect.sync(() => assertions.push(input)).pipe( + Effect.andThen(Effect.suspend(() => afterPermission(input))), + Effect.andThen( + input.action === denyAction + ? Effect.fail( + new Permission.BlockedError({ + rules: [], + permission: input.action, + resources: input.resources, + }), + ) + : Effect.void, ), + ) +const permission = permissionLayer({ + assert: checkPermission, + assertNotDenied: checkPermission, }) const reset = () => { @@ -185,6 +187,9 @@ const noFlagOverrides = Layer.succeed(Flag.Overrides, undefined) const productionIt = testEffect(AppNodeBuilder.build(nodes, replacements).pipe(Layer.provide(noFlagOverrides))) const shellLayer = AppNodeBuilder.build(nodes, [...replacements, PluginSupervisor.node.replace(shellPluginSupervisor)]) const it = testEffect(shellLayer.pipe(Layer.provideMerge(noFlagOverrides))) +const scopedShellIt = testEffect( + shellLayer.pipe(Layer.provideMerge(Layer.succeed(Flag.Overrides, "workspace_read_scope"))), +) const codeModeIt = testEffect(shellLayer.pipe(Layer.provide(Layer.succeed(Flag.Overrides, "full_codemode")))) // On the real process daemon (when its binary is compatible; otherwise this falls back to spawning). const daemonIt = testEffect( @@ -1347,6 +1352,47 @@ describe("ShellTool", () => { { timeout: 15_000 }, ) + scopedShellIt.live("checks a physical assigned cwd and fails closed without a compatible daemon", () => + withTempDir((tmp) => + Effect.gen(function* () { + if (process.platform !== "linux") return + reset() + const active = path.join(tmp.path, "active") + const assigned = path.join(tmp.path, "assigned") + yield* Effect.promise(() => Promise.all([fs.mkdir(active), fs.mkdir(assigned)])) + yield* withSession(active, (registry) => + Effect.gen(function* () { + const hooks = yield* PluginHooks.Service + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => { + if (event.sessionID === sessionID) + event.scopes.push({ members: [{ physical: assigned, logical: path.join(active, "member") }] }) + }), + ) + const result = yield* executeTool(registry, call({ command: "pwd", workdir: assigned })) + expect(result).toMatchObject({ + status: "error", + error: { message: expect.stringContaining("compatible process daemon") }, + }) + expect(assertions.map((item) => item.action)).toEqual(["external_directory", "read", "shell"]) + expect(assertions[0]?.resources).toEqual([path.join(assigned, "*")]) + expect(assertions[1]?.resources).toEqual(["member", assigned]) + + reset() + denyAction = "read" + const denied = yield* executeTool(registry, call({ command: "pwd", workdir: assigned }, "denied-cwd")) + expect(denied).toMatchObject({ + status: "error", + error: { message: expect.stringContaining("Permission denied: read") }, + }) + expect(assertions.map((item) => item.action)).toEqual(["external_directory", "read"]) + reset() + }), + ) + }), + ), + ) + it.live( "deduplicates external directory approvals across workdir and directory-change commands", () => diff --git a/packages/core/test/tool-write.test.ts b/packages/core/test/tool-write.test.ts index 918ccfe25a46..4dc02dcc8591 100644 --- a/packages/core/test/tool-write.test.ts +++ b/packages/core/test/tool-write.test.ts @@ -12,6 +12,7 @@ import { LayerNode } from "@opencode/util/effect/layer-node" import { Environment } from "@opencode/core/environment/index" import { Location } from "@opencode/core/location" import { FileAccess } from "@opencode/core/file-access" +import { PluginHooks } from "@opencode/core/plugin/hooks" import { Permission } from "@opencode/core/permission" import { AbsolutePath } from "@opencode/core/schema" import { Session } from "@opencode/core/session" @@ -47,6 +48,7 @@ const makeWriteFixture = () => { } const permission = permissionLayer({ + assertNotDenied: () => Effect.void, assert: (input) => Effect.sync(() => fixture.assertions.push(input)).pipe( Effect.andThen( @@ -74,6 +76,7 @@ const withTool = ( directory: string, fixture: ReturnType, body: (registry: Tool.Interface) => Effect.Effect, + scoped = false, ) => { const activeLocation = Layer.succeed( Location.Service, @@ -84,22 +87,26 @@ const withTool = ( return yield* body(registry) }).pipe( Effect.provide( - AppNodeBuilder.build(LayerNode.group([Tool.node, FileAccess.node, FileMutation.node, writeToolNode]), [ - Environment.node.replace( - transformEnvironmentFiles((files) => ({ - read: (target, options) => - Effect.sync(() => fixture.reads.push({ target, length: options?.length })).pipe( - Effect.andThen(files.read(target, options)), - ), - write: (target, content) => - Effect.sync(() => fixture.writes.push(target)).pipe(Effect.andThen(files.write(target, content))), - })), - ), - Location.node.replace(activeLocation), - Formatter.node.replace(fixture.formatter), - Permission.node.replace(fixture.permission), - Config.node.replace(Config.testLayer()), - ]), + AppNodeBuilder.build( + LayerNode.group([Tool.node, FileAccess.node, FileMutation.node, PluginHooks.node, writeToolNode]), + [ + Environment.node.replace( + transformEnvironmentFiles((files) => ({ + read: (target, options) => + Effect.sync(() => fixture.reads.push({ target, length: options?.length })).pipe( + Effect.andThen(files.read(target, options)), + ), + write: (target, content) => + Effect.sync(() => fixture.writes.push(target)).pipe(Effect.andThen(files.write(target, content))), + })), + ), + Location.node.replace(activeLocation), + Formatter.node.replace(fixture.formatter), + Permission.node.replace(fixture.permission), + Config.node.replace(Config.testLayer()), + ...(scoped ? [Flag.node.replace(Flag.testLayer([], { overrides: "workspace_read_scope" }))] : []), + ], + ), ), ) } @@ -113,6 +120,82 @@ const call = (input: typeof WriteTool.Input.Type, id = "call-write") => ({ const it = testEffect(Layer.succeed(Flag.Overrides, undefined)) describe("WriteTool", () => { + const scopedWrite = process.platform === "linux" ? it.live : it.live.skip + + scopedWrite("writes through the physical member and skips pathname formatting", () => + withTempDir((logical) => + withTempDir((physical) => { + const fixture = makeWriteFixture() + let formatterCalls = 0 + fixture.formatFile = () => + Effect.sync(() => { + formatterCalls++ + return true + }) + return withTool( + logical.path, + fixture, + (registry) => + Effect.gen(function* () { + const hooks = yield* PluginHooks.Service + yield* hooks.register("permission", "experimental.workspace.readScope", (event) => + Effect.sync(() => { + if (event.sessionID === sessionID && event.action === "write") + event.scopes.push({ + members: [ + { + logical: path.join(logical.path, "member"), + physical: physical.path, + protectedPaths: [".git"], + }, + ], + }) + }), + ) + expect(yield* executeTool(registry, call({ path: "member/new.txt", content: "scoped" }))).toMatchObject({ + status: "completed", + output: "Created file successfully: member/new.txt", + }) + expect(yield* Effect.promise(() => fs.readFile(path.join(physical.path, "new.txt"), "utf8"))).toBe( + "scoped", + ) + expect(fixture.assertions).toMatchObject([ + { action: "edit", resources: ["member/new.txt", path.join(physical.path, "new.txt")] }, + ]) + expect(fixture.assertions[0]?.verifiedWorkspace).toBe(true) + expect(fixture.writes).toEqual([]) + expect(formatterCalls).toBe(0) + expect( + yield* executeTool( + registry, + call({ path: path.join(physical.path, "new.txt"), content: "alias" }, "call-alias"), + ), + ).toMatchObject({ + status: "completed", + }) + expect(yield* Effect.promise(() => fs.readFile(path.join(physical.path, "new.txt"), "utf8"))).toBe( + "alias", + ) + expect( + yield* executeTool(registry, call({ path: "member/.git/config", content: "blocked" }, "call-git")), + ).toMatchObject({ + status: "error", + }) + expect( + yield* Effect.promise(() => + fs.stat(path.join(physical.path, ".git")).then( + () => true, + () => false, + ), + ), + ).toBe(false) + }), + true, + ) + }), + ), + ) + it.live("registers and creates a relative file through FileMutation once", () => withTempDir((tmp) => { const fixture = makeWriteFixture() @@ -134,6 +217,7 @@ describe("WriteTool", () => { expect(fixture.assertions).toMatchObject([ { sessionID, action: "edit", resources: ["src/new.txt"], save: ["*"] }, ]) + expect(fixture.assertions[0]?.verifiedWorkspace).toBeUndefined() expect(fixture.assertions[0]?.metadata).toMatchObject({ files: [ { diff --git a/packages/plugin/src/effect/permission.ts b/packages/plugin/src/effect/permission.ts index 23aba2da117d..16ad6dbc6be7 100644 --- a/packages/plugin/src/effect/permission.ts +++ b/packages/plugin/src/effect/permission.ts @@ -4,7 +4,7 @@ import type { Permission } from "@opencode/schema/permission" import type { Session } from "@opencode/schema/session" import type { Tool } from "@opencode/schema/tool" import type { Effect } from "effect" -import type { AssertInput } from "../permission.js" +import type { AssertInput, WorkspaceReadScopeHook } from "../permission.js" import type { Hooks } from "./registration.js" export interface PermissionEvaluation { @@ -13,6 +13,7 @@ export interface PermissionEvaluation { readonly action: string readonly resources: ReadonlyArray readonly metadata?: Record + readonly verifiedWorkspace?: true readonly source?: Permission.Source effect: Permission.Effect message?: string @@ -20,6 +21,7 @@ export interface PermissionEvaluation { export interface PermissionHooks { readonly evaluate: PermissionEvaluation + readonly "experimental.workspace.readScope": WorkspaceReadScopeHook } export type PermissionDomain = Pick, "list" | "get" | "reply"> & { diff --git a/packages/plugin/src/permission.ts b/packages/plugin/src/permission.ts index 73c854f07544..80e15fef0636 100644 --- a/packages/plugin/src/permission.ts +++ b/packages/plugin/src/permission.ts @@ -1,7 +1,27 @@ import { Agent } from "@opencode/schema/agent" import { Permission } from "@opencode/schema/permission" +import type { Session } from "@opencode/schema/session" import { Schema } from "effect" +/** A trusted adapter's verified correspondence between workspace paths and their resolved paths. */ +export interface WorkspaceReadScope { + readonly members: ReadonlyArray<{ + readonly logical: string + readonly physical: string + /** Member-relative files or directory subtrees that may never be mutated. */ + readonly protectedPaths?: ReadonlyArray + }> +} + +/** An empty `scopes` array means unmanaged; `null` records a failed managed binding. */ +export interface WorkspaceReadScopeHook { + readonly sessionID: Session.ID + readonly directory: string + readonly action: "read" | "write" | "shell-cwd" + readonly source: Permission.Request["source"] + readonly scopes: Array +} + export const AssertInput = Schema.Struct({ sessionID: Permission.Request.fields.sessionID, agent: Agent.ID.pipe(Schema.optional), diff --git a/packages/plugin/src/promise/permission.ts b/packages/plugin/src/promise/permission.ts index f7eff1a5eb96..612b6bef1bcb 100644 --- a/packages/plugin/src/promise/permission.ts +++ b/packages/plugin/src/promise/permission.ts @@ -2,7 +2,7 @@ import type { PermissionApi } from "@opencode/client/promise/api" import type { Agent } from "@opencode/schema/agent" import type { Permission } from "@opencode/schema/permission" import type { Session } from "@opencode/schema/session" -import type { AssertInput } from "../permission.js" +import type { AssertInput, WorkspaceReadScopeHook } from "../permission.js" import type { Hooks } from "./registration.js" export interface PermissionEvaluation { @@ -11,6 +11,7 @@ export interface PermissionEvaluation { readonly action: string readonly resources: ReadonlyArray readonly metadata?: Record + readonly verifiedWorkspace?: true readonly source?: Permission.Source effect: Permission.Effect message?: string @@ -18,6 +19,7 @@ export interface PermissionEvaluation { export interface PermissionHooks { readonly evaluate: PermissionEvaluation + readonly "experimental.workspace.readScope": WorkspaceReadScopeHook } export type PermissionDomain = Pick & { diff --git a/packages/process-daemon/src/client.rs b/packages/process-daemon/src/client.rs index 1336b5fa04b2..ac6667fbabcb 100644 --- a/packages/process-daemon/src/client.rs +++ b/packages/process-daemon/src/client.rs @@ -179,6 +179,7 @@ impl TerminalClient { program: request.program, args: request.args, cwd: request.cwd, + guarded_cwd: request.guarded_cwd, env: request.env, group_id: request.group_id, output_path: request.output_path, diff --git a/packages/process-daemon/src/daemon/server.rs b/packages/process-daemon/src/daemon/server.rs index 80b6ab011855..d8dfe66b2c67 100644 --- a/packages/process-daemon/src/daemon/server.rs +++ b/packages/process-daemon/src/daemon/server.rs @@ -613,6 +613,7 @@ fn dispatch( program, args, cwd, + guarded_cwd, env, group_id, output_path, @@ -622,6 +623,7 @@ fn dispatch( program, args, cwd, + guarded_cwd, env, group_id, output_path, @@ -1071,6 +1073,7 @@ mod tests { program: "/bin/sh".into(), args: vec!["-c".into(), script.into()], cwd: "/".into(), + guarded_cwd: None, env: Default::default(), group_id: "test".into(), output_path, diff --git a/packages/process-daemon/src/protocol.rs b/packages/process-daemon/src/protocol.rs index 95752d4e9f93..9f3665cfa4a1 100644 --- a/packages/process-daemon/src/protocol.rs +++ b/packages/process-daemon/src/protocol.rs @@ -10,8 +10,11 @@ use crate::service::{ }; pub const PROTOCOL_VERSION: u32 = 9; -/// Additive capabilities of this daemon. Breaking changes bump -/// `PROTOCOL_VERSION`; everything in protocol 9 needs no feature. +/// Additive capabilities of this daemon. Breaking changes bump `PROTOCOL_VERSION`. +/// Clients must require a feature before sending an optional security-sensitive request field. +#[cfg(target_os = "linux")] +pub const FEATURES: &[&str] = &["guarded_cwd"]; +#[cfg(not(target_os = "linux"))] pub const FEATURES: &[&str] = &[]; pub fn features() -> Vec { @@ -57,6 +60,8 @@ pub enum Request { program: String, args: Vec, cwd: PathBuf, + #[serde(default, skip_serializing_if = "Option::is_none")] + guarded_cwd: Option, env: HashMap, group_id: String, output_path: PathBuf, @@ -363,9 +368,15 @@ mod tests { } #[test] - fn version_9_has_no_features() { + fn version_9_advertises_supported_features() { assert_eq!(PROTOCOL_VERSION, 9); - assert!(features().is_empty()); + assert_eq!( + features(), + FEATURES + .iter() + .map(|feature| feature.to_string()) + .collect::>() + ); // `features` is required. assert!( serde_json::from_value::( diff --git a/packages/process-daemon/src/service.rs b/packages/process-daemon/src/service.rs index 6c1a34bab352..5d0cf4d73245 100644 --- a/packages/process-daemon/src/service.rs +++ b/packages/process-daemon/src/service.rs @@ -276,6 +276,8 @@ pub struct CreatePipe { pub args: Vec, /// Absolute. pub cwd: PathBuf, + /// Physical root and child path for a cwd selected from a verified workspace scope. + pub guarded_cwd: Option, /// The child's whole environment; nothing is inherited from the daemon. pub env: HashMap, pub group_id: String, @@ -284,6 +286,12 @@ pub struct CreatePipe { pub metadata: PipeMetadata, } +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct GuardedCwd { + pub root: PathBuf, + pub relative: PathBuf, +} + pub struct TerminalService { terminals: Mutex>>, /// Failed-command escalation outlives record deletion. Shutdown waits for it. @@ -325,6 +333,9 @@ impl TerminalService { if !request.cwd.is_absolute() { bail!("cwd must be absolute"); } + if request.guarded_cwd.is_some() && !cfg!(target_os = "linux") { + bail!("guarded cwd requires Linux"); + } if !request.output_path.is_absolute() { bail!("output_path must be absolute"); } diff --git a/packages/process-daemon/src/service/pipe.rs b/packages/process-daemon/src/service/pipe.rs index 8b494e8cc8e3..a973ddc41fc8 100644 --- a/packages/process-daemon/src/service/pipe.rs +++ b/packages/process-daemon/src/service/pipe.rs @@ -123,6 +123,7 @@ fn new_pipe_info(id: TerminalId, pid: u32, request: CreatePipe) -> ProcessInfo { program, args, cwd, + guarded_cwd: _, env: _, group_id, output_path, diff --git a/packages/process-daemon/src/service/pipe/unix.rs b/packages/process-daemon/src/service/pipe/unix.rs index af3b2487647e..5ed6efbfb67f 100644 --- a/packages/process-daemon/src/service/pipe/unix.rs +++ b/packages/process-daemon/src/service/pipe/unix.rs @@ -11,11 +11,17 @@ //! - A cancelled reader closes the pipe, so leftover writers get `SIGPIPE` //! once the drain deadline passes. +#[cfg(target_os = "linux")] +use std::fs::File; use std::fs::OpenOptions; use std::io::{self, PipeReader, PipeWriter, Read}; use std::os::fd::AsFd; +#[cfg(target_os = "linux")] +use std::os::fd::AsRawFd; use std::os::unix::fs::OpenOptionsExt; use std::os::unix::process::CommandExt; +#[cfg(target_os = "linux")] +use std::path::{Component, Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::sync::{Arc, Mutex, PoisonError, RwLock}; use std::time::{Duration, Instant}; @@ -82,6 +88,21 @@ impl TerminalHandle { exited, exited_writer, } = Pipes::new()?; + // Authorization selects an inode when this request is handled. Keeping its descriptor through spawn means + // a later symlink change cannot redirect the child; a later rename cannot change the selected inode. + #[cfg(target_os = "linux")] + let guarded = request + .guarded_cwd + .as_ref() + .map(open_guarded_cwd) + .transpose()?; + #[cfg(target_os = "linux")] + if let Some(scope) = &request.guarded_cwd { + anyhow::ensure!( + request.cwd == scope.root.join(&scope.relative), + "guarded cwd does not match cwd" + ); + } // Before spawning, so a bad path fails the request with nothing to clean up. // The reader is the file's only writer, so it needs no append mode. let sink = OpenOptions::new() @@ -100,16 +121,29 @@ impl TerminalHandle { let mut command = Command::new(&request.program); command .args(&request.args) - .current_dir(&request.cwd) .env_clear() .envs(&request.env) .stdin(Stdio::null()) .stdout(output_writer) .stderr(stderr) .process_group(0); + #[cfg(target_os = "linux")] + if guarded.is_none() { + command.current_dir(&request.cwd); + } + #[cfg(not(target_os = "linux"))] + command.current_dir(&request.cwd); // SAFETY: only async-signal-safe calls run between fork and exec. unsafe { - command.pre_exec(reset_signals); + command.pre_exec(move || { + #[cfg(target_os = "linux")] + if let Some(directory) = &guarded { + if libc::fchdir(directory.as_raw_fd()) != 0 { + return Err(io::Error::last_os_error()); + } + } + reset_signals() + }); } let child = { let _guard = SPAWN_LOCK.write().unwrap_or_else(PoisonError::into_inner); @@ -139,6 +173,65 @@ impl TerminalHandle { } } +#[cfg(target_os = "linux")] +fn open_guarded_cwd(request: &crate::service::GuardedCwd) -> Result { + use anyhow::{bail, ensure}; + + ensure!( + request.root.is_absolute(), + "guarded cwd root must be absolute" + ); + ensure!( + std::fs::canonicalize(&request.root)? == request.root, + "guarded cwd root must be canonical" + ); + let segments = if request.relative.as_os_str().is_empty() { + Vec::new() + } else { + request + .relative + .components() + .map(|component| match component { + Component::Normal(segment) => Ok(segment.to_owned()), + _ => bail!("guarded cwd must contain only relative child segments"), + }) + .collect::>>()? + }; + ensure!( + request.relative == segments.iter().collect::(), + "guarded cwd must contain only relative child segments" + ); + let mut directory = OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW) + .open(&request.root)?; + verify_directory(&directory, &request.root)?; + let mut expected = request.root.clone(); + for segment in segments { + verify_directory(&directory, &expected)?; + expected.push(segment); + directory = OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW) + .open( + PathBuf::from(format!("/proc/self/fd/{}", directory.as_raw_fd())) + .join(expected.file_name().unwrap()), + )?; + verify_directory(&directory, &expected)?; + } + verify_directory(&directory, &expected)?; + Ok(directory) +} + +#[cfg(target_os = "linux")] +fn verify_directory(directory: &File, expected: &Path) -> Result<()> { + anyhow::ensure!( + std::fs::read_link(format!("/proc/self/fd/{}", directory.as_raw_fd()))? == expected, + "guarded cwd changed during open" + ); + Ok(()) +} + /// Runs in the child between fork and exec. The daemon blocks SIGTERM and /// SIGINT on all its threads, and std keeps the signal mask across exec, so /// clear it, and give every signal portable-pty also resets its default action. diff --git a/packages/process-daemon/src/service/pipe/windows.rs b/packages/process-daemon/src/service/pipe/windows.rs index feafd649672e..77c97f0d28ad 100644 --- a/packages/process-daemon/src/service/pipe/windows.rs +++ b/packages/process-daemon/src/service/pipe/windows.rs @@ -1027,6 +1027,7 @@ mod tests { program: program.into(), args: args.iter().map(|arg| arg.to_string()).collect(), cwd: std::env::current_dir().unwrap(), + guarded_cwd: None, env: ["PATH", "SystemRoot", "TEMP"] .into_iter() .filter_map(|name| Some((name.to_string(), std::env::var(name).ok()?))) diff --git a/packages/process-daemon/tests/ownership.rs b/packages/process-daemon/tests/ownership.rs index 70c7ecf75171..0e7bd5d5b03f 100644 --- a/packages/process-daemon/tests/ownership.rs +++ b/packages/process-daemon/tests/ownership.rs @@ -13,7 +13,7 @@ use opencode_pty::daemon::Registration; use opencode_pty::protocol::{ AttachmentRole, Envelope, Request, Response, read_frame, write_frame, }; -use opencode_pty::service::{ProcessInfo, ProcessMode}; +use opencode_pty::service::{GuardedCwd, ProcessInfo, ProcessMode}; struct Daemon { child: Child, @@ -314,10 +314,13 @@ fn rename_is_served() { use opencode_pty::protocol::{SubscriptionEvent, read_subscription_event}; let mut daemon = Daemon::start(); - assert!(daemon.registration.features.is_empty()); + assert_eq!( + daemon.registration.features, + opencode_pty::protocol::features() + ); assert!(matches!( daemon.request(Request::Ping), - Response::Pong { protocol: 9, features, .. } if features.is_empty() + Response::Pong { protocol: 9, features, .. } if features == opencode_pty::protocol::features() )); let (owner, response) = daemon.own(None); assert!(matches!(response, Response::Owned)); @@ -596,6 +599,10 @@ fn pipe_processes_survive_handoff_and_stay_out_of_pty_lists() { "echo before; sleep 1; echo after; exit 4".into(), ], cwd: daemon.directory.clone(), + guarded_cwd: cfg!(target_os = "linux").then(|| GuardedCwd { + root: daemon.directory.clone(), + relative: PathBuf::new(), + }), env: Default::default(), group_id: "ownership".into(), output_path: output_file.clone(), @@ -667,6 +674,7 @@ fn pipe_processes_do_not_inherit_the_daemons_blocked_signals() { program: "/bin/sh".into(), args: vec!["-c".into(), "exec sleep 1000".into()], cwd: daemon.directory.clone(), + guarded_cwd: None, env: Default::default(), group_id: "ownership".into(), output_path: daemon.root.join(format!("{name}.out")), diff --git a/packages/process-daemon/tests/pipe.rs b/packages/process-daemon/tests/pipe.rs index 97f40b16258c..9a09aa1e8e1e 100644 --- a/packages/process-daemon/tests/pipe.rs +++ b/packages/process-daemon/tests/pipe.rs @@ -5,6 +5,8 @@ use std::env; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; +#[cfg(target_os = "linux")] +use opencode_pty::service::GuardedCwd; use opencode_pty::service::{ CreatePipe, CreatePty, MAX_METADATA_BYTES, PipeMetadata, ProcessExit, ProcessInfo, ProcessMode, ProcessSignal, TerminalId, TerminalLifecycle, TerminalService, @@ -33,6 +35,7 @@ fn pipe(script: &str, output: &Path) -> CreatePipe { program: "/bin/sh".to_string(), args: vec!["-c".to_string(), script.to_string()], cwd: env::current_dir().expect("cwd"), + guarded_cwd: None, env: HashMap::from([("PATH".to_string(), env::var("PATH").unwrap_or_default())]), group_id: "pipe".to_string(), output_path: output.to_path_buf(), @@ -427,6 +430,43 @@ fn rejected_requests_never_touch_the_output_file_or_run() { assert!(!marker.0.exists()); } +#[cfg(target_os = "linux")] +#[test] +fn guarded_cwd_opens_at_launch_and_rejects_a_new_symlink() { + let root = TempPath::new("guard-root"); + let outside = TempPath::new("guard-outside"); + std::fs::create_dir(&root.0).unwrap(); + std::fs::create_dir(&outside.0).unwrap(); + std::fs::create_dir(root.0.join("child")).unwrap(); + let service = TerminalService::default(); + let output = TempPath::new("guard-output"); + let request = CreatePipe { + cwd: root.0.join("child"), + guarded_cwd: Some(GuardedCwd { + root: root.0.clone(), + relative: "child".into(), + }), + ..pipe("pwd", &output.0) + }; + let info = service.create_pipe(request.clone()).unwrap(); + assert_eq!( + run(&service, info.id, &output).output.trim(), + request.cwd.to_str().unwrap() + ); + service.terminate(info.id).unwrap(); + + std::fs::remove_dir(root.0.join("child")).unwrap(); + std::os::unix::fs::symlink(&outside.0, root.0.join("child")).unwrap(); + assert!(service.create_pipe(request).is_err()); + assert_eq!( + std::fs::read_to_string(&output.0).unwrap().trim(), + root.0.join("child").to_str().unwrap() + ); + std::fs::remove_file(root.0.join("child")).unwrap(); + std::fs::remove_dir(&root.0).unwrap(); + std::fs::remove_dir(&outside.0).unwrap(); +} + #[test] fn the_child_gets_exactly_the_given_environment() { // Something the test process (and so a daemon) certainly has. diff --git a/packages/process-daemon/tests/pipe_windows.rs b/packages/process-daemon/tests/pipe_windows.rs index 04360afa14e0..84922ee00f7c 100644 --- a/packages/process-daemon/tests/pipe_windows.rs +++ b/packages/process-daemon/tests/pipe_windows.rs @@ -88,6 +88,7 @@ fn pipe( program: program.into(), args, cwd: env::current_dir().expect("cwd"), + guarded_cwd: None, env, group_id: "pipe".into(), output_path: output.to_path_buf(), diff --git a/packages/schema/src/config/flag.ts b/packages/schema/src/config/flag.ts index 1943e63071b4..a66f90b7e593 100644 --- a/packages/schema/src/config/flag.ts +++ b/packages/schema/src/config/flag.ts @@ -28,10 +28,12 @@ export const registry = { "Load skills from MCP servers that offer them (the io.modelcontextprotocol/skills extension), named :. A server that offers skills no longer has its instructions included.", sqlite_fts: "Build an SQLite full-text index of session titles and message text in the background, and enable the opencode.session.search and opencode.session.read tools. The index covers every session in the database and starts while any loaded location enables it; SQLite keeps it current from then on, also after this is turned off.", + workspace_read_scope: + "Use a trusted adapter's verified workspace scope for guarded regular-file reads and directory listings. Off by default in every build; opt in with OPENCODE_FLAGS=workspace_read_scope or experimental.workspace_read_scope: true.", } as const satisfies Record export type Key = keyof typeof registry -export const optInOnly: ReadonlySet = new Set(["todo", "opencode_api"]) +export const optInOnly: ReadonlySet = new Set(["todo", "opencode_api", "workspace_read_scope"]) /** Flags that stay off outside local and dev builds, whatever `OPENCODE_FLAGS` or config say. */ export const localOnly: ReadonlySet = new Set(["opencode_api"])