[1-day] OpenCode Issue #26514
이번엔 CVE는 아니고 OpenCode의 Github Issue #26514이다.
이 이슈는 Plan Mode의 메인 agent에서는 edit과 write가 차단되지만 task 도구로 생성한 subagent는 파일을 수정할 수 있는 문제이다.
Issue
Github Issue - Subagents Bypass Plan Mode READ-ONLY Restrictions #26514
- Fix PR: #26597
- 최초 수정 포함 릴리스: v1.14.46
- 취약 분석 커밋:
cd74f3ff329d40d6d6574e2a213233f2ef06c85c - 수정 커밋:
6346ef07fb0194a1fa25fe644b594fa1a2a9ab2c
보안 영향은 OpenCode가 접근할 수 있는 파일의 무결성 훼손이다.
분석 환경 구축
분석 결과를 재현하기 위해 Docker 컨테이너 안에 두 커밋을 브랜치로 준비한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# syntax=docker/dockerfile:1
FROM oven/bun:1.3.13-debian
ARG OPENCODE_COMMIT=cd74f3ff329d40d6d6574e2a213233f2ef06c85c
ENV DEBIAN_FRONTEND=noninteractive \
CI=1 \
HUSKY=0
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
bash build-essential ca-certificates git jq less \
node-gyp pkg-config python3 ripgrep vim \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /opt/opencode
RUN git init \
&& git remote add origin https://github.com/anomalyco/opencode.git \
&& git fetch --depth=2 origin refs/pull/26597/head \
&& test "$(git rev-parse FETCH_HEAD^)" = "${OPENCODE_COMMIT}" \
&& git branch issue-26514-fixed FETCH_HEAD \
&& git checkout -b issue-26514-vulnerable "${OPENCODE_COMMIT}"
RUN --mount=type=cache,target=/root/.bun/install/cache \
bun install --filter ./packages/opencode \
&& git restore bun.lock
CMD ["/bin/bash"]
Patch Diff
1
git diff --stat issue-26514-vulnerable issue-26514-fixed
권한 전달과 회귀 테스트에 해당하는 세 파일만 변경됐다.
1
2
3
4
5
git diff --unified=30 \
issue-26514-vulnerable issue-26514-fixed -- \
packages/opencode/src/tool/task.ts \
packages/opencode/src/agent/subagent-permissions.ts \
packages/opencode/test/agent/plan-mode-subagent-bypass.test.ts
읽다보면 반복해서 등장하는 값이 있다.
parent.agentparent.permissionnext.permissionsession.permissionPermission.merge()
이번 문제는 권한 규칙이 존재하지 않았던 것이 아니라 부모 권한을 읽어야 하는 위치가 잘못된 것 같다고 생각했다.
취약 코드 분석
agent.ts
1
2
3
4
git switch issue-26514-vulnerable
rg -n -C 18 'plan:|name: "plan"|edit:' \
packages/opencode/src/agent/agent.ts
plan agent의 설정에는 다음과 같은 규칙이 있다.
1
2
3
edit:
"*": deny
plan 문서 경로: allow
즉 Plan Mode의 read-only 제한은 session.permission이 아니라 planAgent.permisson에 저장된다.
반면 general subagent에는 같은 edit deny가 없다. 따라서 부모의 제한이 전달되지 않으면 general은 자신의 기본 권한으로 파일을 수정할 수 있다.
task.ts
1
sed -n '55,130p' packages/opencode/src/tool/task.ts
취약 버전의 TaskTool은 부모 세션을 읽은 다음 다음 규칙만 하위 세션에 전달한다.
1
2
3
parent.permission
- external_directory 규칙
- action이 deny인 규칙
문제는 여기서 parent가 부모 agent가 아니라 부모 session이라는 점이다.
데이터 흐름을 단순화하면 다음과 같다.
1
2
3
4
Plan Mode edit deny
-> parent agent.permission에 존재
-> task.ts는 parent session.permission만 확인
-> child session에 edit deny가 전달되지 않음
부모가 직접 수정할 때는 agent 규칙이 적용되지만 subagent를 만드는 순간 그 규칙이권한 전파 경로에서 사라진다.
prompt.ts
1
2
3
rg -n -C 8 \
'Permission.merge\(input.agent.permission|Permission.merge\(taskAgent.permission' \
packages/opencode/src/session/prompt.ts
subagent가 실제 도구를 호출할 때 사용되는 권한은 다음과 같이 만들어진다.
1
2
3
effective permission
= subagent agent.permission
+ child session.permission
취약 버전에서는 child session에 Plan Mode의 edit deny가 없다.
따라서 generalAgent.permission이 edit을 허용한다면 최종 결과도 allow가 된다.
permission/evaluate.ts
1
2
3
4
sed -n '1,180p' packages/opencode/src/permission/evaluate.ts
rg -n -C 10 'export function merge|EDIT_TOOLS|export function disabled' \
packages/opencode/src/permission/index.ts
Permission.merge()는 규칙 배열을 평평하게 이어 붙인다. evaluate()는 permission과 pattern이 일치하는 규칙 중 마지막 규칙을 선택한다.
또한 edit, write, apply_patch는 도구 노출 단계에서 모두 edit 권한군으로 정규화된다. 따라서 Plan Mode의 edit deny가 전달되지 않는 문제는 여러 파일 변경 도구에 영향을 준다.
Regression Test
수정 PR에는 실제 LLM 호출 없이 권한 계산만 결정론적으로 검증하는 회귀 테스트가 추가됐다.
1
2
rg -n -C 30 '#26514' \
packages/opencode/test/agent/plan-mode-subagent-bypass.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
1-/**
2: * Reproducer for opencode issue #26514:
3- *
4- * In Plan Mode (the `plan` agent), the main agent's edit/write tools are
5- * blocked by the plan agent's permission ruleset (`edit: { "*": "deny" }`).
6- * However, when the plan agent spawns a subagent via the `task` tool, the
7- * subagent retains full file modification capabilities — a security bypass.
8- *
9- * This test replicates the permission ruleset that would govern a
10- * `general` subagent when launched from a `plan` parent session, mirroring
11- * the logic in `src/tool/task.ts` (filtered parent permissions ++ runtime
12- * subagent agent permissions, evaluated as in `session/prompt.ts`).
13- *
14- * The expected (secure) behavior is that the subagent inherits the plan
15- * mode read-only restriction and `edit`/`write` resolve to `deny`. On
16- * origin/dev this assertion fails because the parent **agent** permissions
17- * are not propagated to the subagent — only the parent **session**
18- * permissions are passed through, and Plan Mode's restrictions live on the
19- * agent, not the session.
20- */
21-import { test, expect, afterEach } from "bun:test"
22-import { Effect } from "effect"
23-import { disposeAllInstances, provideInstance, tmpdir } from "../fixture/fixture"
24-import { WithInstance } from "../../src/project/with-instance"
25-import { Agent } from "../../src/agent/agent"
26-import { Permission } from "../../src/permission"
27-
28-afterEach(async () => {
29- await disposeAllInstances()
30-})
31-
32-function load<A>(dir: string, fn: (svc: Agent.Interface) => Effect.Effect<A>) {
33- return Effect.runPromise(provideInstance(dir)(Agent.Service.use(fn)).pipe(Effect.provide(Agent.defaultLayer)))
34-}
35-
36-/**
37- * Replicates the subagent session permission construction in
38- * `packages/opencode/src/tool/task.ts` (~lines 74-101). Only `external_directory`
39- * rules and any `deny` rules from the parent session's `permission` field are
40- * forwarded to the subagent session; the `todowrite` and `task` denies are
41- * appended unconditionally for `general`.
42- */
43-function deriveSubagentSessionPermission(
44- parentSessionPermission: Permission.Ruleset,
45- subagent: Agent.Info,
46-): Permission.Ruleset {
47- const canTask = subagent.permission.some((rule) => rule.permission === "task")
48- const canTodo = subagent.permission.some((rule) => rule.permission === "todowrite")
49- return [
50- ...(parentSessionPermission ?? []).filter(
51- (rule) => rule.permission === "external_directory" || rule.action === "deny",
52- ),
53- ...(canTodo ? [] : [{ permission: "todowrite" as const, pattern: "*" as const, action: "deny" as const }]),
54- ...(canTask ? [] : [{ permission: "task" as const, pattern: "*" as const, action: "deny" as const }]),
55- ]
56-}
57-
58:test("[#26514] subagent spawned from plan mode inherits read-only restriction (edit denied)", async () => {
59- await using tmp = await tmpdir()
60- await WithInstance.provide({
61- directory: tmp.path,
62- fn: async () => {
63- const planAgent = await load(tmp.path, (svc) => svc.get("plan"))
64- const generalAgent = await load(tmp.path, (svc) => svc.get("general"))
65-
66- expect(planAgent).toBeDefined()
67- expect(generalAgent).toBeDefined()
68- // Sanity: the plan agent itself blocks edit. (Note: `write` and
69- // `apply_patch` route through the `edit` permission at the runtime
70- // tool layer — see Permission.disabled / EDIT_TOOLS.)
71- expect(Permission.evaluate("edit", "/some/file.ts", planAgent!.permission).action).toBe("deny")
72-
73- // Simulate the plan-mode parent session: in real flow the plan
74- // session's `permission` field is empty (Plan Mode lives on the agent
75- // ruleset, not the session). So we pass [] through as the parent
76- // session permission, exactly like the actual code path.
77- const parentSessionPermission: Permission.Ruleset = []
78-
79- const subagentSessionPermission = deriveSubagentSessionPermission(parentSessionPermission, generalAgent!)
80-
81- // Mirror the runtime evaluation in session/prompt.ts (~line 410, 639):
82- // ruleset: Permission.merge(agent.permission, session.permission ?? [])
83- const effective = Permission.merge(generalAgent!.permission, subagentSessionPermission)
84-
85- expect(Permission.evaluate("edit", "/some/file.ts", effective).action).toBe("deny")
86- expect(Permission.evaluate("edit", "/another/path/index.tsx", effective).action).toBe("deny")
87- },
88- })
89-})
90-
91:test("[#26514] explore subagent launched from plan mode also stays read-only", async () => {
92- // Sibling check: even though `explore` is intrinsically read-only, the
93- // bug surface is the same. Including this case to document that the fix
94- // should propagate the parent **agent** permissions, not just deny edit
95- // when the subagent happens to already deny it.
96- await using tmp = await tmpdir()
97- await WithInstance.provide({
98- directory: tmp.path,
99- fn: async () => {
100- const planAgent = await load(tmp.path, (svc) => svc.get("plan"))
101- const explore = await load(tmp.path, (svc) => svc.get("explore"))
102- expect(planAgent).toBeDefined()
103- expect(explore).toBeDefined()
104-
105- const parentSessionPermission: Permission.Ruleset = []
106- const subagentSessionPermission = deriveSubagentSessionPermission(parentSessionPermission, explore!)
107- const effective = Permission.merge(explore!.permission, subagentSessionPermission)
108-
109- // Already deny — sanity check.
110- expect(Permission.evaluate("edit", "/x.ts", effective).action).toBe("deny")
111- },
112- })
113-})
114-
115:test("[#26514] custom user subagent launched from plan mode bypasses Plan Mode read-only", async () => {
116- // The most damaging case: a user-defined subagent with default
117- // permissions (allow-by-default, like `general`). The subagent must NOT
118- // be able to edit when the parent agent is `plan`.
119- await using tmp = await tmpdir({
120- config: {
121- agent: {
122- my_subagent: {
123- description: "A user-defined subagent",
124- mode: "subagent",
125- },
126- },
127- },
128- })
129- await WithInstance.provide({
130- directory: tmp.path,
131- fn: async () => {
132- const planAgent = await load(tmp.path, (svc) => svc.get("plan"))
133- const my = await load(tmp.path, (svc) => svc.get("my_subagent"))
134- expect(planAgent).toBeDefined()
135- expect(my).toBeDefined()
136-
137- const parentSessionPermission: Permission.Ruleset = []
138- const subagentSessionPermission = deriveSubagentSessionPermission(parentSessionPermission, my!)
139- const effective = Permission.merge(my!.permission, subagentSessionPermission)
140-
141- // BUG: on origin/dev edit resolves to "allow" because the plan
142- // agent's `edit: deny *` rule never reaches the subagent.
143- expect(Permission.evaluate("edit", "/some/file.ts", effective).action).toBe("deny")
144- },
145- })
테스트 시나리오는 세 가지이다.
- Plan agent ->
generalsubagent - Plan agent -> 이미 read-only인
exploresubagent - Plan agent -> 기본 권한의 사용자 정의 subagent
각 테스트는 다음 형태로 최종 권한을 계산한다.
1
2
Permission.merge(subagent.permission, subagentSessionPermission)
Permission.evaluate("edit", targetPath, effective)
기대 결과는 모두 deny이다.
Vulnerable Version Test
1
bun test test/agent/plan-mode-subagent-bypass.test.ts
explore는 자체 권한이 원래부터 read-only이므로 부모 규칙을 잃어도 edit가 deny되어 통과한다.
반대로 general과 사용자 정의 subagent는 자체 edit 권한을 가지고 있으므로 Plan Mode 제한이 사라진 사실이 그대로 드러난다.
이 결과로 취약 버전에서 다음 상태를 확인할 수 있었다.
1
2
3
main plan agent: edit -> deny
general subagent: edit -> allow
custom subagent: edit -> allow
Fixed Version Test
수정 버전에는 deriveSubagentSessionPermission() 함수가 새로 추가됐다.
1
2
sed -n '1,180p' \
packages/opencode/src/agent/subagent-permissions.ts
초기 수정의 핵심은 부모 agent의 deny 규칙도 하위 세션으로 전달하는 것이다.
1
2
3
parent agent deny rules
+ parent session deny/external_directory rules
+ default subagent restrictions
task.ts도 부모 세션의 agent 이름으로 실제 부모 agent를 조회한 뒤 helper에 함께 넘기도록 바뀌었다.
1
sed -n '55,115p' packages/opencode/src/tool/task.ts
수정 브랜치에서 동일한 테스트를 실행한다.
1
bun test test/agent/plan-mode-subagent-bypass.test.ts
동일한 테스트가 취약 버전에서는 red, 수정 버전에서는 green이 됐다.
Root Cause
근본 원인은 agent-level policy와 session-level policy를 서로 다른 위치에 저장하면서 subagent 위임 코드가 session-level policy만 복사한 것이다.
1
Security policy source != Delegation policy source
Plan Mode 제한의 실제 출처는 다음과 같다.
1
parent agent.permission
하지만 취약한 위임 코드는 다음 값만 신뢰했다.
1
parent session.permission
따라서 부모에서 유효한 제한이 위임 경계를 넘는 순간 소실됐다.
보안 설계 관점에서는 subagent를 새로운 독립 사용자처럼 취급하면 안 된다. 부모의 권한으로 시작된 위임이라면 자식의 유효 권한은 부모의 보안 경계를 넘지 않아야 하거나, 경계를 넘는 위임을 명시적으로 승인받아야 한다.









