You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
permission: a symlink bypasses read rules and the external_directory check #58638
File permission checks use the path as written, not the file that the path points to. A symlink therefore changes the result:
An agent rule such as { "action": "read", "resource": "real/**", "effect": "deny" } denies read real/file.txt. But if link is a symlink to real, read link/file.txt returns the file content.
OpenCode treats a symlink inside the project that points outside the project as an internal path. It does not do the external_directory check.
Cause, at dev b64cc80db3: FileAccess.resolve (packages/core/src/file-access.ts:93-104) uses resolvePath (lexical path.resolve) and FSUtil.contains (path.relative). It does not call realpath. authorizeRead then matches the read rules against that lexical resource (:144-159).
SECURITY.md says that the permission system is not a sandbox, so this is not a security report. It is a bug in the rules: a deny rule for a path does not stop a read of that same file through a link.
Possible fix: resolve the real path (of the longest existing prefix, for new files), check external_directory when the real path is outside the project, and match read and edit rules against both the written path and the real path. Use the stricter result.
Related: #30788 asked for the external_directory part. The stale bot closed it.
Plugins
None that change permission decisions.
OpenCode version
2.1.3 (@opencode/cli). Source checked on dev b64cc80db3.
Steps to reproduce
In a project directory: mkdir real && echo hello > real/file.txt && ln -s real link
Ask the agent to read real/file.txt. OpenCode denies the read.
Ask the agent to read link/file.txt. The read returns hello.
The result is the same for an absolute deny rule on a directory outside the project, with the link in that directory. Edit and write use the same resolve; I did not test them.
Thanks for the detailed report. I can confirm this on 2.1.3, and it still happens on the latest dev (b64cc80db).
Setup: real/file.txt, the symlinks link -> real and vendor -> /tmp/opencode/outside-58638, and build agent rules that allow *, deny read on real/** and deny external_directory on *. Results:
read vendor/notes.txt → returns the file content, with no external_directory check
The script below reproduces it with a simulated model. The recording and screenshot show the actual tool results. I did not test edit or write, but they use the same path resolution.
Related: #40160 reported the external_directory part on v1. Open PR #52224 resolves symlinks before the external_directory check, but it does not appear to cover read or edit rules that match through a link.
recording.mp4
Reproduction script (drive.ts)
// Repro for anomalyco/opencode#58638: symlinks bypass read deny rules and external_directory.// Run: OPENCODE_DRIVE_MEDIA_DIR=/workspace/media opencode-drive run drive.ts (OC_DEV=<checkout> to run from source)import{Effect,Stream}from"effect"import{Llm,OpenCodeDriver}from"opencode-drive"constOUTSIDE="/tmp/opencode/outside-58638"constcall=(id: string,name: string,input: any)=>[Llm.toolCall({index: 0, id, name, input }),Llm.finish("tool-calls"),]// Pull the real tool result for a call id out of the provider request OpenCode sent.constresultOf=(req: any,id: string): string=>{constmessages: any[]=req?.body?.messages??req?.messages??[]constfound=messages.find((m)=>m.role==="tool"&&m.tool_call_id===id)if(found)returnString(found.content).replace(/\s+/g," ").slice(0,110)constm=JSON.stringify(req).match(newRegExp(`tool_call_id\\\\?":\\\\?"${id}\\\\?",\\\\?"content\\\\?":\\\\?"(.{0,110})`))returnm ? m[1] : "(not found)"}constIDS=["call_real","call_link","call_out","call_vendor"]exportdefaultOpenCodeDriver.use({
...(process.env.OC_DEV ? {opencode: {dev: process.env.OC_DEV}} : {}),tui: {recording: true},project: {git: true,files: {"real/file.txt": "hello-from-real\n"}},config: {default_agent: "build",agents: {build: {permissions: [{action: "*",resource: "*",effect: "allow"},{action: "read",resource: "real/**",effect: "deny"},{action: "external_directory",resource: "*",effect: "deny"},],},},},}asany,({ ui, llm })=>Effect.gen(function*(){conststeps: any[][]=[// 1. create link -> real (inside) and vendor -> /tmp/opencode/outside-58638 (outside)call("call_ln","shell",{command: `rm -rf ${OUTSIDE} link vendor && mkdir -p ${OUTSIDE} && echo secret-outside > ${OUTSIDE}/notes.txt && ln -s real link && ln -s ${OUTSIDE} vendor && ls -l`,}),call("call_real","read",{path: "real/file.txt"}),// denied by read rule (expected)call("call_link","read",{path: "link/file.txt"}),// same file via symlink: should be deniedcall("call_out","read",{path: `${OUTSIDE}/notes.txt`}),// denied by external_directory (expected)call("call_vendor","read",{path: "vendor/notes.txt"}),// same file via in-project symlink: should be denied]letstep=0yield*llm.serve((req: any)=>{consttext=JSON.stringify(req)if(text.includes("Reply with only the title"))returnStream.make(Llm.text("symlink repro"),Llm.finish())constnext=steps[step++]if(next)returnStream.make(...next)constreport=IDS.map((id)=>`${id}: ${resultOf(req,id)}`).join("\n\n")returnStream.make(Llm.text(`RESULTS\n\n${report}\n\nEND`),Llm.finish())})yield*ui.submit("Create links and read the files")yield*ui.waitFor("END",{timeout: 60000})yield*Effect.sleep("1 second")yield*ui.screenshot("results")constframe=yield*ui.capture()constlines=(frameasany).lines.map((l: any)=>l.spans.map((s: any)=>s.text).join("")).join("\n")yield*Effect.log(`\n${lines}`)}),)
Run it with opencode-drive: opencode-drive run ./drive.ts. It drives opencode from your PATH; set OC_DEV to the path of an OpenCode checkout to run that from source instead.
I'd like to take this. Plan: resolve the real path in FileAccess.resolve (realpath of the longest existing prefix, keeping the not-yet-existing tail lexical), decide internal/external and the external_directory boundary on the real path, and match read/edit rules against both the written path and the real path — permission.assert already takes the stricter result across multiple resources. Will verify locally with a junction-based repro on Windows plus the existing file-access tests.
Reproduced with the actual @opencode/sdk and @opencode/client2.2.6 on Linux / Node 26.13.0, using a simulated model and the native read and write tools. No external model or product data was involved.
Workspace fixture: chat-a/own.txt, chat-b/secret.txt, and chat-a/link.txt symlinked to chat-b/secret.txt. Session and agent rules are ordered:
Actual results: native read of chat-a/own.txt succeeded; direct read of chat-b/secret.txt and chat-a/../chat-b/secret.txt were denied. Reading chat-a/link.txt returned the sibling marker. Native write created chat-a/created.txt, denied chat-b/created.txt, and succeeded through chat-a/link.txt; an independent filesystem read confirmed the sibling target changed. The model-visible tool catalog and completed native tool results were asserted.
Separately, making chat-a the session location with external_directory denied still allowed reading its symlink to the sibling. This adds a tested write case and an allowlist configuration to the existing report. Resolving and checking both the requested path and real target, including existing prefixes for creates, would cover this case. Race-resistant enforcement and OS isolation are separate concerns; permission rules alone are not an OS sandbox.
Thanks for extending the reproduction to the native write path and the allowlist shape — that was useful confirmation that this is one bug across read, edit/write, and external_directory, not just the original read case.
I re-audited the rebased PR against current dev in light of your results:
FileAccess.resolve matches read rules against both the written resource and the symlink-resolved real resource, and decides internal/external plus the external-directory boundary from the real path.
FileWrite.authorize now uses the same ruleResources, so both native write and edit go through the stricter lexical + real-path decision.
patch combines every target's ruleResources before asserting edit permission.
That audit also caught one same-family call site that the rebase had dropped: worktree_remove had fallen back to [target.resource]. I restored it to target.ruleResources in f9563eaa42.
The PR intentionally remains permission-rule enforcement rather than an OS sandbox; race-resistant filesystem enforcement is outside its scope, as you noted.
One case the real-path fix in #58642 doesn't cover: hard links. OpenCode writes in place (fs.writeFile in environment/local.ts), so if notes.txt is a hard link to opencode.json, writing or editing notes.txt changes opencode.json, while the rules are checked only against notes.txt.
A hard link has no target path, so realpath normally returns the link's own name. Under Bun on macOS, the async fs.realpath that #58642 uses returned the other name in 3 of 40 runs, so it can't be relied on either way.
Making edits ask when the file has more than one link (stat.nlink > 1) would make these edits visible. The link must be created locally first, for example with ln.
Confirmed both mechanisms on current dev (0220248dc1):
Writes go through FileMutation.writeTextPreservingBom → Environment.files.write → fs.writeFile in environment/local.ts, so editing one name keeps the shared inode and silently changes every other name.
fix(core): match file permission rules on the symlink-resolved real path #58642's real-path resolution (FSUtil.resolve → realpathSync.native) returns the written name for a hard link, so ruleResources collapses to the written path and adds nothing here. Agreed on not leaning on realpath for this either way — your 3/40 Bun/macOS observation means even the "helpful" answer can't be trusted. stat.nlink (or dev/ino identity) is the only portable signal.
One catch on making these edits ask: the rule engine can't express an unconditional ask for a resource the rules already allow. evaluate falls back to ask only when nothing matches, and a common config like { "action": "*", "resource": "*", "effect": "allow" } matches any resource string we could synthesize; evaluateInput picks the strictest effect across resources but can only choose among effects the rules produce. Forcing the prompt for nlink > 1 therefore needs one of:
an always-ask gate that bypasses evaluation — changes what an explicit allow means, or
a separate default-ask action in the external_directory style that users can allow explicitly.
Both are policy calls, so I'd rather let the maintainers pick a direction before extending #58642 with it. One cost worth weighing: hard links are routine in snapshot-style trees (rsync --link-dest, cp -l backups), where nlink > 1 would make every edit ask.
Happy to implement either variant in #58642 once there's a nod — including surfacing nlink in the edit request metadata as a smaller first step.
Activity
opencode-agent commentedon Oct 24, 2026
Thanks for the detailed report. I can confirm this on 2.1.3, and it still happens on the latest
dev(b64cc80db).Setup:
real/file.txt, the symlinkslink -> realandvendor -> /tmp/opencode/outside-58638, and build agent rules that allow*, denyreadonreal/**and denyexternal_directoryon*. Results:read real/file.txt→Permission denied: readread link/file.txt→ returns the file contentread /tmp/opencode/outside-58638/notes.txt→Permission denied: external_directoryread vendor/notes.txt→ returns the file content, with noexternal_directorycheckThe script below reproduces it with a simulated model. The recording and screenshot show the actual tool results. I did not test edit or write, but they use the same path resolution.
Related: #40160 reported the
external_directorypart on v1. Open PR #52224 resolves symlinks before theexternal_directorycheck, but it does not appear to cover read or edit rules that match through a link.recording.mp4
Reproduction script (drive.ts)
Run it with opencode-drive:
opencode-drive run ./drive.ts. It drivesopencodefrom yourPATH; setOC_DEVto the path of an OpenCode checkout to run that from source instead.Dopetaiga commentedon Oct 24, 2026
I'd like to take this. Plan: resolve the real path in
FileAccess.resolve(realpath of the longest existing prefix, keeping the not-yet-existing tail lexical), decide internal/external and theexternal_directoryboundary on the real path, and match read/edit rules against both the written path and the real path —permission.assertalready takes the stricter result across multiple resources. Will verify locally with a junction-based repro on Windows plus the existing file-access tests.itlackey commentedon Nov 11, 2026
Reproduced with the actual
@opencode/sdkand@opencode/client2.2.6 on Linux / Node 26.13.0, using a simulated model and the nativereadandwritetools. No external model or product data was involved.Workspace fixture:
chat-a/own.txt,chat-b/secret.txt, andchat-a/link.txtsymlinked tochat-b/secret.txt. Session and agent rules are ordered:[ { "action": "*", "resource": "*", "effect": "deny" }, { "action": "read", "resource": "chat-a/*", "effect": "allow" }, { "action": "edit", "resource": "chat-a/*", "effect": "allow" } ]Actual results: native
readofchat-a/own.txtsucceeded; direct read ofchat-b/secret.txtandchat-a/../chat-b/secret.txtwere denied. Readingchat-a/link.txtreturned the sibling marker. Nativewritecreatedchat-a/created.txt, deniedchat-b/created.txt, and succeeded throughchat-a/link.txt; an independent filesystem read confirmed the sibling target changed. The model-visible tool catalog and completed native tool results were asserted.Separately, making
chat-athe session location withexternal_directorydenied still allowed reading its symlink to the sibling. This adds a tested write case and an allowlist configuration to the existing report. Resolving and checking both the requested path and real target, including existing prefixes for creates, would cover this case. Race-resistant enforcement and OS isolation are separate concerns; permission rules alone are not an OS sandbox.Dopetaiga commentedon Nov 11, 2026
Thanks for extending the reproduction to the native
writepath and the allowlist shape — that was useful confirmation that this is one bug across read, edit/write, andexternal_directory, not just the original read case.I re-audited the rebased PR against current
devin light of your results:FileAccess.resolvematches read rules against both the written resource and the symlink-resolved real resource, and decides internal/external plus the external-directory boundary from the real path.FileWrite.authorizenow uses the sameruleResources, so both nativewriteand edit go through the stricter lexical + real-path decision.ruleResourcesbefore asserting edit permission.That audit also caught one same-family call site that the rebase had dropped:
worktree_removehad fallen back to[target.resource]. I restored it totarget.ruleResourcesinf9563eaa42.Focused verification on the rebased head:
The PR intentionally remains permission-rule enforcement rather than an OS sandbox; race-resistant filesystem enforcement is outside its scope, as you noted.
knp-sap commentedon Nov 18, 2026
One case the real-path fix in #58642 doesn't cover: hard links. OpenCode writes in place (
fs.writeFileinenvironment/local.ts), so ifnotes.txtis a hard link toopencode.json, writing or editingnotes.txtchangesopencode.json, while the rules are checked only againstnotes.txt.A hard link has no target path, so
realpathnormally returns the link's own name. Under Bun on macOS, the asyncfs.realpaththat #58642 uses returned the other name in 3 of 40 runs, so it can't be relied on either way.Making edits ask when the file has more than one link (
stat.nlink > 1) would make these edits visible. The link must be created locally first, for example withln.Dopetaiga commentedon Nov 18, 2026
Confirmed both mechanisms on current dev (
0220248dc1):FileMutation.writeTextPreservingBom→Environment.files.write→fs.writeFileinenvironment/local.ts, so editing one name keeps the shared inode and silently changes every other name.FSUtil.resolve→realpathSync.native) returns the written name for a hard link, soruleResourcescollapses to the written path and adds nothing here. Agreed on not leaning onrealpathfor this either way — your 3/40 Bun/macOS observation means even the "helpful" answer can't be trusted.stat.nlink(or dev/ino identity) is the only portable signal.One catch on making these edits ask: the rule engine can't express an unconditional ask for a resource the rules already allow.
evaluatefalls back toaskonly when nothing matches, and a common config like{ "action": "*", "resource": "*", "effect": "allow" }matches any resource string we could synthesize;evaluateInputpicks the strictest effect across resources but can only choose among effects the rules produce. Forcing the prompt fornlink > 1therefore needs one of:external_directorystyle that users can allow explicitly.Both are policy calls, so I'd rather let the maintainers pick a direction before extending #58642 with it. One cost worth weighing: hard links are routine in snapshot-style trees (
rsync --link-dest,cp -lbackups), wherenlink > 1would make every edit ask.Happy to implement either variant in #58642 once there's a nod — including surfacing
nlinkin the edit request metadata as a smaller first step.