oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package provider
2
3import (
4 "encoding/json"
5 "errors"
6 "os"
7 "path/filepath"
8 "slices"
9 "strings"
10 "testing"
11)
12
13// opencodeFixture is an OpenCode launch's inputs on disk: a sealed tree
14// holding the binary, the pinned files, the prepared runtime home and a
15// workspace.
16func opencodeFixture(t *testing.T, action string, tools []string) OpenCodePolicyInputs {
17 t.Helper()
18 root := t.TempDir()
19 file := func(name, content string, mode os.FileMode) string {
20 p := filepath.Join(root, name)
21 if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
22 t.Fatal(err)
23 }
24 if err := os.WriteFile(p, []byte(content), mode); err != nil {
25 t.Fatal(err)
26 }
27 return p
28 }
29 tree := filepath.Join(root, "opencode", "node_modules")
30 binary := file("opencode/node_modules/@opencode/cli-linux-x64/bin/opencode", "opencode binary", 0755)
31 file("opencode/node_modules/@opencode/cli/package.json", "{}", 0644)
32 t.Cleanup(func() { unsealTree(tree) })
33 if err := SealTree(tree); err != nil {
34 t.Fatal(err)
35 }
36 treeSum, err := TreeSHA256(tree)
37 if err != nil {
38 t.Fatal(err)
39 }
40 home := filepath.Join(root, "homes", "opencode-home")
41 if err := os.MkdirAll(home, 0700); err != nil {
42 t.Fatal(err)
43 }
44 work := filepath.Join(root, "work")
45 if err := os.Mkdir(work, 0700); err != nil {
46 t.Fatal(err)
47 }
48 readOnly := action != "implement"
49 in := OpenCodePolicyInputs{
50 Binary: binary, BinarySHA256: digest([]byte("opencode binary")), Tree: tree, TreeSHA256: treeSum,
51 Bwrap: file("bwrap", "bwrap", 0755), ToolProxy: file("proxy", "proxy", 0755),
52 Home: home, Workspace: work, Action: action, Provider: "opencode-go", Model: "glm-5.3", KeyEnv: "OPENCODE_GO_API_KEY",
53 Tools: tools, EgressHosts: []string{"opencode.ai"}, Config: OpenCodeConfig("opencode-go", "glm-5.3", tools, readOnly),
54 }
55 if err := WriteOpenCodeConfig(in); err != nil {
56 t.Fatal(err)
57 }
58 return in
59}
60
61var opencodeReview = []string{"read", "glob", "grep", "equipo_submit_review", "equipo_ask_person"}
62var opencodeEngineering = []string{"read", "glob", "grep", "edit", "shell", "equipo_submit_candidate"}
63
64type rule struct{ Action, Resource, Effect string }
65
66// effect is OpenCode's own rule: the last matching rule wins, and no
67// match asks.
68func effect(rules []rule, action string) string {
69 out := "ask"
70 for _, r := range rules {
71 if r.Action == action || r.Action == "*" {
72 out = r.Effect
73 }
74 }
75 return out
76}
77
78func permissionsOf(t *testing.T, raw json.RawMessage) []rule {
79 t.Helper()
80 var c struct {
81 Permissions []rule `json:"permissions"`
82 }
83 if err := json.Unmarshal(raw, &c); err != nil {
84 t.Fatal(err)
85 }
86 return c.Permissions
87}
88
89// An OpenCode policy fixes everything OpenCode loads: its ACP mode, the
90// isolating switches in an environment with no inherited variable and no
91// key, the configuration in the runtime home exactly as Equipo wrote it
92// (one provider, one model, Equipo's MCP server, no title, summary or
93// automatic compaction call), the role's permissions, and the binary
94// alone mounted from the pinned tree.
95func TestOpenCodePolicyIsolatedConfiguration(t *testing.T) {
96 in := opencodeFixture(t, "inspect", opencodeReview)
97 p, err := BuildOpenCodePolicy(in)
98 if err != nil {
99 t.Fatal(err)
100 }
101 if !p.IsOpenCode() || p.IsPi() || p.IsCheck() || p.IsSignIn() || p.Coordinator() || !p.ReadOnlyWorkspace() || p.Harness() != "opencode" || p.KeyEnv() != "OPENCODE_GO_API_KEY" {
102 t.Fatalf("policy kind: opencode %v ro %v harness %q key %q", p.IsOpenCode(), p.ReadOnlyWorkspace(), p.Harness(), p.KeyEnv())
103 }
104 if !slices.Equal(p.OpenCodeArgv(), []string{"/opt/opencode", "acp"}) {
105 t.Fatalf("argv %q", p.OpenCodeArgv())
106 }
107 env := map[string]string{"LANG": "C.UTF-8", "XDG_CONFIG_HOME": "/home/runner/.config", "XDG_DATA_HOME": "/home/runner/.local/share", "XDG_STATE_HOME": "/home/runner/.local/state", "XDG_CACHE_HOME": "/home/runner/.cache",
108 "OPENCODE_DISABLE_PROJECT_CONFIG": "1", "OPENCODE_DISABLE_CLAUDE_CODE": "1", "OPENCODE_DISABLE_MODELS_FETCH": "1", "OPENCODE_DISABLE_AUTOUPDATE": "1", "OPENCODE_DISABLE_FREE_MODELS": "1", "OPENCODE_DISABLE_FILEWATCHER": "1"}
109 if len(p.Env) != len(env) {
110 t.Fatalf("env %v", p.Env)
111 }
112 for k, v := range env {
113 if p.Env[k] != v {
114 t.Fatalf("env %s=%q want %q", k, p.Env[k], v)
115 }
116 }
117 var targets []string
118 for _, m := range p.Mounts {
119 if !m.ReadOnly {
120 t.Fatalf("writable mount %+v", m)
121 }
122 targets = append(targets, m.Target)
123 }
124 if !slices.Equal(targets, []string{"/opt/opencode", "/opt/equipo-tool-proxy"}) {
125 t.Fatalf("mounts %v", targets)
126 }
127 var c map[string]json.RawMessage
128 if err := json.Unmarshal(p.Settings, &c); err != nil {
129 t.Fatal(err)
130 }
131 keys := []string{}
132 for k := range c {
133 keys = append(keys, k)
134 }
135 slices.Sort(keys)
136 if strings.Join(keys, ",") != "agents,compaction,mcp,model,permissions,providers,share,update" {
137 t.Fatalf("config keys %v", keys)
138 }
139 for k, want := range map[string]string{
140 "update": `"disable"`,
141 "share": `"disabled"`,
142 "model": `"equipo/glm-5.3"`,
143 "agents": `{"summary":{"disabled":true},"title":{"disabled":true}}`,
144 "compaction": `{"auto":false}`,
145 "mcp": `{"equipo":{"command":["/opt/equipo-tool-proxy","--socket","/tool/equipo.sock"],"type":"local"}}`,
146 "providers": `{"equipo":{"env":["OPENCODE_GO_API_KEY"],"models":{"glm-5.3":{"name":"glm-5.3"}},"name":"opencode-go","package":"@opencode/ai/providers/openai-compatible","settings":{"baseURL":"https://opencode.ai/inference/go/openai/v1"}}}`,
147 } {
148 if string(c[k]) != want {
149 t.Fatalf("%s = %s, want %s", k, c[k], want)
150 }
151 }
152 // Review: its read tools and Equipo's, nothing else; edit and shell
153 // denied by name, and the list ends in denies.
154 rules := permissionsOf(t, p.Settings)
155 for action, want := range map[string]string{"read": "allow", "glob": "allow", "grep": "allow", "equipo_submit_review": "allow", "edit": "deny", "shell": "deny", "webfetch": "deny", "websearch": "deny", "subagent": "deny", "skill": "deny", "external_directory": "deny", "question": "deny", "equipo_submit_candidate": "deny", "anything_else": "deny"} {
156 if got := effect(rules, action); got != want {
157 t.Errorf("review %s: %s, want %s", action, got, want)
158 }
159 }
160 if rules[0] != (rule{"*", "*", "deny"}) || rules[len(rules)-1].Effect != "deny" {
161 t.Fatalf("rules %v", rules)
162 }
163 // Spec §4.2: Review gets explicit edit and shell denies, after every
164 // allow, not only the leading deny of everything.
165 tail := rules[len(rules)-2:]
166 if tail[0] != (rule{"edit", "*", "deny"}) || tail[1] != (rule{"shell", "*", "deny"}) {
167 t.Fatalf("review's last rules %v", tail)
168 }
169 for _, r := range rules {
170 if r.Effect == "ask" {
171 t.Fatalf("a rule asks: %v", r)
172 }
173 }
174 if model, resume, ok := p.OpenCodeSelection(); !ok || model != "glm-5.3" || resume != "" {
175 t.Fatalf("selection %q %q", model, resume)
176 }
177 // Engineering edits and runs commands inside the namespace.
178 eng := opencodeFixture(t, "implement", opencodeEngineering)
179 ep, err := BuildOpenCodePolicy(eng)
180 if err != nil || ep.ReadOnlyWorkspace() {
181 t.Fatalf("engineering: %v", err)
182 }
183 erules := permissionsOf(t, ep.Settings)
184 for action, want := range map[string]string{"edit": "allow", "shell": "allow", "equipo_submit_candidate": "allow", "webfetch": "deny", "external_directory": "deny"} {
185 if got := effect(erules, action); got != want {
186 t.Errorf("engineering %s: %s, want %s", action, got, want)
187 }
188 }
189 eng.Resume = "ses_e2ea2ab7effe3nyJtkcQTxERys"
190 rp, err := BuildOpenCodePolicy(eng)
191 if model, resume, ok := rp.OpenCodeSelection(); err != nil || !ok || model != "glm-5.3" || resume != eng.Resume {
192 t.Fatalf("resume %q %q %v", model, resume, err)
193 }
194}
195
196// What an OpenCode policy refuses: a read-only role with edit or shell,
197// an unknown tool, a configuration that is not exactly Equipo's (another
198// key, a plugin, an instruction, a second provider, a literal key, an ask
199// rule, a second config file beside it), an unpinned binary or tree, a
200// binary outside the tree, a model or session id that could be a path,
201// and another provider.
202func TestOpenCodePolicyRefusals(t *testing.T) {
203 edit := func(f func(c map[string]any)) func(in *OpenCodePolicyInputs) {
204 return func(in *OpenCodePolicyInputs) {
205 var c map[string]any
206 json.Unmarshal(in.Config, &c)
207 f(c)
208 in.Config, _ = json.Marshal(c)
209 if err := WriteOpenCodeConfig(*in); err != nil {
210 panic(err)
211 }
212 }
213 }
214 for _, tc := range []struct {
215 name string
216 action string
217 tools []string
218 change func(in *OpenCodePolicyInputs)
219 }{
220 {"review with shell", "inspect", []string{"read", "shell"}, nil},
221 {"review with edit", "inspect", []string{"read", "edit"}, nil},
222 {"ask with shell", "answer", []string{"read", "shell"}, nil},
223 {"unknown tool", "implement", []string{"read", "webfetch"}, nil},
224 {"a subagent tool", "implement", []string{"read", "subagent"}, nil},
225 {"an MCP tool from another server", "inspect", []string{"read", "evil_tool"}, nil},
226 {"the coordinator", "converse", opencodeReview, nil},
227 {"another provider", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Provider = "tensorx" }},
228 {"another key variable", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.KeyEnv = "TENSORX_API_KEY" }},
229 {"a model that is a path", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Model = "../glm" }},
230 {"a session id that is a path", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Resume = "../ses_x" }},
231 {"no egress", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.EgressHosts = nil }},
232 {"a plugin", "inspect", opencodeReview, edit(func(c map[string]any) { c["plugins"] = []string{"./evil.js"} })},
233 {"instructions", "inspect", opencodeReview, edit(func(c map[string]any) { c["instructions"] = []string{"AGENTS.md"} })},
234 {"warming", "inspect", opencodeReview, edit(func(c map[string]any) { c["warming"] = true })},
235 {"the title agent on", "inspect", opencodeReview, edit(func(c map[string]any) { c["agents"] = map[string]any{"summary": map[string]bool{"disabled": true}} })},
236 {"automatic compaction", "inspect", opencodeReview, edit(func(c map[string]any) { delete(c, "compaction") })},
237 {"updates on", "inspect", opencodeReview, edit(func(c map[string]any) { c["update"] = "auto" })},
238 {"sharing allowed", "inspect", opencodeReview, edit(func(c map[string]any) { c["share"] = "manual" })},
239 {"sharing left out", "inspect", opencodeReview, edit(func(c map[string]any) { delete(c, "share") })},
240 {"a literal key", "inspect", opencodeReview, edit(func(c map[string]any) {
241 c["providers"].(map[string]any)["equipo"].(map[string]any)["settings"] = map[string]string{"baseURL": "https://opencode.ai/inference/go/openai/v1", "apiKey": "sk-go-123"}
242 })},
243 {"another base URL", "inspect", opencodeReview, edit(func(c map[string]any) {
244 c["providers"].(map[string]any)["equipo"].(map[string]any)["settings"] = map[string]string{"baseURL": "https://evil.example/v1"}
245 })},
246 {"a second provider", "inspect", opencodeReview, edit(func(c map[string]any) {
247 c["providers"].(map[string]any)["evil"] = map[string]any{"package": OpenCodeProviderPackage}
248 })},
249 {"another MCP server", "inspect", opencodeReview, edit(func(c map[string]any) {
250 c["mcp"].(map[string]any)["evil"] = map[string]any{"type": "local", "command": []string{"sh"}}
251 })},
252 {"an ask rule", "inspect", opencodeReview, edit(func(c map[string]any) {
253 c["permissions"] = append(c["permissions"].([]any), map[string]string{"action": "shell", "resource": "*", "effect": "ask"})
254 })},
255 {"shell allowed for review", "inspect", opencodeReview, edit(func(c map[string]any) {
256 c["permissions"] = append(c["permissions"].([]any), map[string]string{"action": "shell", "resource": "*", "effect": "allow"})
257 })},
258 {"the config given differs from the file", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Config = json.RawMessage(`{}`) }},
259 {"a second config file", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) {
260 os.WriteFile(filepath.Join(in.Home, ".config", "opencode", "opencode.jsonc"), []byte(`{"plugins":["x"]}`), 0600)
261 }},
262 {"another binary", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.BinarySHA256 = digest([]byte("other")) }},
263 {"another tree", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.TreeSHA256 = digest([]byte("other")) }},
264 {"a binary outside the tree", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Binary = in.Bwrap; in.BinarySHA256 = digest([]byte("bwrap")) }},
265 {"a writable tree", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { unsealTree(in.Tree); os.Chmod(in.Tree, 0777) }},
266 {"a home inside the workspace", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Home = in.Workspace }},
267 {"a test authority in a release build", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) {
268 if !TestCAAllowed() {
269 in.ExtraCA = in.Bwrap
270 } else {
271 in.Tools = []string{"read", "shell"}
272 }
273 }},
274 } {
275 t.Run(tc.name, func(t *testing.T) {
276 in := opencodeFixture(t, map[bool]string{true: tc.action, false: "inspect"}[tc.action != "converse"], tc.tools)
277 in.Action = tc.action
278 if tc.action != "converse" && tc.change == nil {
279 in.Config = OpenCodeConfig(in.Provider, in.Model, tc.tools, tc.action != "implement")
280 if err := WriteOpenCodeConfig(in); err != nil {
281 t.Fatal(err)
282 }
283 }
284 if tc.change != nil {
285 tc.change(&in)
286 }
287 if p, err := BuildOpenCodePolicy(in); err == nil {
288 t.Fatalf("accepted: %s", p.Settings)
289 }
290 })
291 }
292}
293
294// The attestation reads everything again: the config file, the binary
295// (streamed) and the other pinned files, and holds the launch to the
296// selection, the session it resumes, the home and a tool socket.
297func TestOpenCodePolicyAttestation(t *testing.T) {
298 in := opencodeFixture(t, "inspect", opencodeReview)
299 p, err := BuildOpenCodePolicy(in)
300 if err != nil {
301 t.Fatal(err)
302 }
303 launch := func() Launch {
304 return Launch{ToolSocket: "/tmp/tool.sock", AttemptKey: "step/a", Workspace: in.Workspace, Selection: Selection{Provider: "opencode-go", Model: "glm-5.3", ConnectionID: "go-1"}, Binding: OpenCodeBinding("go-1", in.Home, "/keys/go-1"), Policy: p}
305 }
306 if _, err := AttestLaunch(launch(), OpenCodeArgv()); err != nil {
307 t.Fatal(err)
308 }
309 for name, change := range map[string]func(l *Launch) []string{
310 "another argv": func(l *Launch) []string { return []string{"/opt/opencode", "serve"} },
311 "another model": func(l *Launch) []string { l.Selection.Model = "kimi-k3"; return OpenCodeArgv() },
312 "another provider": func(l *Launch) []string { l.Selection.Provider = "tensorx"; return OpenCodeArgv() },
313 "a resumed session": func(l *Launch) []string { l.ResumeSessionID = "ses_e2ea2ab7effe3nyJtkcQTxERys"; return OpenCodeArgv() },
314 "no tool socket": func(l *Launch) []string { l.ToolSocket = ""; return OpenCodeArgv() },
315 "another home": func(l *Launch) []string { l.Binding.Home = in.Workspace; return OpenCodeArgv() },
316 "another workspace": func(l *Launch) []string { l.Workspace = in.Home; return OpenCodeArgv() },
317 "no attempt": func(l *Launch) []string { l.AttemptKey = ""; return OpenCodeArgv() },
318 "an env changed": func(l *Launch) []string { l.Policy.Env = map[string]string{"LANG": "C.UTF-8"}; return OpenCodeArgv() },
319 "a provider's binding": func(l *Launch) []string { l.Binding.Provider = "claude"; return OpenCodeArgv() },
320 } {
321 l := launch()
322 argv := change(&l)
323 if _, err := AttestLaunch(l, argv); err == nil {
324 t.Errorf("%s: attested", name)
325 }
326 }
327 // The config file changed after the policy.
328 os.WriteFile(filepath.Join(in.Home, ".config", "opencode", "opencode.json"), []byte(`{"update":"auto"}`), 0600)
329 if _, err := AttestLaunch(launch(), OpenCodeArgv()); err == nil {
330 t.Error("a changed config attested")
331 }
332 WriteOpenCodeConfig(in)
333 if _, err := AttestLaunch(launch(), OpenCodeArgv()); err != nil {
334 t.Fatalf("the config written back: %v", err)
335 }
336 // The binary replaced after the policy.
337 unsealTree(in.Tree)
338 os.Chmod(in.Binary, 0755)
339 if err := os.WriteFile(in.Binary, []byte("another binary!"), 0755); err != nil {
340 t.Fatal(err)
341 }
342 if _, err := AttestLaunch(launch(), OpenCodeArgv()); !errors.Is(err, ErrTree) {
343 t.Errorf("a replaced binary attested: %v", err)
344 }
345}
346
347// The key reaches an OpenCode launch only through the secret pipe, from
348// the connection's home, under the policy's variable.
349func TestOpenCodeLaunchSecretEnv(t *testing.T) {
350 in := opencodeFixture(t, "inspect", opencodeReview)
351 p, err := BuildOpenCodePolicy(in)
352 if err != nil {
353 t.Fatal(err)
354 }
355 keys := t.TempDir()
356 if err := os.WriteFile(filepath.Join(keys, TokenFile), []byte("sk-go-test-key"), 0600); err != nil {
357 t.Fatal(err)
358 }
359 env, err := LaunchSecretEnv(Launch{Policy: p, Binding: OpenCodeBinding("go-1", in.Home, keys)})
360 if err != nil || len(env) != 1 || env["OPENCODE_GO_API_KEY"] != "sk-go-test-key" {
361 t.Fatalf("secret env %v %v", env, err)
362 }
363 for k, v := range p.Env {
364 if strings.Contains(v, "sk-go") || strings.Contains(k, "KEY") {
365 t.Fatalf("the key in the policy's env: %s=%s", k, v)
366 }
367 }
368 if strings.Contains(string(p.Manifest), "sk-go") || strings.Contains(string(p.Settings), "sk-go") {
369 t.Fatal("the key in the manifest")
370 }
371}
372
373// Security round finding 2: the binary is held to its seal, not only its
374// bytes, after the policy too: made writable, given a second name, or
375// under a directory others can write, its attestation is refused though
376// its content is unchanged.
377func TestOpenCodeBinaryStaysSealed(t *testing.T) {
378 for name, change := range map[string]func(in OpenCodePolicyInputs){
379 "made writable": func(in OpenCodePolicyInputs) { os.Chmod(in.Binary, 0755) },
380 "a second name": func(in OpenCodePolicyInputs) {
381 if err := os.Link(in.Binary, filepath.Join(t.TempDir(), "other")); err != nil {
382 t.Fatal(err)
383 }
384 },
385 "an ancestor others can write": func(in OpenCodePolicyInputs) { os.Chmod(filepath.Dir(in.Binary), 0777) },
386 } {
387 t.Run(name, func(t *testing.T) {
388 in := opencodeFixture(t, "inspect", opencodeReview)
389 p, err := BuildOpenCodePolicy(in)
390 if err != nil {
391 t.Fatal(err)
392 }
393 l := Launch{ToolSocket: "/tmp/tool.sock", AttemptKey: "step/a", Workspace: in.Workspace, Selection: Selection{Provider: "opencode-go", Model: "glm-5.3"}, Binding: OpenCodeBinding("go-1", in.Home, "/keys/go-1"), Policy: p}
394 if _, err := AttestLaunch(l, OpenCodeArgv()); err != nil {
395 t.Fatal(err)
396 }
397 change(in)
398 if _, err := AttestLaunch(l, OpenCodeArgv()); err == nil {
399 t.Fatal("attested")
400 }
401 })
402 }
403}
404