package provider import ( "encoding/json" "errors" "os" "path/filepath" "slices" "strings" "testing" ) // opencodeFixture is an OpenCode launch's inputs on disk: a sealed tree // holding the binary, the pinned files, the prepared runtime home and a // workspace. func opencodeFixture(t *testing.T, action string, tools []string) OpenCodePolicyInputs { t.Helper() root := t.TempDir() file := func(name, content string, mode os.FileMode) string { p := filepath.Join(root, name) if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(p, []byte(content), mode); err != nil { t.Fatal(err) } return p } tree := filepath.Join(root, "opencode", "node_modules") binary := file("opencode/node_modules/@opencode/cli-linux-x64/bin/opencode", "opencode binary", 0755) file("opencode/node_modules/@opencode/cli/package.json", "{}", 0644) t.Cleanup(func() { unsealTree(tree) }) if err := SealTree(tree); err != nil { t.Fatal(err) } treeSum, err := TreeSHA256(tree) if err != nil { t.Fatal(err) } home := filepath.Join(root, "homes", "opencode-home") if err := os.MkdirAll(home, 0700); err != nil { t.Fatal(err) } work := filepath.Join(root, "work") if err := os.Mkdir(work, 0700); err != nil { t.Fatal(err) } readOnly := action != "implement" in := OpenCodePolicyInputs{ Binary: binary, BinarySHA256: digest([]byte("opencode binary")), Tree: tree, TreeSHA256: treeSum, Bwrap: file("bwrap", "bwrap", 0755), ToolProxy: file("proxy", "proxy", 0755), Home: home, Workspace: work, Action: action, Provider: "opencode-go", Model: "glm-5.3", KeyEnv: "OPENCODE_GO_API_KEY", Tools: tools, EgressHosts: []string{"opencode.ai"}, Config: OpenCodeConfig("opencode-go", "glm-5.3", tools, readOnly), } if err := WriteOpenCodeConfig(in); err != nil { t.Fatal(err) } return in } var opencodeReview = []string{"read", "glob", "grep", "equipo_submit_review", "equipo_ask_person"} var opencodeEngineering = []string{"read", "glob", "grep", "edit", "shell", "equipo_submit_candidate"} type rule struct{ Action, Resource, Effect string } // effect is OpenCode's own rule: the last matching rule wins, and no // match asks. func effect(rules []rule, action string) string { out := "ask" for _, r := range rules { if r.Action == action || r.Action == "*" { out = r.Effect } } return out } func permissionsOf(t *testing.T, raw json.RawMessage) []rule { t.Helper() var c struct { Permissions []rule `json:"permissions"` } if err := json.Unmarshal(raw, &c); err != nil { t.Fatal(err) } return c.Permissions } // An OpenCode policy fixes everything OpenCode loads: its ACP mode, the // isolating switches in an environment with no inherited variable and no // key, the configuration in the runtime home exactly as Equipo wrote it // (one provider, one model, Equipo's MCP server, no title, summary or // automatic compaction call), the role's permissions, and the binary // alone mounted from the pinned tree. func TestOpenCodePolicyIsolatedConfiguration(t *testing.T) { in := opencodeFixture(t, "inspect", opencodeReview) p, err := BuildOpenCodePolicy(in) if err != nil { t.Fatal(err) } if !p.IsOpenCode() || p.IsPi() || p.IsCheck() || p.IsSignIn() || p.Coordinator() || !p.ReadOnlyWorkspace() || p.Harness() != "opencode" || p.KeyEnv() != "OPENCODE_GO_API_KEY" { t.Fatalf("policy kind: opencode %v ro %v harness %q key %q", p.IsOpenCode(), p.ReadOnlyWorkspace(), p.Harness(), p.KeyEnv()) } if !slices.Equal(p.OpenCodeArgv(), []string{"/opt/opencode", "acp"}) { t.Fatalf("argv %q", p.OpenCodeArgv()) } 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", "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"} if len(p.Env) != len(env) { t.Fatalf("env %v", p.Env) } for k, v := range env { if p.Env[k] != v { t.Fatalf("env %s=%q want %q", k, p.Env[k], v) } } var targets []string for _, m := range p.Mounts { if !m.ReadOnly { t.Fatalf("writable mount %+v", m) } targets = append(targets, m.Target) } if !slices.Equal(targets, []string{"/opt/opencode", "/opt/equipo-tool-proxy"}) { t.Fatalf("mounts %v", targets) } var c map[string]json.RawMessage if err := json.Unmarshal(p.Settings, &c); err != nil { t.Fatal(err) } keys := []string{} for k := range c { keys = append(keys, k) } slices.Sort(keys) if strings.Join(keys, ",") != "agents,compaction,mcp,model,permissions,providers,share,update" { t.Fatalf("config keys %v", keys) } for k, want := range map[string]string{ "update": `"disable"`, "share": `"disabled"`, "model": `"equipo/glm-5.3"`, "agents": `{"summary":{"disabled":true},"title":{"disabled":true}}`, "compaction": `{"auto":false}`, "mcp": `{"equipo":{"command":["/opt/equipo-tool-proxy","--socket","/tool/equipo.sock"],"type":"local"}}`, "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"}}}`, } { if string(c[k]) != want { t.Fatalf("%s = %s, want %s", k, c[k], want) } } // Review: its read tools and Equipo's, nothing else; edit and shell // denied by name, and the list ends in denies. rules := permissionsOf(t, p.Settings) 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"} { if got := effect(rules, action); got != want { t.Errorf("review %s: %s, want %s", action, got, want) } } if rules[0] != (rule{"*", "*", "deny"}) || rules[len(rules)-1].Effect != "deny" { t.Fatalf("rules %v", rules) } // Spec ยง4.2: Review gets explicit edit and shell denies, after every // allow, not only the leading deny of everything. tail := rules[len(rules)-2:] if tail[0] != (rule{"edit", "*", "deny"}) || tail[1] != (rule{"shell", "*", "deny"}) { t.Fatalf("review's last rules %v", tail) } for _, r := range rules { if r.Effect == "ask" { t.Fatalf("a rule asks: %v", r) } } if model, resume, ok := p.OpenCodeSelection(); !ok || model != "glm-5.3" || resume != "" { t.Fatalf("selection %q %q", model, resume) } // Engineering edits and runs commands inside the namespace. eng := opencodeFixture(t, "implement", opencodeEngineering) ep, err := BuildOpenCodePolicy(eng) if err != nil || ep.ReadOnlyWorkspace() { t.Fatalf("engineering: %v", err) } erules := permissionsOf(t, ep.Settings) for action, want := range map[string]string{"edit": "allow", "shell": "allow", "equipo_submit_candidate": "allow", "webfetch": "deny", "external_directory": "deny"} { if got := effect(erules, action); got != want { t.Errorf("engineering %s: %s, want %s", action, got, want) } } eng.Resume = "ses_e2ea2ab7effe3nyJtkcQTxERys" rp, err := BuildOpenCodePolicy(eng) if model, resume, ok := rp.OpenCodeSelection(); err != nil || !ok || model != "glm-5.3" || resume != eng.Resume { t.Fatalf("resume %q %q %v", model, resume, err) } } // What an OpenCode policy refuses: a read-only role with edit or shell, // an unknown tool, a configuration that is not exactly Equipo's (another // key, a plugin, an instruction, a second provider, a literal key, an ask // rule, a second config file beside it), an unpinned binary or tree, a // binary outside the tree, a model or session id that could be a path, // and another provider. func TestOpenCodePolicyRefusals(t *testing.T) { edit := func(f func(c map[string]any)) func(in *OpenCodePolicyInputs) { return func(in *OpenCodePolicyInputs) { var c map[string]any json.Unmarshal(in.Config, &c) f(c) in.Config, _ = json.Marshal(c) if err := WriteOpenCodeConfig(*in); err != nil { panic(err) } } } for _, tc := range []struct { name string action string tools []string change func(in *OpenCodePolicyInputs) }{ {"review with shell", "inspect", []string{"read", "shell"}, nil}, {"review with edit", "inspect", []string{"read", "edit"}, nil}, {"ask with shell", "answer", []string{"read", "shell"}, nil}, {"unknown tool", "implement", []string{"read", "webfetch"}, nil}, {"a subagent tool", "implement", []string{"read", "subagent"}, nil}, {"an MCP tool from another server", "inspect", []string{"read", "evil_tool"}, nil}, {"the coordinator", "converse", opencodeReview, nil}, {"another provider", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Provider = "tensorx" }}, {"another key variable", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.KeyEnv = "TENSORX_API_KEY" }}, {"a model that is a path", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Model = "../glm" }}, {"a session id that is a path", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Resume = "../ses_x" }}, {"no egress", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.EgressHosts = nil }}, {"a plugin", "inspect", opencodeReview, edit(func(c map[string]any) { c["plugins"] = []string{"./evil.js"} })}, {"instructions", "inspect", opencodeReview, edit(func(c map[string]any) { c["instructions"] = []string{"AGENTS.md"} })}, {"warming", "inspect", opencodeReview, edit(func(c map[string]any) { c["warming"] = true })}, {"the title agent on", "inspect", opencodeReview, edit(func(c map[string]any) { c["agents"] = map[string]any{"summary": map[string]bool{"disabled": true}} })}, {"automatic compaction", "inspect", opencodeReview, edit(func(c map[string]any) { delete(c, "compaction") })}, {"updates on", "inspect", opencodeReview, edit(func(c map[string]any) { c["update"] = "auto" })}, {"sharing allowed", "inspect", opencodeReview, edit(func(c map[string]any) { c["share"] = "manual" })}, {"sharing left out", "inspect", opencodeReview, edit(func(c map[string]any) { delete(c, "share") })}, {"a literal key", "inspect", opencodeReview, edit(func(c map[string]any) { 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"} })}, {"another base URL", "inspect", opencodeReview, edit(func(c map[string]any) { c["providers"].(map[string]any)["equipo"].(map[string]any)["settings"] = map[string]string{"baseURL": "https://evil.example/v1"} })}, {"a second provider", "inspect", opencodeReview, edit(func(c map[string]any) { c["providers"].(map[string]any)["evil"] = map[string]any{"package": OpenCodeProviderPackage} })}, {"another MCP server", "inspect", opencodeReview, edit(func(c map[string]any) { c["mcp"].(map[string]any)["evil"] = map[string]any{"type": "local", "command": []string{"sh"}} })}, {"an ask rule", "inspect", opencodeReview, edit(func(c map[string]any) { c["permissions"] = append(c["permissions"].([]any), map[string]string{"action": "shell", "resource": "*", "effect": "ask"}) })}, {"shell allowed for review", "inspect", opencodeReview, edit(func(c map[string]any) { c["permissions"] = append(c["permissions"].([]any), map[string]string{"action": "shell", "resource": "*", "effect": "allow"}) })}, {"the config given differs from the file", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Config = json.RawMessage(`{}`) }}, {"a second config file", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { os.WriteFile(filepath.Join(in.Home, ".config", "opencode", "opencode.jsonc"), []byte(`{"plugins":["x"]}`), 0600) }}, {"another binary", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.BinarySHA256 = digest([]byte("other")) }}, {"another tree", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.TreeSHA256 = digest([]byte("other")) }}, {"a binary outside the tree", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Binary = in.Bwrap; in.BinarySHA256 = digest([]byte("bwrap")) }}, {"a writable tree", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { unsealTree(in.Tree); os.Chmod(in.Tree, 0777) }}, {"a home inside the workspace", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { in.Home = in.Workspace }}, {"a test authority in a release build", "inspect", opencodeReview, func(in *OpenCodePolicyInputs) { if !TestCAAllowed() { in.ExtraCA = in.Bwrap } else { in.Tools = []string{"read", "shell"} } }}, } { t.Run(tc.name, func(t *testing.T) { in := opencodeFixture(t, map[bool]string{true: tc.action, false: "inspect"}[tc.action != "converse"], tc.tools) in.Action = tc.action if tc.action != "converse" && tc.change == nil { in.Config = OpenCodeConfig(in.Provider, in.Model, tc.tools, tc.action != "implement") if err := WriteOpenCodeConfig(in); err != nil { t.Fatal(err) } } if tc.change != nil { tc.change(&in) } if p, err := BuildOpenCodePolicy(in); err == nil { t.Fatalf("accepted: %s", p.Settings) } }) } } // The attestation reads everything again: the config file, the binary // (streamed) and the other pinned files, and holds the launch to the // selection, the session it resumes, the home and a tool socket. func TestOpenCodePolicyAttestation(t *testing.T) { in := opencodeFixture(t, "inspect", opencodeReview) p, err := BuildOpenCodePolicy(in) if err != nil { t.Fatal(err) } launch := func() Launch { 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} } if _, err := AttestLaunch(launch(), OpenCodeArgv()); err != nil { t.Fatal(err) } for name, change := range map[string]func(l *Launch) []string{ "another argv": func(l *Launch) []string { return []string{"/opt/opencode", "serve"} }, "another model": func(l *Launch) []string { l.Selection.Model = "kimi-k3"; return OpenCodeArgv() }, "another provider": func(l *Launch) []string { l.Selection.Provider = "tensorx"; return OpenCodeArgv() }, "a resumed session": func(l *Launch) []string { l.ResumeSessionID = "ses_e2ea2ab7effe3nyJtkcQTxERys"; return OpenCodeArgv() }, "no tool socket": func(l *Launch) []string { l.ToolSocket = ""; return OpenCodeArgv() }, "another home": func(l *Launch) []string { l.Binding.Home = in.Workspace; return OpenCodeArgv() }, "another workspace": func(l *Launch) []string { l.Workspace = in.Home; return OpenCodeArgv() }, "no attempt": func(l *Launch) []string { l.AttemptKey = ""; return OpenCodeArgv() }, "an env changed": func(l *Launch) []string { l.Policy.Env = map[string]string{"LANG": "C.UTF-8"}; return OpenCodeArgv() }, "a provider's binding": func(l *Launch) []string { l.Binding.Provider = "claude"; return OpenCodeArgv() }, } { l := launch() argv := change(&l) if _, err := AttestLaunch(l, argv); err == nil { t.Errorf("%s: attested", name) } } // The config file changed after the policy. os.WriteFile(filepath.Join(in.Home, ".config", "opencode", "opencode.json"), []byte(`{"update":"auto"}`), 0600) if _, err := AttestLaunch(launch(), OpenCodeArgv()); err == nil { t.Error("a changed config attested") } WriteOpenCodeConfig(in) if _, err := AttestLaunch(launch(), OpenCodeArgv()); err != nil { t.Fatalf("the config written back: %v", err) } // The binary replaced after the policy. unsealTree(in.Tree) os.Chmod(in.Binary, 0755) if err := os.WriteFile(in.Binary, []byte("another binary!"), 0755); err != nil { t.Fatal(err) } if _, err := AttestLaunch(launch(), OpenCodeArgv()); !errors.Is(err, ErrTree) { t.Errorf("a replaced binary attested: %v", err) } } // The key reaches an OpenCode launch only through the secret pipe, from // the connection's home, under the policy's variable. func TestOpenCodeLaunchSecretEnv(t *testing.T) { in := opencodeFixture(t, "inspect", opencodeReview) p, err := BuildOpenCodePolicy(in) if err != nil { t.Fatal(err) } keys := t.TempDir() if err := os.WriteFile(filepath.Join(keys, TokenFile), []byte("sk-go-test-key"), 0600); err != nil { t.Fatal(err) } env, err := LaunchSecretEnv(Launch{Policy: p, Binding: OpenCodeBinding("go-1", in.Home, keys)}) if err != nil || len(env) != 1 || env["OPENCODE_GO_API_KEY"] != "sk-go-test-key" { t.Fatalf("secret env %v %v", env, err) } for k, v := range p.Env { if strings.Contains(v, "sk-go") || strings.Contains(k, "KEY") { t.Fatalf("the key in the policy's env: %s=%s", k, v) } } if strings.Contains(string(p.Manifest), "sk-go") || strings.Contains(string(p.Settings), "sk-go") { t.Fatal("the key in the manifest") } } // Security round finding 2: the binary is held to its seal, not only its // bytes, after the policy too: made writable, given a second name, or // under a directory others can write, its attestation is refused though // its content is unchanged. func TestOpenCodeBinaryStaysSealed(t *testing.T) { for name, change := range map[string]func(in OpenCodePolicyInputs){ "made writable": func(in OpenCodePolicyInputs) { os.Chmod(in.Binary, 0755) }, "a second name": func(in OpenCodePolicyInputs) { if err := os.Link(in.Binary, filepath.Join(t.TempDir(), "other")); err != nil { t.Fatal(err) } }, "an ancestor others can write": func(in OpenCodePolicyInputs) { os.Chmod(filepath.Dir(in.Binary), 0777) }, } { t.Run(name, func(t *testing.T) { in := opencodeFixture(t, "inspect", opencodeReview) p, err := BuildOpenCodePolicy(in) if err != nil { t.Fatal(err) } 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} if _, err := AttestLaunch(l, OpenCodeArgv()); err != nil { t.Fatal(err) } change(in) if _, err := AttestLaunch(l, OpenCodeArgv()); err == nil { t.Fatal("attested") } }) } }