Skip to content

Commit a0b1eea

Browse files
hkaltaiclaude
andcommitted
fix(permission): let resolved twins only tighten, and keep project files spelled through a link inside
A generated allow twin was appended right after its rule, so it could land after a deny the user wrote for the real path and win under last-match-wins: {"/private/tmp/*": "deny", "/tmp/*": "allow"} allowed /private/tmp/x. Allow twins now go before the authored rules of the same config, so an authored deny or ask for the real path keeps winning while an unmatched real path still gets the allow. Deny and ask twins still follow their rule. The in-project check compared the authored path lexically against the realpath'd project directory, so a project file spelled through a link to the project (/var vs /private/var, a symlinked ~/code) was treated as external: builder prompted and analyst refused its own files. The authored side is now decided on the real location of the parent, so an outside link entry still asks while files under it stay inside. The link-budget error carries code ELOOP, and a rule whose resolved twin cannot be built is logged at debug level. Docs: the agent permissions example uses builder, since analyst's shell is always denied, and the analyst pages say a global "*": "allow" also turns on MCP and custom tools for analyst, including ones that write. Tests: twin vs an authored deny in both orders, a project file spelled through a link in both check variants, patterned analyst grants, and two skill folders with a sibling folder sharing a prefix. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6b14216 commit a0b1eea

9 files changed

Lines changed: 142 additions & 15 deletions

File tree

‎docs/docs/configure/agents.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ The agent for asking questions about your data. Truly read-only mode for safe da
2929
- **Web**: Fetch and search allowed without prompts
3030
- **Schema/warehouse/finops**: All inspection tools available
3131
- **Workspace knowledge**: Loads workspace and project skills; reads workspace memory and views this checkout's memory audit log. Can read files bundled with skills, including global skills stored outside the project. Reloading memory syncs the local copy with the workspace, which can remove a local copy of a block the workspace archived. Saving memory is done with `builder`.
32-
- **Config overrides**: A permission config such as `"*": "allow"` cannot turn file edits, SQL writes (including data diffs of arbitrary queries), shell, memory saves, warehouse connection or MCP config changes, training imports, sample project setup, feedback submission, batch tool calls or delegation beyond `data-explorer` back on
32+
- **Config overrides**: A permission config such as `"*": "allow"` cannot turn file edits, SQL writes (including data diffs of arbitrary queries), shell, memory saves, warehouse connection or MCP config changes, training imports, sample project setup, feedback submission, batch tool calls or delegation beyond `data-explorer` back on A global `"*": "allow"` does turn on MCP and custom tools for analyst, including ones that write (for example a SQL MCP server); to keep them from analyst, put the `"*": "allow"` under `agent.builder` instead of the global config, or deny those tools under `agent.analyst.permission`.
3333

3434
!!! tip
3535
Use `analyst` when exploring data to ensure no accidental writes. Switch to `builder` when you're ready to create or modify models.
@@ -122,7 +122,7 @@ Each agent can have its own permission overrides:
122122
```json
123123
{
124124
"agent": {
125-
"analyst": {
125+
"builder": {
126126
"permission": {
127127
"write": "deny",
128128
"edit": "deny",
@@ -138,6 +138,8 @@ Each agent can have its own permission overrides:
138138
}
139139
```
140140

141+
`analyst` already denies its shell and built-in write tools whatever its config says, so its config is only useful to restrict it further (for example `"webfetch": "deny"`) or to allow MCP and custom tools.
142+
141143
!!! warning
142144
Agent-specific permissions override global permissions. A `"deny"` at the agent level cannot be overridden by a global `"allow"`.
143145

‎docs/docs/configure/permissions.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ Override permissions for specific agents:
8080
}
8181
```
8282

83-
The `analyst` agent's shell and built-in write tools (file edits, SQL writes, memory saves and the other built-in tools that change state) stay denied even if its permission config allows them. Training entries remain available through `training_save` and `training_remove`, and analyst can create session scratch tables. MCP and custom tools follow your config, and config can still restrict analyst further.
83+
The `analyst` agent's shell and built-in write tools (file edits, SQL writes, memory saves and the other built-in tools that change state) stay denied even if its permission config allows them. Training entries remain available through `training_save` and `training_remove`, and analyst can create session scratch tables. MCP and custom tools follow your config, so a global `"*": "allow"` turns them on for analyst too, including ones that write. Config can still restrict analyst further.
8484

8585
Rules are evaluated in order and the last matching rule wins, so put a `"*"` rule before the more specific patterns it should not override.
8686

‎docs/docs/data-engineering/agent-modes.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ Analyst mode enforces strict guardrails:
9090
- **No file writes.** Cannot modify your codebase
9191
- **No shell.** Bash is denied. Files are read with the read, grep and glob tools
9292
- **No memory saves.** Workspace memory blocks can be read, but not saved, extracted or deleted (use builder). Training entries can still be saved and removed
93-
- **Config cannot lift these.** A permission config such as `"*": "allow"` does not turn file edits, SQL writes (including data diffs of arbitrary queries), shell, memory saves, warehouse connection or MCP config changes, training imports, sample project setup, feedback submission, batch tool calls or delegation beyond `data-explorer` back on for analyst
93+
- **Config cannot lift these.** A permission config such as `"*": "allow"` does not turn file edits, SQL writes (including data diffs of arbitrary queries), shell, memory saves, warehouse connection or MCP config changes, training imports, sample project setup, feedback submission, batch tool calls or delegation beyond `data-explorer` back on for analyst MCP and custom tools are not covered: a global `"*": "allow"` turns them on for analyst too, including ones that write.
9494
- **Skill files readable.** Files bundled with a skill, including global skills stored outside the project, can be read
9595
- **Full web access.** Fetch and search allowed without prompts
9696
- **All inspection tools.** Schema, warehouse, finops, lineage, and core analysis tools available

‎packages/opencode/src/permission/index.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ import os from "os"
88
import path from "path"
99
import { FSUtil } from "@opencode-ai/core/fs-util"
1010
import { Filesystem } from "@/util/filesystem"
11+
// altimate_change start — log rules whose resolved twin cannot be built
12+
import { Log } from "@/util/log"
13+
14+
const log = Log.create({ service: "permission" })
15+
// altimate_change end
1116
// altimate_change end
1217
import { PermissionV1 } from "@opencode-ai/core/v1/permission"
1318
import { EventV2Bridge } from "@/event-v2-bridge"
@@ -216,12 +221,21 @@ export function fromConfig(permission: ConfigPermissionV1.Info) {
216221
continue
217222
}
218223
// altimate_change start — external_directory also asks for a path's symlink-resolved directory,
219-
// so a directory rule covers its resolved spelling too (e.g. macOS /tmp -> /private/tmp)
224+
// so a directory rule covers its resolved spelling too (e.g. macOS /tmp -> /private/tmp).
225+
// A generated twin may only tighten: deny/ask twins follow their rule, but allow twins go
226+
// before this map's authored rules, so a deny or ask the user wrote for the real path still
227+
// wins (last match wins) while an unmatched real path still gets the allow.
228+
const allowTwins: PermissionV1.Rule[] = []
229+
const rules: PermissionV1.Rule[] = []
220230
for (const [pattern, action] of Object.entries(value)) {
221-
ruleset.push({ permission: key, pattern: expand(pattern), action })
231+
rules.push({ permission: key, pattern: expand(pattern), action })
222232
const resolved = key === "external_directory" ? resolvedDirectoryPattern(expand(pattern)) : undefined
223-
if (resolved) ruleset.push({ permission: key, pattern: resolved, action })
233+
if (!resolved) continue
234+
const twin = { permission: key, pattern: resolved, action }
235+
if (action === "allow") allowTwins.push(twin)
236+
else rules.push(twin)
224237
}
238+
ruleset.push(...allowTwins, ...rules)
225239
// altimate_change end
226240
}
227241
return ruleset
@@ -238,7 +252,8 @@ function resolvedDirectoryPattern(pattern: string) {
238252
const resolved = (() => {
239253
try {
240254
return Filesystem.realLocation(dir)
241-
} catch {
255+
} catch (error) {
256+
log.debug("no resolved twin for external_directory rule", { pattern, error: String(error) })
242257
return undefined
243258
}
244259
})()

‎packages/opencode/src/tool/external-directory.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,12 @@ function authoredPath(target: string) {
4141
return path.resolve(FSUtil.windowsPath(target))
4242
}
4343

44-
function containsAuthoredPath(filepath: string, directory: string, worktree: string) {
44+
function containsAuthoredPath(target: string, directory: string, worktree: string) {
45+
// Resolve the parent, not the entry: an outside link into the project stays outside (its
46+
// delete or move acts on the outside entry), while a project file spelled through a link to
47+
// the project (e.g. /var -> /private/var) stays inside.
48+
const parent = Filesystem.realLocation(path.dirname(target))
49+
const filepath = parent ? path.join(parent, path.basename(target)) : target
4550
if (FSUtil.contains(directory, filepath)) return true
4651
if (worktree === "/") return false
4752
return FSUtil.contains(worktree, filepath)

‎packages/opencode/src/util/filesystem.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,8 @@ export namespace Filesystem {
251251
} catch {
252252
return undefined
253253
}
254-
if (--budget.links < 0) throw new Error(`Too many symbolic links while resolving ${link}`)
254+
if (--budget.links < 0)
255+
throw Object.assign(new Error(`Too many symbolic links while resolving ${link}`), { code: "ELOOP" })
255256
// Concatenated, not joined: join would collapse ".." in the target before the walk follows it.
256257
return resolveLocation(isAbsolute(target) ? target : `${dir}${sep}${target}`, budget)
257258
}

‎packages/opencode/test/agent/analyst-data-explorer.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,3 +567,56 @@ if (process.platform !== "win32") {
567567
{ config: { skills: { paths: [externalSkills] } } },
568568
)
569569
}
570+
571+
// A second skill root, plus a sibling folder whose name only extends a skill folder's name.
572+
const otherSkills = fs.mkdtempSync(path.join(os.tmpdir(), "analyst-team-skills-"))
573+
fs.mkdirSync(path.join(otherSkills, "style"), { recursive: true })
574+
fs.writeFileSync(
575+
path.join(otherSkills, "style", "SKILL.md"),
576+
"---\nname: style\ndescription: SQL style.\n---\n\nSee style.md.\n",
577+
)
578+
fs.mkdirSync(path.join(externalSkills, "naming-evil"), { recursive: true })
579+
afterAll(() => fs.rmSync(otherSkills, { recursive: true, force: true }))
580+
581+
it.instance(
582+
"analyst can read every discovered skill folder but not a sibling folder sharing a prefix",
583+
() =>
584+
Effect.gen(function* () {
585+
const analyst = (yield* Agent.use.get("analyst"))!
586+
expect(action(analyst, "external_directory", path.join(externalSkills, "naming", "*"))).toBe("allow")
587+
expect(action(analyst, "external_directory", path.join(otherSkills, "style", "*"))).toBe("allow")
588+
expect(action(analyst, "external_directory", path.join(externalSkills, "naming-evil", "*"))).toBe("deny")
589+
expect(action(analyst, "external_directory", path.join(externalSkills, "*"))).toBe("deny")
590+
}),
591+
{ config: { skills: { paths: [externalSkills, otherSkills] } } },
592+
)
593+
594+
// Patterned grants match only some inputs; the re-applied "*" deny still wins for every input.
595+
it.instance(
596+
"analyst keeps write tools denied under patterned config grants",
597+
() =>
598+
Effect.gen(function* () {
599+
const analyst = (yield* Agent.use.get("analyst"))!
600+
expect(action(analyst, "sql_execute_write", "INSERT INTO t VALUES (1)")).toBe("deny")
601+
expect(action(analyst, "edit", "models/orders.sql")).toBe("deny")
602+
expect(action(analyst, "bash", "ls -la")).toBe("deny")
603+
expect(action(analyst, "altimate_memory_write", "naming-rule")).toBe("deny")
604+
expect(Permission.disabled(["sql_execute_write", "edit", "bash"], analyst.permission)).toEqual(
605+
new Set(["sql_execute_write", "edit", "bash"]),
606+
)
607+
}),
608+
{
609+
config: {
610+
agent: {
611+
analyst: {
612+
permission: {
613+
sql_execute_write: { "INSERT *": "allow" },
614+
edit: { "models/*": "allow" },
615+
bash: { "ls *": "allow" },
616+
altimate_memory_write: { "naming-*": "allow" },
617+
},
618+
},
619+
},
620+
},
621+
},
622+
)

‎packages/opencode/test/permission/next.test.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,20 +128,43 @@ test.skipIf(process.platform === "win32")(
128128
try {
129129
fs.mkdirSync(path.join(root, "real"))
130130
fs.symlinkSync(path.join(root, "real"), path.join(root, "link"))
131+
// An allow twin goes before the authored rules, so it never outranks one of them.
131132
expect(Permission.fromConfig({ external_directory: { [path.join(root, "link", "*")]: "allow" } })).toEqual([
132-
{ permission: "external_directory", pattern: path.join(root, "link", "*"), action: "allow" },
133133
{ permission: "external_directory", pattern: path.join(root, "real", "*"), action: "allow" },
134+
{ permission: "external_directory", pattern: path.join(root, "link", "*"), action: "allow" },
134135
])
135136
// Wildcard rules keep their wildcard part, and a directory that does not exist yet resolves
136137
// through its nearest existing ancestor.
137-
expect(Permission.fromConfig({ external_directory: { [path.join(root, "link", "**")]: "allow" } })[1]).toEqual({
138+
expect(Permission.fromConfig({ external_directory: { [path.join(root, "link", "**")]: "allow" } })[0]).toEqual({
138139
permission: "external_directory",
139140
pattern: path.join(root, "real", "**"),
140141
action: "allow",
141142
})
142143
expect(
143144
Permission.fromConfig({ external_directory: { [path.join(root, "link", "later", "*")]: "deny" } })[1],
144145
).toEqual({ permission: "external_directory", pattern: path.join(root, "real", "later", "*"), action: "deny" })
146+
// A generated twin only tightens: a deny written for the real path keeps winning over a later
147+
// allow written for the link, in either order, while an unmatched real path still gets the allow.
148+
const deny = (first: "deny" | "allow") =>
149+
Permission.fromConfig({
150+
external_directory:
151+
first === "deny"
152+
? { [path.join(root, "real", "secret", "*")]: "deny", [path.join(root, "link", "*")]: "allow" }
153+
: { [path.join(root, "link", "*")]: "allow", [path.join(root, "real", "secret", "*")]: "deny" },
154+
})
155+
for (const first of ["deny", "allow"] as const) {
156+
const rules = deny(first)
157+
const at = (...p: string[]) =>
158+
Permission.evaluate("external_directory", path.join(root, ...p, "*"), rules).action
159+
expect(at("real", "secret"), first).toBe("deny")
160+
expect(at("real", "other"), first).toBe("allow")
161+
expect(at("link", "other"), first).toBe("allow")
162+
}
163+
// A deny twin still follows its rule, so it tightens the real spelling too.
164+
const denyLink = Permission.fromConfig({
165+
external_directory: { [path.join(root, "*")]: "allow", [path.join(root, "link", "*")]: "deny" },
166+
})
167+
expect(Permission.evaluate("external_directory", path.join(root, "real", "x", "*"), denyLink).action).toBe("deny")
145168
// Other permissions and non-symlinked directories get no extra rule.
146169
expect(Permission.fromConfig({ read: { [path.join(root, "link", "*")]: "allow" } })).toHaveLength(1)
147170
expect(Permission.fromConfig({ external_directory: { [path.join(root, "real", "*")]: "allow" } })).toHaveLength(1)

‎packages/opencode/test/tool/external-directory.test.ts‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,12 @@ describe("tool.assertExternalDirectory", () => {
7272
const outside = yield* tmpdirScoped()
7373
const link = path.join(outside, "project-link")
7474
fs.symlinkSync(test.directory, link, process.platform === "win32" ? "junction" : "dir")
75-
const target = path.join(link, "file.txt")
75+
// The link entry itself: deleting or moving it acts on the outside directory.
76+
const target = link
7677
const expected =
7778
process.platform === "win32"
78-
? path.join(path.resolve(Filesystem.windowsPath(link)), "*")
79-
: glob(path.join(link, "*"))
79+
? path.join(path.resolve(Filesystem.windowsPath(outside)), "*")
80+
: glob(path.join(outside, "*"))
8081

8182
const { requests, ctx } = makeCtx()
8283
yield* assertExternalDirectoryEffect(ctx, target)
@@ -96,6 +97,33 @@ describe("tool.assertExternalDirectory", () => {
9697
}),
9798
)
9899

100+
it.instance("treats a project file spelled through a link to the project as inside it", () =>
101+
Effect.gen(function* () {
102+
const test = yield* TestInstance
103+
const outside = yield* tmpdirScoped()
104+
const link = path.join(outside, "project-link")
105+
fs.symlinkSync(test.directory, link, process.platform === "win32" ? "junction" : "dir")
106+
// Same shape as /var/... for a project at /private/var/... on macOS.
107+
const target = path.join(link, "file.txt")
108+
109+
const { requests, ctx } = makeCtx()
110+
yield* assertExternalDirectoryEffect(ctx, target)
111+
expect(requests).toEqual([])
112+
113+
const legacy: string[][] = []
114+
const instance = yield* InstanceState.context
115+
yield* Effect.promise(() =>
116+
Instance.restore(instance, () =>
117+
assertExternalDirectoryLegacy(
118+
{ ...baseCtx, metadata: () => {}, ask: async (req) => void legacy.push([...req.patterns]) },
119+
target,
120+
),
121+
),
122+
)
123+
expect(legacy).toEqual([])
124+
}),
125+
)
126+
99127
if (process.platform !== "win32") {
100128
it.instance("preserves a literal backslash in an external POSIX directory", () =>
101129
Effect.gen(function* () {

0 commit comments

Comments
 (0)