| 1 | package provider |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "slices" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | ) |
| 13 | |
| 14 | // piFixture is a Pi launch's inputs on disk: the pinned files, a sealed |
| 15 | // tree, the prepared runtime home and a workspace. |
| 16 | func piFixture(t *testing.T, action string, tools []string) PiPolicyInputs { |
| 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, "pi", "node_modules") |
| 30 | file("pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js", "cli", 0755) |
| 31 | t.Cleanup(func() { unsealTree(tree) }) |
| 32 | if err := SealTree(tree); err != nil { |
| 33 | t.Fatal(err) |
| 34 | } |
| 35 | treeSum, err := TreeSHA256(tree) |
| 36 | if err != nil { |
| 37 | t.Fatal(err) |
| 38 | } |
| 39 | home := filepath.Join(root, "homes", "pi-home") |
| 40 | if err := os.MkdirAll(filepath.Join(home, "agent"), 0700); err != nil { |
| 41 | t.Fatal(err) |
| 42 | } |
| 43 | if err := os.Chmod(home, 0700); err != nil { |
| 44 | t.Fatal(err) |
| 45 | } |
| 46 | work := filepath.Join(root, "work") |
| 47 | if err := os.Mkdir(work, 0700); err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | in := PiPolicyInputs{ |
| 51 | Node: file("node", "node", 0755), NodeSHA256: digest([]byte("node")), Tree: tree, TreeSHA256: treeSum, |
| 52 | Bwrap: file("bwrap", "bwrap", 0755), ToolProxy: file("proxy", "proxy", 0755), Extension: file("equipo.ts", string(PiExtensionSource()), 0600), |
| 53 | Shell: file("bash", string(PiShellSource()), 0700), Home: home, Workspace: work, Action: action, Provider: "tensorx", Model: "z-ai/glm-5.3", KeyEnv: "TENSORX_API_KEY", |
| 54 | Tools: tools, EgressHosts: []string{"api.tensorx.ai"}, |
| 55 | Models: json.RawMessage(`{"providers":{"tensorx":{"api":"openai-completions","apiKey":"$TENSORX_API_KEY","baseUrl":"https://api.tensorx.ai/v1","models":[{"id":"z-ai/glm-5.3"}]}}}`), |
| 56 | Settings: PiSettings, |
| 57 | MCP: json.RawMessage(`{"autoEnableCodemode":false,"mcpServers":{"equipo":{"args":["--socket","/tool/equipo.sock"],"command":"/opt/equipo-tool-proxy","exposure":"direct"}}}`), |
| 58 | } |
| 59 | if err := WritePiConfig(in); err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | return in |
| 63 | } |
| 64 | |
| 65 | func unsealTree(dir string) { |
| 66 | filepath.Walk(dir, func(p string, info os.FileInfo, err error) error { |
| 67 | if err == nil && info.IsDir() { |
| 68 | os.Chmod(p, 0755) |
| 69 | } |
| 70 | return nil |
| 71 | }) |
| 72 | } |
| 73 | |
| 74 | var reviewTools = []string{"read", "grep", "find", "ls", "mcp__equipo__submit_review", "mcp__equipo__ask_person"} |
| 75 | |
| 76 | // A Pi policy fixes everything Pi loads: the isolating switches in an |
| 77 | // exact argv, Equipo's extension and nothing else, its own config |
| 78 | // directory, the runtime home's session directory, the pinned tools, |
| 79 | // and an environment with no inherited variable and no key. |
| 80 | func TestPiPolicyIsolatedConfiguration(t *testing.T) { |
| 81 | in := piFixture(t, "inspect", reviewTools) |
| 82 | p, err := BuildPiPolicy(in) |
| 83 | if err != nil { |
| 84 | t.Fatal(err) |
| 85 | } |
| 86 | if !p.IsPi() || p.IsCheck() || p.IsSignIn() || p.Coordinator() || !p.ReadOnlyWorkspace() || p.Harness() != "pi" || p.KeyEnv() != "TENSORX_API_KEY" { |
| 87 | t.Fatalf("policy kind: pi %v ro %v harness %q", p.IsPi(), p.ReadOnlyWorkspace(), p.Harness()) |
| 88 | } |
| 89 | argv := PiArgv(in) |
| 90 | want := []string{"/opt/node", "/opt/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js", "--mode", "rpc", "--no-approve", "--offline", "--no-context-files", "--no-extensions", "-e", "builtin:mcp", "-e", "/config/pi/equipo.ts", "--no-skills", "--no-prompt-templates", "--no-themes", "--session-dir", "/home/runner/sessions", "--provider", "tensorx", "--model", "z-ai/glm-5.3", "--tools", strings.Join(reviewTools, ",")} |
| 91 | if !slices.Equal(argv, want) { |
| 92 | t.Fatalf("argv\n%q\nwant\n%q", argv, want) |
| 93 | } |
| 94 | env := map[string]string{"LANG": "C.UTF-8", "PI_CODING_AGENT_DIR": "/home/runner/agent", "PI_OFFLINE": "1", "PI_SKIP_VERSION_CHECK": "1", "PI_TELEMETRY": "0", "EQUIPO_PI_TOOLS": strings.Join(reviewTools, ","), "EQUIPO_PI_CONFINE": "/workspace"} |
| 95 | if len(p.Env) != len(env) { |
| 96 | t.Fatalf("env %v", p.Env) |
| 97 | } |
| 98 | for k, v := range env { |
| 99 | if p.Env[k] != v { |
| 100 | t.Fatalf("env %s=%q want %q", k, p.Env[k], v) |
| 101 | } |
| 102 | } |
| 103 | var targets []string |
| 104 | for _, m := range p.Mounts { |
| 105 | if !m.ReadOnly { |
| 106 | t.Fatalf("writable mount %+v", m) |
| 107 | } |
| 108 | targets = append(targets, m.Target) |
| 109 | } |
| 110 | if !slices.Equal(targets, []string{"/opt/node", "/opt/pi/node_modules", "/opt/equipo-tool-proxy", "/config/pi/equipo.ts", "/opt/bwrap", PiShell}) { |
| 111 | t.Fatalf("mounts %v", targets) |
| 112 | } |
| 113 | in.Resume = "01a1d02a-2fc0-7066-b385-fa7d30fbd4fb" |
| 114 | if got := PiArgv(in); !slices.Equal(got[len(got)-2:], []string{"--session-id", in.Resume}) { |
| 115 | t.Fatalf("resume argv %q", got) |
| 116 | } |
| 117 | in.Resume = "" |
| 118 | // Engineering keeps native file tools in the workspace. |
| 119 | eng := piFixture(t, "implement", []string{"read", "bash", "edit", "write", "grep", "find", "ls", "mcp__equipo__submit_candidate"}) |
| 120 | ep, err := BuildPiPolicy(eng) |
| 121 | if err != nil || ep.ReadOnlyWorkspace() || ep.Env["EQUIPO_PI_CONFINE"] != "/workspace" { |
| 122 | t.Fatalf("engineering: %v %v", err, ep.Env) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | // What a Pi policy refuses: a read-only role with a write or shell tool, |
| 127 | // an unknown tool, a key written into models.json, an unpinned Node or |
| 128 | // tree, a writable tree, and a home outside the runner's homes. |
| 129 | func TestPiPolicyRefusals(t *testing.T) { |
| 130 | for _, tc := range []struct { |
| 131 | name string |
| 132 | action string |
| 133 | tools []string |
| 134 | change func(in *PiPolicyInputs) |
| 135 | }{ |
| 136 | {"review with bash", "inspect", []string{"read", "bash"}, nil}, |
| 137 | {"review with write", "inspect", []string{"read", "write"}, nil}, |
| 138 | {"review with edit", "inspect", []string{"read", "edit"}, nil}, |
| 139 | {"ask with bash", "answer", []string{"read", "bash"}, nil}, |
| 140 | {"unknown tool", "implement", []string{"read", "codemode"}, nil}, |
| 141 | {"another MCP server", "implement", []string{"read", "mcp__other__x"}, nil}, |
| 142 | {"an MCP wildcard", "implement", []string{"read", "mcp__equipo__*"}, nil}, |
| 143 | {"the key in models.json", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 144 | in.Models = json.RawMessage(`{"providers":{"tensorx":{"api":"openai-completions","apiKey":"tx-secret","baseUrl":"https://api.tensorx.ai/v1","models":[{"id":"z-ai/glm-5.3"}]}}}`) |
| 145 | }}, |
| 146 | {"a command for the key", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 147 | in.Models = json.RawMessage(`{"providers":{"tensorx":{"api":"openai-completions","apiKey":"!cat /home/runner/key","baseUrl":"https://api.tensorx.ai/v1","models":[{"id":"z-ai/glm-5.3"}]}}}`) |
| 148 | }}, |
| 149 | {"a token in settings", "inspect", reviewTools, func(in *PiPolicyInputs) { in.Settings = json.RawMessage(`{"token":"x"}`) }}, |
| 150 | {"another node", "inspect", reviewTools, func(in *PiPolicyInputs) { in.NodeSHA256 = digest([]byte("other")) }}, |
| 151 | {"another tree", "inspect", reviewTools, func(in *PiPolicyInputs) { in.TreeSHA256 = digest([]byte("other")) }}, |
| 152 | {"a writable tree", "inspect", reviewTools, func(in *PiPolicyInputs) { os.Chmod(in.Tree, 0755) }}, |
| 153 | {"an install root others can write", "inspect", reviewTools, func(in *PiPolicyInputs) { os.Chmod(filepath.Dir(in.Tree), 0777) }}, |
| 154 | {"a key variable of another name", "inspect", reviewTools, func(in *PiPolicyInputs) { in.KeyEnv = "OPENAI_API_KEY" }}, |
| 155 | {"a test CA in a release build", "inspect", reviewTools, func(in *PiPolicyInputs) { in.ExtraCA = in.Bwrap }}, |
| 156 | // Only Equipo's own configuration: no other MCP server, command, |
| 157 | // argument or exposure; no other setting; models.json's exact |
| 158 | // shape at the provider's own base URL; Equipo's extension. |
| 159 | {"an MCP server running a shell", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 160 | in.MCP = json.RawMessage(`{"autoEnableCodemode":false,"mcpServers":{"equipo":{"args":["-c","id"],"command":"/bin/sh","exposure":"direct"}}}`) |
| 161 | }}, |
| 162 | {"a second MCP server", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 163 | in.MCP = json.RawMessage(`{"autoEnableCodemode":false,"mcpServers":{"equipo":{"args":["--socket","/tool/equipo.sock"],"command":"/opt/equipo-tool-proxy","exposure":"direct"},"other":{"url":"https://example.com/mcp"}}}`) |
| 164 | }}, |
| 165 | {"codemode exposure", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 166 | in.MCP = json.RawMessage(`{"autoEnableCodemode":true,"mcpServers":{"equipo":{"args":["--socket","/tool/equipo.sock"],"command":"/opt/equipo-tool-proxy","exposure":"codemode"}}}`) |
| 167 | }}, |
| 168 | {"another setting", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 169 | in.Settings = json.RawMessage(`{"defaultProjectTrust":"never","defaultTools":["+codemode"]}`) |
| 170 | }}, |
| 171 | {"project trust", "inspect", reviewTools, func(in *PiPolicyInputs) { in.Settings = json.RawMessage(`{"defaultProjectTrust":"always"}`) }}, |
| 172 | {"another base URL", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 173 | in.Models = json.RawMessage(`{"providers":{"tensorx":{"api":"openai-completions","apiKey":"$TENSORX_API_KEY","baseUrl":"https://api.tensorx.ai.evil.example/v1","models":[{"id":"z-ai/glm-5.3"}]}}}`) |
| 174 | }}, |
| 175 | {"headers in models.json", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 176 | in.Models = json.RawMessage(`{"providers":{"tensorx":{"api":"openai-completions","apiKey":"$TENSORX_API_KEY","baseUrl":"https://api.tensorx.ai/v1","headers":{"x":"!cat /proc/self/environ"},"models":[{"id":"z-ai/glm-5.3"}]}}}`) |
| 177 | }}, |
| 178 | {"a field in a model", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 179 | in.Models = json.RawMessage(`{"providers":{"tensorx":{"api":"openai-completions","apiKey":"$TENSORX_API_KEY","baseUrl":"https://api.tensorx.ai/v1","models":[{"id":"z-ai/glm-5.3","compat":{"x":1}}]}}}`) |
| 180 | }}, |
| 181 | {"another extension", "inspect", reviewTools, func(in *PiPolicyInputs) { |
| 182 | os.WriteFile(in.Extension, []byte("export default function () {}"), 0600) |
| 183 | }}, |
| 184 | } { |
| 185 | t.Run(tc.name, func(t *testing.T) { |
| 186 | in := piFixture(t, tc.action, tc.tools) |
| 187 | if tc.change != nil { |
| 188 | tc.change(&in) |
| 189 | if err := WritePiConfig(in); err != nil { |
| 190 | t.Fatal(err) |
| 191 | } |
| 192 | } |
| 193 | if tc.name == "a test CA in a release build" && TestCAAllowed() { |
| 194 | t.Skip("the test build allows a test CA") |
| 195 | } |
| 196 | if _, err := BuildPiPolicy(in); err == nil { |
| 197 | t.Fatal("accepted") |
| 198 | } |
| 199 | }) |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | // A launch is held to its Pi policy: the exact argv, the config files |
| 204 | // as they were hashed, the tree and Node as pinned, the workspace and |
| 205 | // the selection. Changed after the policy was built, it is refused. |
| 206 | func TestPiPolicyAttestation(t *testing.T) { |
| 207 | launch := func(t *testing.T) (Launch, []string, PiPolicyInputs) { |
| 208 | in := piFixture(t, "inspect", reviewTools) |
| 209 | p, err := BuildPiPolicy(in) |
| 210 | if err != nil { |
| 211 | t.Fatal(err) |
| 212 | } |
| 213 | l := Launch{ToolSocket: "/state/tool/equipo.sock", AttemptKey: "step/x/1/a", Workspace: in.Workspace, Selection: Selection{ConnectionID: "tensorx-abc", Provider: "tensorx", Model: in.Model, Family: "glm"}, Binding: PiBinding("tensorx-abc", in.Home, filepath.Join(filepath.Dir(in.Home), "key")), Policy: p} |
| 214 | return l, PiArgv(in), in |
| 215 | } |
| 216 | l, argv, _ := launch(t) |
| 217 | if _, err := AttestLaunch(l, argv); err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | for _, tc := range []struct { |
| 221 | name string |
| 222 | change func(l *Launch, argv *[]string, in PiPolicyInputs) |
| 223 | }{ |
| 224 | {"argv", func(l *Launch, argv *[]string, in PiPolicyInputs) { *argv = append(*argv, "--approve") }}, |
| 225 | {"models.json", func(l *Launch, argv *[]string, in PiPolicyInputs) { |
| 226 | os.WriteFile(filepath.Join(in.Home, "agent", "models.json"), []byte(`{}`), 0600) |
| 227 | }}, |
| 228 | {"mcp.json", func(l *Launch, argv *[]string, in PiPolicyInputs) { |
| 229 | os.WriteFile(filepath.Join(in.Home, "agent", "mcp.json"), []byte(`{}`), 0600) |
| 230 | }}, |
| 231 | {"extension", func(l *Launch, argv *[]string, in PiPolicyInputs) { |
| 232 | os.WriteFile(in.Extension, []byte("export default function (pi) { }"), 0600) |
| 233 | }}, |
| 234 | {"tree", func(l *Launch, argv *[]string, in PiPolicyInputs) { |
| 235 | cli := filepath.Join(in.Tree, "@earendil-works/pi-coding-agent/dist/bundle/cli.js") |
| 236 | dir := filepath.Dir(cli) |
| 237 | os.Chmod(dir, 0755) |
| 238 | os.Chmod(cli, 0755) |
| 239 | os.WriteFile(cli, []byte("other"), 0755) |
| 240 | os.Chmod(cli, 0555) |
| 241 | os.Chmod(dir, 0555) |
| 242 | }}, |
| 243 | {"node", func(l *Launch, argv *[]string, in PiPolicyInputs) { os.WriteFile(in.Node, []byte("other"), 0755) }}, |
| 244 | {"workspace", func(l *Launch, argv *[]string, in PiPolicyInputs) { l.Workspace = filepath.Join(in.Workspace, "x") }}, |
| 245 | {"model", func(l *Launch, argv *[]string, in PiPolicyInputs) { l.Selection.Model = "z-ai/glm-5.3-flash" }}, |
| 246 | {"provider", func(l *Launch, argv *[]string, in PiPolicyInputs) { l.Selection.Provider = "claude" }}, |
| 247 | {"tool socket missing", func(l *Launch, argv *[]string, in PiPolicyInputs) { l.ToolSocket = "" }}, |
| 248 | {"env", func(l *Launch, argv *[]string, in PiPolicyInputs) { |
| 249 | env := map[string]string{} |
| 250 | for k, v := range l.Policy.Env { |
| 251 | env[k] = v |
| 252 | } |
| 253 | env["EQUIPO_PI_TOOLS"] = "read,bash" |
| 254 | l.Policy.Env = env |
| 255 | }}, |
| 256 | } { |
| 257 | t.Run(tc.name, func(t *testing.T) { |
| 258 | l, argv, in := launch(t) |
| 259 | tc.change(&l, &argv, in) |
| 260 | if _, err := AttestLaunch(l, argv); err == nil { |
| 261 | t.Fatal("attested") |
| 262 | } |
| 263 | }) |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | // The key reaches a Pi launch as its provider's variable, from the 0600 |
| 268 | // file in the connection's home, through the containment's secret pipe: |
| 269 | // never in argv, the policy or the manifest. |
| 270 | func TestPiLaunchSecretEnv(t *testing.T) { |
| 271 | in := piFixture(t, "inspect", reviewTools) |
| 272 | p, err := BuildPiPolicy(in) |
| 273 | if err != nil { |
| 274 | t.Fatal(err) |
| 275 | } |
| 276 | keyHome := filepath.Join(t.TempDir(), "tensorx-abc") |
| 277 | if err := os.Mkdir(keyHome, 0700); err != nil { |
| 278 | t.Fatal(err) |
| 279 | } |
| 280 | if err := os.WriteFile(filepath.Join(keyHome, TokenFile), []byte("tx-test-key"), 0600); err != nil { |
| 281 | t.Fatal(err) |
| 282 | } |
| 283 | l := Launch{AttemptKey: "a", Workspace: in.Workspace, Selection: Selection{Provider: "tensorx", Model: in.Model}, Binding: PiBinding("tensorx-abc", in.Home, keyHome), Policy: p} |
| 284 | env, err := LaunchSecretEnv(l) |
| 285 | if err != nil || len(env) != 1 || env["TENSORX_API_KEY"] != "tx-test-key" { |
| 286 | t.Fatalf("%v %v", env, err) |
| 287 | } |
| 288 | for _, raw := range [][]byte{p.Manifest, []byte(strings.Join(PiArgv(in), " "))} { |
| 289 | if strings.Contains(string(raw), "tx-test-key") { |
| 290 | t.Fatal("the key is in the policy") |
| 291 | } |
| 292 | } |
| 293 | os.Remove(filepath.Join(keyHome, TokenFile)) |
| 294 | if _, err := LaunchSecretEnv(l); err == nil { |
| 295 | t.Fatal("a launch with no key started") |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | // The policy's base URLs are the provider table's (wire.APIKeyProviders). |
| 300 | func TestPiBaseURLsAreTheProviders(t *testing.T) { |
| 301 | for name, url := range PiBaseURLs { |
| 302 | p, ok := wire.APIKeyProviders[name] |
| 303 | if !ok || p.Harness != wire.HarnessPi || url != p.Upstream+p.APIPath { |
| 304 | t.Errorf("%s: %s, the provider table says %+v", name, url, p) |
| 305 | } |
| 306 | } |
| 307 | if len(PiBaseURLs) != len(PiKeyEnvs) { |
| 308 | t.Fatal("a Pi provider without a base URL or a key variable") |
| 309 | } |
| 310 | } |
| 311 | |