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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 38 additions & 21 deletions packages/core/src/codemode/bun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ const call = <A, E>(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.
Expand All @@ -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),
)
Expand Down Expand Up @@ -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
Expand All @@ -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 })
Expand Down Expand Up @@ -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 })
Expand Down
94 changes: 94 additions & 0 deletions packages/core/src/environment/guarded-mutation.ts
Original file line number Diff line number Diff line change
@@ -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<void>,
) {
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()
}
}
118 changes: 118 additions & 0 deletions packages/core/src/environment/guarded-read.ts
Original file line number Diff line number Diff line change
@@ -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<FileHandle> {
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<Promise<Dirent[]>>()

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<Dirent[]> {
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")
}
Loading
Loading