Skip to content

permission: a symlink bypasses read rules and the external_directory check #58638

Open

Description

@iceteaSA

Description

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

  1. In a project directory: mkdir real && echo hello > real/file.txt && ln -s real link

  2. In opencode.json, set the agent rules:

    {
      "default_agent": "build",
      "agents": {
        "build": {
          "permissions": [
            { "action": "*", "resource": "*", "effect": "allow" },
            { "action": "read", "resource": "real/**", "effect": "deny" }
          ]
        }
      }
    }
  3. Ask the agent to read real/file.txt. OpenCode denies the read.

  4. 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.

Operating System

Linux

Activity

  1. opencode-agent commented on Oct 24, 2026

    @opencode-agent
    Contributor

    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 real/file.txt → Permission denied: read
    • read link/file.txt → returns the file content
    • read /tmp/opencode/outside-58638/notes.txt → Permission denied: external_directory
    • 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

    Screenshot

    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"
    
    const OUTSIDE = "/tmp/opencode/outside-58638"
    
    const call = (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.
    const resultOf = (req: any, id: string): string => {
      const messages: any[] = req?.body?.messages ?? req?.messages ?? []
      const found = messages.find((m) => m.role === "tool" && m.tool_call_id === id)
      if (found) return String(found.content).replace(/\s+/g, " ").slice(0, 110)
      const m = JSON.stringify(req).match(new RegExp(`tool_call_id\\\\?":\\\\?"${id}\\\\?",\\\\?"content\\\\?":\\\\?"(.{0,110})`))
      return m ? m[1] : "(not found)"
    }
    
    const IDS = ["call_real", "call_link", "call_out", "call_vendor"]
    
    export default OpenCodeDriver.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" },
              ],
            },
          },
        },
      } as any,
      ({ ui, llm }) =>
        Effect.gen(function* () {
          const steps: 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 denied
            call("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
          ]
          let step = 0
          yield* llm.serve((req: any) => {
            const text = JSON.stringify(req)
            if (text.includes("Reply with only the title")) return Stream.make(Llm.text("symlink repro"), Llm.finish())
            const next = steps[step++]
            if (next) return Stream.make(...next)
            const report = IDS.map((id) => `${id}: ${resultOf(req, id)}`).join("\n\n")
            return Stream.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")
          const frame = yield* ui.capture()
          const lines = (frame as any).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.

  2. Dopetaiga commented on Oct 24, 2026

    @Dopetaiga

    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.

  3. itlackey commented on Nov 11, 2026

    @itlackey

    Reproduced with the actual @opencode/sdk and @opencode/client 2.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:

    [
      { "action": "*", "resource": "*", "effect": "deny" },
      { "action": "read", "resource": "chat-a/*", "effect": "allow" },
      { "action": "edit", "resource": "chat-a/*", "effect": "allow" }
    ]

    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.

  4. Dopetaiga commented on Nov 11, 2026

    @Dopetaiga

    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.

    Focused verification on the rebased head:

    file-access-path + tool-opencode: 24 passed / 0 failed
    TypeScript typecheck: clean
    GitHub check-compliance / check-standards: passed
    

    The PR intentionally remains permission-rule enforcement rather than an OS sandbox; race-resistant filesystem enforcement is outside its scope, as you noted.

  5. knp-sap commented on Nov 18, 2026

    @knp-sap
    Contributor

    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.

  6. Dopetaiga commented on Nov 18, 2026

    @Dopetaiga

    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:

    1. an always-ask gate that bypasses evaluation — changes what an explicit allow means, or
    2. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions