fix(preview): pin the physical workspace directory for each grant

This commit is contained in:
Luke Parker 2026-11-16 16:17:56 +10:00
parent 0a4479bc5b
commit 93e224a813
14 changed files with 149 additions and 41 deletions

View file

@ -1518,6 +1518,7 @@ export function make(options: ClientOptions) {
sessionID: input["sessionID"],
path: input["path"],
document: input["document"],
root: input["root"],
entry: input["entry"],
},
successStatus: 200,

View file

@ -4598,6 +4598,7 @@ export type ExperimentalPreviewReadInput = {
readonly sessionID: string
readonly path: string
readonly document: string
readonly root: string
readonly entry?: "1" | undefined
}

View file

@ -774,8 +774,8 @@ export function createBrowserPage(
if (!closed()) options.hidden?.()
})
const load = async (url: string) => {
const destination = url.startsWith("artifact:") ? options.artifacts?.load(url) : localFileURL(url) || url.startsWith("workspace:") ? options.workspace?.load(url, () => notices.show({reason:"browser.preview.restricted"})) : url
const load = async (url: string, retry = false) => {
const destination = url.startsWith("artifact:") ? options.artifacts?.load(url) : localFileURL(url) || url.startsWith("workspace:") ? await options.workspace?.load(url, () => notices.show({reason:"browser.preview.restricted"}), retry ? contents.getURL() : undefined) : url
if (!destination) return Promise.reject(new Error("Workspace preview is unavailable."))
@ -811,13 +811,13 @@ export function createBrowserPage(
const reload = async () => {
const tab = state()
if (tab.loadError && /^(?:file|workspace|artifact):/.test(tab.url)) return void await load(tab.url)
if (tab.loadError && /^(?:file|workspace|artifact):/.test(tab.url)) return void await load(tab.url, true)
const actual = contents.getURL()
if (options.workspace?.host(actual) && options.workspace.display(actual) === tab.url) return void await load(tab.url)
if (options.workspace?.host(actual) && options.workspace.display(actual) === tab.url) return void await load(tab.url, true)
const address = reloadAddress(actual, state().url, options.workspace?.host(actual), policy.fileRoots ?? [], policy.remote)
if (address) return void await load(address)
if (address) return void await load(address, true)
contents.reload()
}

View file

@ -30,6 +30,8 @@ function fixture(read: Remote["read"]) {
type: "remote",
root: "/work",
document: "index.html",
identity: "fixture",
pin: async () => "fixture",
takeEntry: () => false,
denied: () => {},
prefix: "workspace://session/",

View file

@ -43,11 +43,15 @@ test("the authenticated read under a server base path names exactly the file val
expect(req.headers.get("authorization")).toBe("fixture")
expect(req.headers.get("accept-encoding")).toBe("identity")
expect(url.pathname).toBe("/sub/api/experimental/preview/read")
const pin = "a".repeat(64)
if (url.searchParams.get("root") === "bind") return new Response(null, {headers:{"x-opencode-preview":"3","x-opencode-preview-root":pin}})
expect(url.searchParams.get("root")).toBe(pin)
if (req.method === "HEAD") checked.push(url.searchParams.get("path") ?? "")
else reads.push(url.searchParams.get("path") ?? "")
return new Response("x", { headers: { "x-opencode-preview": "2", "content-length": "1" } })
return new Response("x", { headers: { "x-opencode-preview": "3", "content-length": "1" } })
},
})
@ -60,7 +64,10 @@ test("the authenticated read under a server base path names exactly the file val
controller.signal,
)
const grants = new Map<string, PreviewSource>([["grant", {...source, document:"index.html", takeEntry:()=>false, denied:()=>{}}]])
const identity = await source.pin("index.html", controller.signal)
if (!identity) throw new Error("expected root identity")
const grants = new Map<string, PreviewSource>([["grant", {...source, identity, document:"index.html", takeEntry:()=>false, denied:()=>{}}]])
const names = ["dir/50% off.html", "#?.txt", "a%2fb", "%252e%252e/[slug]", "日本語.txt"]
try {

View file

@ -11,11 +11,12 @@ export function remotePreview(
): Extract<WorkspaceSource, { type: "remote" }> {
let outdated = false
const request = async (path: string, method: "HEAD" | "GET", range: string | undefined, signal: AbortSignal, document: string, entry: boolean) => {
const request = async (path: string, method: "HEAD" | "GET", range: string | undefined, signal: AbortSignal, document: string, entry: boolean, identity: string) => {
const url = new URL("api/experimental/preview/read", `${server.url.replace(/\/+$/, "")}/`)
url.searchParams.set("sessionID", session)
url.searchParams.set("path", path)
url.searchParams.set("document", document)
url.searchParams.set("root", identity)
if (entry) url.searchParams.set("entry", "1")
url.searchParams.set("location[directory]", location.directory)
@ -36,7 +37,7 @@ export function remotePreview(
signal: AbortSignal.any([signal, lifetime, timeout.signal]),
})
if (response.headers.get("x-opencode-preview") === "2") {
if (response.headers.get("x-opencode-preview") === "3") {
outdated = false
return response
@ -51,13 +52,24 @@ export function remotePreview(
}
}
const pin = async (document:string, signal:AbortSignal) => {
const response = await request(document, "HEAD", undefined, signal, document, true, "bind").catch(() => undefined)
const id = response?.headers.get("x-opencode-preview-root")
return response?.ok && id && /^[a-f0-9]{64}$/.test(id) ? id : undefined
}
return {
type: "remote",
root: location.directory,
prefix: workspacePrefix(session),
needsUpdate: () => outdated,
stat: async (path, signal, document=path, entry=false) => {
const response = await request(path, "HEAD", undefined, signal, document, entry).catch(() => undefined)
pin,
stat: async (path, signal, document=path, entry=false, identity) => {
const id = identity ?? await pin(document,signal)
if (!id) return null
const response = await request(path, "HEAD", undefined, signal, document, entry, id).catch(() => undefined)
if (response?.headers.get("x-opencode-preview-denied") === "1") return "denied"
const length = response?.headers.get("content-length")
@ -66,6 +78,6 @@ export function remotePreview(
? Number(length)
: null
},
read: (path, range, signal, document, entry) => request(path, "GET", range, signal, document, entry),
read: (path, range, signal, document, entry, identity) => request(path, "GET", range, signal, document, entry, identity),
}
}

View file

@ -3,6 +3,7 @@ import { link, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/
import { tmpdir } from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { previewRoot } from "@opencode/util/preview-scope"
import { resolvePreviewRequest, workspaceFile, type PreviewSource } from "./workspace-file"
test("preview and reveal resolve existing regular files under the real workspace, including a linked root", async () => {
@ -26,7 +27,8 @@ test("preview and reveal resolve existing regular files under the real workspace
await mkdir(path.dirname(doc))
await writeFile(doc, "report")
await symlink(repo, path.join(repo, "reports", "alias"), directoryLink)
const restricted = new Map<string, PreviewSource>([["scoped", {type:"local", roots:()=>[repo], document:"reports/index.html", takeEntry:()=>false, denied:()=>{}}]])
const identity = (await previewRoot(repo)).id
const restricted = new Map<string, PreviewSource>([["scoped", {type:"local", identity, roots:()=>[repo], document:"reports/index.html", takeEntry:()=>false, denied:()=>{}}]])
const scoped = (path: string) => resolvePreviewRequest(pathToFileURL(path).href.replace("file://", "oc-preview://scoped"), "GET", "oc-preview://scoped", restricted, new AbortController().signal)
const control = await scoped(doc)
expect(control?.type).toBe("local")
@ -41,7 +43,7 @@ test("preview and reveal resolve existing regular files under the real workspace
await link(file, path.join(repo, "hardlink"))
expect(await lookup(path.join(repo, "hardlink"))).toMatchObject({ size: 6 })
const scope = { document:"index.html", takeEntry:()=>false, denied:()=>{} }
const scope = { identity, document:"index.html", takeEntry:()=>false, denied:()=>{} }
const grants = new Map([["first", { ...scope,type: "local" as const, roots: () => [repo] }]])
const url = pathToFileURL(file).href.replace("file://", "oc-preview://first")
const request = (method: string) => resolvePreviewRequest(url, method, "oc-preview://first", grants, new AbortController().signal)
@ -65,7 +67,7 @@ test("preview and reveal resolve existing regular files under the real workspace
const sources = new Map<string, PreviewSource>([
["local", { ...scope,type: "local", roots: () => [repo] }],
["remote", { ...scope,type: "remote",root:"/work", prefix: "workspace://session/", stat: async (path) => {
["remote", { ...scope,type: "remote",root:"/work", prefix: "workspace://session/", pin:async()=>identity, stat: async (path) => {
remotePaths.push(path)
return path === "server-only.html" ? 17 : null

View file

@ -14,19 +14,21 @@ export type WorkspaceSource =
type: "remote"
root: string
prefix: string
pin(document: string, signal: AbortSignal): Promise<string | undefined>
needsUpdate?(): boolean
stat(path: string, signal: AbortSignal, document?: string, entry?: boolean): Promise<number | null | "denied">
stat(path: string, signal: AbortSignal, document?: string, entry?: boolean, identity?:string): Promise<number | null | "denied">
read(
path: string,
range: string | undefined,
signal: AbortSignal,
document: string,
entry: boolean,
identity: string,
): Promise<Response>
}
export type PreviewSource =
| (WorkspaceSource & { document: string; takeEntry(): boolean; denied(): void })
| (WorkspaceSource & { document: string; identity: string; takeEntry(): boolean; denied(): void })
| { type: "artifact"; id: string; read(route: string, method: string, signal: AbortSignal): Promise<Response> }
/** The grant must still belong to this binding after asynchronous path resolution. */
@ -49,6 +51,8 @@ export async function resolvePreviewRequest(
return item && { type: "artifact" as const, route: item.route, read: grant.read }
}
if (!grant.identity) return
if (grant.type === "remote") {
const origin = `oc-preview://${host}`
@ -68,7 +72,7 @@ export async function resolvePreviewRequest(
return
}
const size = await grant.stat(path, signal, grant.document, entry)
const size = await grant.stat(path, signal, grant.document, entry, grant.identity)
if (size === "denied") {
grant.denied()
@ -83,7 +87,7 @@ export async function resolvePreviewRequest(
path,
size,
read: async (path: string, range: string | undefined, signal: AbortSignal) => {
const response = await grant.read(path, range, signal, grant.document, entry)
const response = await grant.read(path, range, signal, grant.document, entry, grant.identity)
if (response.headers.get("x-opencode-preview-denied") === "1" && grants.get(host) === grant) grant.denied()
@ -106,7 +110,7 @@ export async function resolvePreviewRequest(
if (!root) return
const path = relative(root, fileURLToPath(file)).replaceAll("\\", "/")
const entry = path === grant.document && initiator === undefined && grant.takeEntry()
const target = await openPreviewFile(root, grant.document, path, entry).catch(() => undefined)
const target = await openPreviewFile(root, grant.document, path, entry, grant.identity).catch(() => undefined)
if (target === "denied") {
grant.denied()

View file

@ -1,7 +1,7 @@
import { relative } from "node:path"
import { homedir } from "node:os"
import { fileURLToPath } from "node:url"
import { openPreviewFile, previewAllowed } from "@opencode/util/preview-scope"
import { openPreviewFile, previewAllowed, previewRoot } from "@opencode/util/preview-scope"
import type { createPreviews } from "./profile/previews"
import type { WorkspaceSource } from "./workspace-file"
import { fileURLWithin } from "./policy"
@ -15,7 +15,8 @@ export function workspacePages(
source: WorkspaceSource,
lifetime: AbortSignal,
) {
const grants = new Map<string, { document: string; release(): void }>()
const grants = new Map<string, { document: string; identity: string; release(): void }>()
let lastRoot: string | undefined
const remote = source.type === "remote" ? source.prefix : undefined
const roots = source.type === "local" ? [root] : []
@ -27,10 +28,16 @@ export function workspacePages(
: undefined
return {
load(address: string, refused: () => void) {
async load(address: string, refused: () => void, retryFrom?: string) {
const document = path(address)
if (!document) return
const old = retryFrom && this.host(retryFrom)
const prior = retryFrom === undefined ? undefined : (old && grants.get(old)?.identity) || lastRoot
const identity = prior ?? (source.type === "remote" ? await source.pin(document, lifetime) : await previewRoot(root).then(pin => pin.id, () => undefined))
if (lifetime.aborted) return
lastRoot = identity
let first = true
let notified = false
@ -38,6 +45,8 @@ export function workspacePages(
{
...source,
document,
// An unavailable initial bind must still let Chromium report a failed load. Never read without a pin.
identity: identity ?? "",
takeEntry() {
const value = first
first = false
@ -53,7 +62,7 @@ export function workspacePages(
lifetime,
)
grants.set(grant.host, { document, release: grant.release })
grants.set(grant.host, { document, identity: identity ?? "", release: grant.release })
return previewAddress(address, grant.host, roots, remote)
},
@ -88,14 +97,15 @@ export function workspacePages(
},
async exists(url: string, signal: AbortSignal) {
const host = this.host(url)
const doc = host && grants.get(host)?.document
const grant = host && grants.get(host)
const display = this.display(url)
const file = display && path(display)
if (!doc || !file) return false
if (!grant || !file) return false
const doc = grant.document
if (source.type === "remote") return Number.isSafeInteger(await source.stat(file, signal, doc, file === doc))
const opened = await openPreviewFile(root, doc, file, file === doc).catch(() => undefined)
if (source.type === "remote") return Number.isSafeInteger(await source.stat(file, signal, doc, file === doc, grant.identity))
const opened = await openPreviewFile(root, doc, file, file === doc, grant.identity).catch(() => undefined)
if (!opened || opened === "denied") return false
await opened.file.close()

View file

@ -13,7 +13,7 @@ import { LocationQuery, locationQueryOpenApi } from "./location.js"
export const ExperimentalGroup = PersistentPtyGroup.add(
MediaGetEndpoint,
HttpApiEndpoint.get("preview.read", "/api/experimental/preview/read", {
query: Schema.Struct({ ...LocationQuery.fields, sessionID: SessionID, path: Schema.String, document: Schema.String, entry: Schema.optional(Schema.Literal("1")) }),
query: Schema.Struct({ ...LocationQuery.fields, sessionID: SessionID, path: Schema.String, document: Schema.String, root: Schema.String.annotate({description:"The opaque root identity from a binding HEAD request; use bind only to establish a new grant."}), entry: Schema.optional(Schema.Literal("1")) }),
success: Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()),
error: SessionNotFoundError,
})

View file

@ -1,5 +1,5 @@
import { Session } from "@opencode/core/session"
import { openPreviewFile } from "@opencode/util/preview-scope"
import { openPreviewFile, previewRoot } from "@opencode/util/preview-scope"
import { Effect, Stream } from "effect"
import { type HttpServerRequest, HttpServerResponse } from "effect/http"
import { ContentHeaders } from "../content-headers"
@ -9,12 +9,12 @@ import { missingSession } from "./session-error"
export const makePreviewRead = Effect.gen(function* () {
const sessions = yield* Session.Service
return Effect.fn("Preview.read")(function* (
query: { sessionID: Session.ID; path: string; document: string; entry?: "1"; location?: { directory?: string; workspace?: string } },
query: { sessionID: Session.ID; path: string; document: string; root: string; entry?: "1"; location?: { directory?: string; workspace?: string } },
req: HttpServerRequest.HttpServerRequest,
) {
const session = yield* sessions.get(query.sessionID).pipe(Effect.mapError(missingSession))
const headers = {
"x-opencode-preview": "2",
"x-opencode-preview": "3",
"cache-control": "no-store, no-transform",
"accept-ranges": "bytes",
...ContentHeaders.download({ path: query.path, mime: "application/octet-stream" }),
@ -25,9 +25,14 @@ export const makePreviewRead = Effect.gen(function* () {
session.location.workspaceID
)
return HttpServerResponse.empty({ status: 404, headers })
if (query.root === "bind" && req.method === "HEAD") {
const root = yield* Effect.promise(() => previewRoot(session.location.directory).catch(() => undefined))
return root ? HttpServerResponse.empty({headers:{...headers,"x-opencode-preview-root":root.id}}) : HttpServerResponse.empty({status:404,headers})
}
if (!/^[a-f0-9]{64}$/.test(query.root)) return HttpServerResponse.empty({status:404,headers})
const opened = yield* Effect.acquireRelease(
Effect.promise(() =>
openPreviewFile(session.location.directory, query.document, query.path, query.entry === "1")
openPreviewFile(session.location.directory, query.document, query.path, query.entry === "1", query.root)
.catch(() => undefined),
),
(opened) =>

View file

@ -136,9 +136,14 @@ it.live(
preview.searchParams.set("location[directory]", created.data.location.directory)
preview.searchParams.set("path", "clip.mp4")
preview.searchParams.set("document", "index.html")
preview.searchParams.set("root", "bind")
const bound = yield* Effect.promise(() => fetch(preview, {method:"HEAD",headers:server.headers}))
const pin = bound.headers.get("x-opencode-preview-root")
expect(pin).toMatch(/^[a-f0-9]{64}$/)
preview.searchParams.set("root", pin ?? "")
const slice = yield* Effect.promise(() => fetch(preview, { headers: { ...server.headers, range: "bytes=2-5" } }))
expect(slice.status).toBe(206)
expect(slice.headers.get("x-opencode-preview")).toBe("2")
expect(slice.headers.get("x-opencode-preview")).toBe("3")
expect(yield* Effect.promise(() => slice.text())).toBe("2345")
preview.searchParams.set("path", "escape-link/secret.txt")
const refused = yield* Effect.promise(() => fetch(preview, {headers:server.headers}))

View file

@ -1,5 +1,6 @@
import { homedir } from "node:os"
import { realpath } from "node:fs/promises"
import { lstat, realpath } from "node:fs/promises"
import { createHash } from "node:crypto"
import { relative } from "node:path"
import { openContained } from "./contained-file.js"
@ -35,13 +36,40 @@ export function previewAllowed(root: string, document: string, path: string, ent
)
}
/** The same decision both before opening and on the kernel's name for the handle: an innocuous alias is not authority. */
export async function openPreviewFile(workspace: string, document: string, path: string, entry: boolean) {
/** The remote wire representation is opaque; never send the physical server path or a lossy numeric inode. */
export async function previewRoot(workspace: string) {
const path = await realpath(workspace)
const info = await lstat(path, { bigint: true })
if (!info.isDirectory() || info.ino === 0n) throw new Error("Cannot identify the preview root")
return {
path,
id: createHash("sha256")
.update(JSON.stringify([path, String(info.dev), String(info.ino), String(info.birthtimeNs)]))
.digest("hex"),
}
}
/** The grant's root must still name the original directory before and after authorizing the open file. */
export async function openPreviewFile(
workspace: string,
document: string,
path: string,
entry: boolean,
identity: string,
) {
if (!previewAllowed(workspace, document, path, entry, homedir())) return "denied"
const root = await realpath(workspace)
const opened = await openContained(root, path)
const root = await previewRoot(workspace)
if (root.id !== identity) return "denied"
const opened = await openContained(root.path, path)
if (!opened) return
if (previewAllowed(root, document, relative(root, opened.path), entry, homedir())) return opened
if (
previewAllowed(root.path, document, relative(root.path, opened.path), entry, homedir()) &&
(await previewRoot(workspace).then(
(current) => current.id === identity,
() => false,
))
)
return opened
await opened.file.close()
return "denied"
}

View file

@ -1,5 +1,36 @@
import { expect, test } from "bun:test"
import { previewAllowed } from "../src/preview-scope.js"
import { mkdir, mkdtemp, rename, rm, symlink, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { previewAllowed, previewRoot, openPreviewFile } from "../src/preview-scope.js"
test("an existing grant cannot follow a replaced root; a fresh grant may use a recreated workspace", async () => {
const temp = await mkdtemp(join(tmpdir(), "pin-root-"))
const workspace = join(temp, "workspace")
const other = join(temp, "other")
try {
await Promise.all([mkdir(workspace), mkdir(other)])
await writeFile(join(other, "index.html"), "outside")
const pin = (await previewRoot(workspace)).id
const read = (id: string) => openPreviewFile(workspace, "index.html", "index.html", true, id)
await rename(workspace, join(temp, "original"))
await symlink(other, workspace, process.platform === "win32" ? "junction" : "dir")
expect(await read(pin)).toBe("denied")
await rm(workspace)
await mkdir(workspace)
await writeFile(join(workspace, "index.html"), "recreated")
expect(await read(pin)).toBe("denied")
const opened = await read((await previewRoot(workspace)).id)
if (!opened || opened === "denied") throw new Error("missing fresh grant control")
try {
expect(await opened.file.readFile("utf8")).toBe("recreated")
} finally {
await opened.file.close()
}
} finally {
await rm(temp, { recursive: true, force: true })
}
})
test.each([
["/home/u/repo", "/home/u", "/"],