| 1 | package provider |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | _ "embed" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "reflect" |
| 12 | "slices" |
| 13 | "sort" |
| 14 | "strings" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider/gotoolchain" |
| 17 | "golang.org/x/sys/unix" |
| 18 | ) |
| 19 | |
| 20 | const checkPolicyVersion = "checks-v1" |
| 21 | |
| 22 | type CheckPolicyInputs struct { |
| 23 | Workspace, Binary, RunnerBinary, Bwrap, GoRoot, ModuleCache string |
| 24 | GateFiles []Mount |
| 25 | Argv []string |
| 26 | Env map[string]string |
| 27 | } |
| 28 | |
| 29 | // BuildCheckPolicy admits no provider home, network, or writable host cache. |
| 30 | func BuildCheckPolicy(in CheckPolicyInputs) (Policy, error) { |
| 31 | home, err := os.UserHomeDir() |
| 32 | if err != nil { |
| 33 | return Policy{}, ErrPolicy |
| 34 | } |
| 35 | m := effectiveManifest{Version: checkPolicyVersion, Workspace: in.Workspace, Argv: in.Argv, Env: in.Env, NamespaceArgs: NamespaceArguments()} |
| 36 | for _, path := range []string{in.Workspace, in.GoRoot, in.ModuleCache} { |
| 37 | if path == "" && path != in.Workspace { |
| 38 | // The Go toolchain and module cache are optional (thin checks |
| 39 | // on a runner without them). |
| 40 | continue |
| 41 | } |
| 42 | if path == "/" || path == "/tmp" || withinPath(home, path) { |
| 43 | return Policy{}, fmt.Errorf("%w: check directory %q includes a broad host directory", ErrPolicy, path) |
| 44 | } |
| 45 | f, err := pinDirectory(path) |
| 46 | if err != nil { |
| 47 | return Policy{}, fmt.Errorf("%w: check directory %q must be a canonical directory without symlinks", err, path) |
| 48 | } |
| 49 | f.Close() |
| 50 | } |
| 51 | // Pinned files first (the Codex binary only when given; thin checks |
| 52 | // run the repository's gate directly), then the Go trees. |
| 53 | files := []Mount{{Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true}} |
| 54 | if in.Binary != "" { |
| 55 | files = append([]Mount{{Source: in.Binary, Target: "/opt/codex", ReadOnly: true}}, files...) |
| 56 | } |
| 57 | for _, mount := range in.GateFiles { |
| 58 | if !mount.ReadOnly || !validGateTarget(mount.Target) || withinPath(in.Workspace, mount.Source) || withinPath(mount.Source, in.Workspace) { |
| 59 | return Policy{}, ErrPolicy |
| 60 | } |
| 61 | files = append(files, mount) |
| 62 | } |
| 63 | m.OuterMounts = files |
| 64 | if in.GoRoot != "" { |
| 65 | m.OuterMounts = append(m.OuterMounts, Mount{Source: in.GoRoot, Target: "/opt/go", ReadOnly: true}) |
| 66 | } |
| 67 | if in.ModuleCache != "" { |
| 68 | m.OuterMounts = append(m.OuterMounts, Mount{Source: in.ModuleCache, Target: "/opt/go-mod", ReadOnly: true}) |
| 69 | } |
| 70 | |
| 71 | if in.Env != nil { |
| 72 | for k, v := range gotoolchain.Environment() { |
| 73 | if supplied, ok := in.Env[k]; ok && supplied != v { |
| 74 | return Policy{}, ErrPolicy |
| 75 | } |
| 76 | } |
| 77 | m.Env = map[string]string{} |
| 78 | for k, v := range in.Env { |
| 79 | m.Env[k] = v |
| 80 | } |
| 81 | for k, v := range gotoolchain.Environment() { |
| 82 | m.Env[k] = v |
| 83 | } |
| 84 | } |
| 85 | for _, mount := range files { |
| 86 | fd, err := openNoLinks(mount.Source, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK) |
| 87 | if err != nil { |
| 88 | return Policy{}, ErrPolicy |
| 89 | } |
| 90 | f := os.NewFile(uintptr(fd), mount.Source) |
| 91 | info, err := f.Stat() |
| 92 | f.Close() |
| 93 | if err == nil && info.IsDir() && validGateTarget(mount.Target) { |
| 94 | sum, err := TreeSHA256(mount.Source) |
| 95 | if err != nil { |
| 96 | return Policy{}, err |
| 97 | } |
| 98 | m.Trees = append(m.Trees, treePin{Mount: mount, SHA256: sum}) |
| 99 | continue |
| 100 | } |
| 101 | if err != nil || !info.Mode().IsRegular() { |
| 102 | return Policy{}, ErrPolicy |
| 103 | } |
| 104 | raw, err := os.ReadFile(mount.Source) |
| 105 | if err != nil { |
| 106 | return Policy{}, err |
| 107 | } |
| 108 | m.Files = append(m.Files, fileDigest{Mount: mount, SHA256: digest(raw)}) |
| 109 | } |
| 110 | raw, hash, err := hashJSON(m) |
| 111 | if err != nil { |
| 112 | return Policy{}, err |
| 113 | } |
| 114 | return Policy{Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: m.Env}, nil |
| 115 | } |
| 116 | |
| 117 | func (p Policy) IsCheck() bool { |
| 118 | var m effectiveManifest |
| 119 | return json.Unmarshal(p.Manifest, &m) == nil && m.Version == checkPolicyVersion |
| 120 | } |
| 121 | |
| 122 | // CheckGateMount identifies a workspace file hashed by the check policy. |
| 123 | func (p Policy) CheckGateMount(mount Mount) bool { |
| 124 | if !p.IsCheck() || !mount.ReadOnly || !validGateTarget(mount.Target) { |
| 125 | return false |
| 126 | } |
| 127 | var m effectiveManifest |
| 128 | if json.Unmarshal(p.Manifest, &m) != nil { |
| 129 | return false |
| 130 | } |
| 131 | for _, f := range m.Files { |
| 132 | if f.Mount == mount { |
| 133 | return true |
| 134 | } |
| 135 | } |
| 136 | for _, t := range m.Trees { |
| 137 | if t.Mount == mount { |
| 138 | return true |
| 139 | } |
| 140 | } |
| 141 | return false |
| 142 | } |
| 143 | |
| 144 | func (p Policy) CheckGateTree(mount Mount) bool { |
| 145 | var m effectiveManifest |
| 146 | if !p.CheckGateMount(mount) || json.Unmarshal(p.Manifest, &m) != nil { |
| 147 | return false |
| 148 | } |
| 149 | for _, t := range m.Trees { |
| 150 | if t.Mount == mount { |
| 151 | return true |
| 152 | } |
| 153 | } |
| 154 | return false |
| 155 | } |
| 156 | |
| 157 | func validGateTarget(target string) bool { |
| 158 | if !strings.HasPrefix(target, "/workspace/") || filepath.Clean(target) != target || strings.ContainsAny(target, "\\\x00") { |
| 159 | return false |
| 160 | } |
| 161 | relative := strings.TrimPrefix(target, "/workspace/") |
| 162 | return relative != ".git" && !strings.HasPrefix(relative, ".git/") |
| 163 | } |
| 164 | |
| 165 | func attestCheck(l Launch, argv []string) (string, error) { |
| 166 | p := l.Policy |
| 167 | var m effectiveManifest |
| 168 | if l.Selection != (Selection{}) || l.Binding != (Binding{}) || l.ToolSocket != "" || l.ResumeSessionID != "" || l.AttemptKey == "" || json.Unmarshal(p.Manifest, &m) != nil || digest(p.Manifest) != p.ManifestHash || p.Hash != p.ManifestHash || m.Workspace != l.Workspace || !reflect.DeepEqual(argv, m.Argv) || !reflect.DeepEqual(p.Env, m.Env) || !reflect.DeepEqual(p.Mounts, m.OuterMounts) || !reflect.DeepEqual(m.NamespaceArgs, NamespaceArguments()) { |
| 169 | return "", ErrPolicy |
| 170 | } |
| 171 | for _, f := range m.Files { |
| 172 | raw, err := os.ReadFile(f.Mount.Source) |
| 173 | if err != nil || digest(raw) != f.SHA256 { |
| 174 | return "", ErrPolicy |
| 175 | } |
| 176 | } |
| 177 | for _, t := range m.Trees { |
| 178 | sum, err := TreeSHA256(t.Mount.Source) |
| 179 | if err != nil || sum != t.SHA256 { |
| 180 | return "", ErrPolicy |
| 181 | } |
| 182 | } |
| 183 | for _, mount := range p.Mounts { |
| 184 | if !mount.ReadOnly || !filepath.IsAbs(mount.Source) { |
| 185 | return "", ErrPolicy |
| 186 | } |
| 187 | } |
| 188 | _, hash, err := hashJSON(struct{ Manifest, Attempt string }{p.ManifestHash, l.AttemptKey}) |
| 189 | return hash, err |
| 190 | } |
| 191 | |
| 192 | // The Pi harness's effective policy (connectors spec §3 and §4.1, slice |
| 193 | // S2), built and attested here like a check's: no account lease, every |
| 194 | // input exact. Pi loads only what this names: Node and the Pi tree as |
| 195 | // pinned, Equipo's extension and Pi's built-in MCP support (every other |
| 196 | // extension, skill, prompt template, theme, context file and project |
| 197 | // resource switched off by flag), its config directory in the attempt's |
| 198 | // own runtime home with the three files the runner wrote and this hashed, |
| 199 | // sessions in that home, and the tools the role pins. The key is not in |
| 200 | // it: it reaches the namespace as KeyEnv through the secret pipe. |
| 201 | |
| 202 | const piPolicyVersion = "pi-v2" |
| 203 | |
| 204 | // Paths inside a Pi namespace. |
| 205 | const ( |
| 206 | PiNode = "/opt/node" |
| 207 | PiTree = "/opt/pi/node_modules" |
| 208 | PiCLI = PiTree + "/@earendil-works/pi-coding-agent/dist/bundle/cli.js" |
| 209 | PiExtension = "/config/pi/equipo.ts" |
| 210 | PiAgentDir = "/home/runner/agent" |
| 211 | PiSessions = "/home/runner/sessions" |
| 212 | piTestCA = "/opt/test-ca.pem" |
| 213 | ) |
| 214 | |
| 215 | // PiKeyEnvs are the variables a Pi launch may receive its key in, one per |
| 216 | // provider behind Pi. |
| 217 | var PiKeyEnvs = map[string]string{"tensorx": "TENSORX_API_KEY"} |
| 218 | |
| 219 | // PiBaseURLs are the OpenAI-compatible base URLs of the providers behind |
| 220 | // Pi (the provider table's upstream and API path). |
| 221 | var PiBaseURLs = map[string]string{"tensorx": "https://api.tensorx.ai/v1"} |
| 222 | |
| 223 | // piExtension is Equipo's own Pi extension (pi_extension.ts), the only |
| 224 | // one Pi loads beside its built-in MCP support: the tool gate. A Pi |
| 225 | // policy pins its digest. |
| 226 | // |
| 227 | //go:embed pi_extension.ts |
| 228 | var piExtension []byte |
| 229 | |
| 230 | // PiExtensionSource is the extension's source. |
| 231 | func PiExtensionSource() []byte { return bytes.Clone(piExtension) } |
| 232 | |
| 233 | // PiExtensionSHA256 is its digest. |
| 234 | func PiExtensionSHA256() string { return digest(piExtension) } |
| 235 | |
| 236 | // PiSettings is settings.json: project trust never granted, whatever a |
| 237 | // flag or a project says. |
| 238 | var PiSettings = json.RawMessage(`{"defaultProjectTrust":"never","shellPath":"/config/pi/bash"}`) |
| 239 | |
| 240 | // PiMCP is mcp.json: Equipo's own tools only, through the tool proxy on |
| 241 | // the attempt's socket, declared to the model directly (no codemode, no |
| 242 | // tool search). |
| 243 | var PiMCP = json.RawMessage(`{"autoEnableCodemode":false,"mcpServers":{"equipo":{"command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"],"exposure":"direct"}}}`) |
| 244 | |
| 245 | // PiModels is models.json for one provider behind Pi: its base URL, the |
| 246 | // chat completions API, the key by its variable (never the key) and the |
| 247 | // connection's one model. |
| 248 | func PiModels(provider, model string) json.RawMessage { |
| 249 | raw, _ := json.Marshal(map[string]any{"providers": map[string]any{provider: map[string]any{"baseUrl": PiBaseURLs[provider], "api": "openai-completions", "apiKey": "$" + PiKeyEnvs[provider], "models": []map[string]string{{"id": model}}}}}) |
| 250 | return raw |
| 251 | } |
| 252 | |
| 253 | // piTools are the tools a Pi role may pin: Pi's built-ins, and the step's |
| 254 | // own Equipo tools over MCP, each named exactly. |
| 255 | var piReadTools = []string{"read", "grep", "find", "ls"} |
| 256 | var piWriteTools = []string{"bash", "edit", "write"} |
| 257 | |
| 258 | // PiPolicyInputs are one Pi launch's inputs. Node, Tree, Bwrap, |
| 259 | // ToolProxy and Extension are host paths; Home is the attempt's runtime |
| 260 | // home (under the scratch root's homes), whose agent directory holds |
| 261 | // Models, Settings and MCP as WritePiConfig wrote them. |
| 262 | type PiPolicyInputs struct { |
| 263 | Node, NodeSHA256, Tree, TreeSHA256 string |
| 264 | Bwrap, ToolProxy, Extension string |
| 265 | Shell, GoRoot, ModuleCache string |
| 266 | GoLease *GoLease |
| 267 | Home, Workspace, Action string |
| 268 | Provider, Model, KeyEnv string |
| 269 | Tools, EgressHosts []string |
| 270 | Resume string |
| 271 | Models, Settings, MCP json.RawMessage |
| 272 | // ExtraCA is a test build's certificate authority for its fake |
| 273 | // provider (TestCAAllowed); a release build refuses one. |
| 274 | ExtraCA string |
| 275 | } |
| 276 | |
| 277 | // testCA is set by the test build only (testca_testbuild.go). |
| 278 | var testCA bool |
| 279 | |
| 280 | // TestCAAllowed reports whether this build lets a Pi launch trust a test |
| 281 | // certificate authority: only a test build does. |
| 282 | func TestCAAllowed() bool { return testCA } |
| 283 | |
| 284 | // PiArgv is Pi's exact argv inside the namespace: RPC mode, project |
| 285 | // trust refused, offline, no context files, no extension but Equipo's |
| 286 | // and the built-in MCP support, no skills, prompt templates or themes, |
| 287 | // sessions in the runtime home, the connection's provider and model, the |
| 288 | // pinned tools, and the session to keep or resume. |
| 289 | func PiArgv(in PiPolicyInputs) []string { |
| 290 | argv := []string{PiNode, PiCLI, "--mode", "rpc", "--no-approve", "--offline", "--no-context-files", "--no-extensions", "-e", "builtin:mcp", "-e", PiExtension, "--no-skills", "--no-prompt-templates", "--no-themes", "--session-dir", PiSessions, "--provider", in.Provider, "--model", in.Model, "--tools", strings.Join(in.Tools, ",")} |
| 291 | if in.Resume != "" { |
| 292 | argv = append(argv, "--session-id", in.Resume) |
| 293 | } |
| 294 | return argv |
| 295 | } |
| 296 | |
| 297 | // piEnv is Pi's environment: its config directory, every startup fetch |
| 298 | // off (version check, catalogue, telemetry), and the extension's gate. |
| 299 | func piEnv(in PiPolicyInputs) map[string]string { |
| 300 | env := map[string]string{"LANG": "C.UTF-8", "PI_CODING_AGENT_DIR": PiAgentDir, "PI_OFFLINE": "1", "PI_SKIP_VERSION_CHECK": "1", "PI_TELEMETRY": "0", "EQUIPO_PI_TOOLS": strings.Join(in.Tools, ",")} |
| 301 | env["EQUIPO_PI_CONFINE"] = "/workspace" |
| 302 | if in.ExtraCA != "" { |
| 303 | env["NODE_EXTRA_CA_CERTS"] = piTestCA |
| 304 | } |
| 305 | return env |
| 306 | } |
| 307 | |
| 308 | // PiBinding is the binding of a Pi launch: the connection, its prepared |
| 309 | // runtime home and the home holding its key (never mounted). |
| 310 | func PiBinding(local, home, keyHome string) Binding { |
| 311 | return Binding{ID: local, Home: home, CredentialHome: keyHome, Token: true} |
| 312 | } |
| 313 | |
| 314 | // WritePiConfig writes the three config files into the runtime home's |
| 315 | // agent directory, 0600, as the policy will hash them. |
| 316 | func WritePiConfig(in PiPolicyInputs) error { |
| 317 | dir, err := pinDirectory(filepath.Join(in.Home, "agent")) |
| 318 | if err != nil { |
| 319 | return err |
| 320 | } |
| 321 | defer dir.Close() |
| 322 | for name, raw := range map[string]json.RawMessage{"models.json": in.Models, "settings.json": in.Settings, "mcp.json": in.MCP} { |
| 323 | c, err := canonical(raw) |
| 324 | if err != nil { |
| 325 | return err |
| 326 | } |
| 327 | if err := atomicPrivate(dir, name, c); err != nil { |
| 328 | return err |
| 329 | } |
| 330 | } |
| 331 | return nil |
| 332 | } |
| 333 | |
| 334 | // validPiTools: names only, each once; Pi's built-ins and Equipo's own |
| 335 | // MCP tools; no write or shell tool in a read-only role. |
| 336 | func validPiTools(tools []string, readOnly bool) bool { |
| 337 | if len(tools) == 0 { |
| 338 | return false |
| 339 | } |
| 340 | seen := map[string]bool{} |
| 341 | for _, t := range tools { |
| 342 | name, mcp := strings.CutPrefix(t, "mcp__equipo__") |
| 343 | switch { |
| 344 | case seen[t]: |
| 345 | return false |
| 346 | case mcp: |
| 347 | if name == "" || strings.Trim(name, "abcdefghijklmnopqrstuvwxyz_") != "" { |
| 348 | return false |
| 349 | } |
| 350 | case slices.Contains(piReadTools, t): |
| 351 | case slices.Contains(piWriteTools, t): |
| 352 | if readOnly { |
| 353 | return false |
| 354 | } |
| 355 | default: |
| 356 | return false |
| 357 | } |
| 358 | seen[t] = true |
| 359 | } |
| 360 | return true |
| 361 | } |
| 362 | |
| 363 | func piFile(m Mount) (fileDigest, error) { |
| 364 | fd, err := openNoLinks(m.Source, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK) |
| 365 | if err != nil { |
| 366 | return fileDigest{}, ErrPolicy |
| 367 | } |
| 368 | f := os.NewFile(uintptr(fd), m.Source) |
| 369 | defer f.Close() |
| 370 | info, err := f.Stat() |
| 371 | if err != nil || !info.Mode().IsRegular() { |
| 372 | return fileDigest{}, ErrPolicy |
| 373 | } |
| 374 | raw, err := io.ReadAll(f) |
| 375 | if err != nil { |
| 376 | return fileDigest{}, ErrPolicy |
| 377 | } |
| 378 | return fileDigest{Mount: m, SHA256: digest(raw)}, nil |
| 379 | } |
| 380 | |
| 381 | // readPiConfig reads the three config files back from the home. |
| 382 | func readPiConfig(home string) (models, settings, mcp json.RawMessage, err error) { |
| 383 | dir, err := pinDirectory(filepath.Join(home, "agent")) |
| 384 | if err != nil { |
| 385 | return nil, nil, nil, err |
| 386 | } |
| 387 | defer dir.Close() |
| 388 | out := make([]json.RawMessage, 3) |
| 389 | for i, name := range []string{"models.json", "settings.json", "mcp.json"} { |
| 390 | raw, err := readPrivate(dir, name) |
| 391 | if err != nil { |
| 392 | return nil, nil, nil, ErrPolicy |
| 393 | } |
| 394 | if out[i], err = canonical(raw); err != nil { |
| 395 | return nil, nil, nil, err |
| 396 | } |
| 397 | } |
| 398 | return out[0], out[1], out[2], nil |
| 399 | } |
| 400 | |
| 401 | // BuildPiPolicy checks a Pi launch's inputs and certifies them. |
| 402 | func BuildPiPolicy(in PiPolicyInputs) (Policy, error) { |
| 403 | profile, err := Profile(in.Action) |
| 404 | if err != nil || (in.Action != "implement" && in.Action != "inspect" && in.Action != "answer") { |
| 405 | return Policy{}, ErrPolicy |
| 406 | } |
| 407 | if PiKeyEnvs[in.Provider] == "" || in.KeyEnv != PiKeyEnvs[in.Provider] || in.Model == "" || strings.ContainsAny(in.Model, " \t\n,") || !validPiTools(in.Tools, profile.ReadOnly) || len(in.EgressHosts) == 0 { |
| 408 | return Policy{}, ErrPolicy |
| 409 | } |
| 410 | if in.Resume != "" && !piSessionID(in.Resume) { |
| 411 | return Policy{}, ErrPolicy |
| 412 | } |
| 413 | if in.ExtraCA != "" && !TestCAAllowed() { |
| 414 | return Policy{}, ErrPolicy |
| 415 | } |
| 416 | for _, path := range []string{in.Home, in.Workspace} { |
| 417 | f, err := pinDirectory(path) |
| 418 | if err != nil { |
| 419 | return Policy{}, ErrPolicy |
| 420 | } |
| 421 | f.Close() |
| 422 | } |
| 423 | if withinPath(in.Workspace, in.Home) || withinPath(in.Home, in.Workspace) { |
| 424 | return Policy{}, ErrPolicy |
| 425 | } |
| 426 | models, settings, mcp, err := readPiConfig(in.Home) |
| 427 | if err != nil { |
| 428 | return Policy{}, err |
| 429 | } |
| 430 | // Exactly Equipo's configuration, rebuilt here from the provider and |
| 431 | // model: no other setting, MCP server, command, argument or exposure, |
| 432 | // and no other field in models.json. |
| 433 | if PiBaseURLs[in.Provider] == "" { |
| 434 | return Policy{}, ErrPolicy |
| 435 | } |
| 436 | for _, pair := range [][3]json.RawMessage{{models, in.Models, PiModels(in.Provider, in.Model)}, {settings, in.Settings, PiSettings}, {mcp, in.MCP, PiMCP}} { |
| 437 | given, err := canonical(pair[1]) |
| 438 | if err != nil || !bytes.Equal(pair[0], given) { |
| 439 | return Policy{}, ErrPolicy |
| 440 | } |
| 441 | want, err := canonical(pair[2]) |
| 442 | if err != nil || !bytes.Equal(pair[0], want) { |
| 443 | return Policy{}, ErrPolicy |
| 444 | } |
| 445 | } |
| 446 | m := effectiveManifest{Version: piPolicyVersion, Action: in.Action, Provider: in.Provider, Harness: "pi", KeyEnv: in.KeyEnv, Argv: PiArgv(in), Env: piEnv(in), NamespaceArgs: NamespaceArguments(), Workspace: in.Workspace, RuntimeHome: in.Home, Tools: slices.Clone(in.Tools), Settings: settings, MCP: mcp, Catalog: models} |
| 447 | m.EgressHosts = slices.Clone(in.EgressHosts) |
| 448 | sort.Strings(m.EgressHosts) |
| 449 | m.OuterMounts = []Mount{{Source: in.Node, Target: PiNode, ReadOnly: true}, {Source: in.Tree, Target: PiTree, ReadOnly: true}, {Source: in.ToolProxy, Target: "/opt/equipo-tool-proxy", ReadOnly: true}, {Source: in.Extension, Target: PiExtension, ReadOnly: true}} |
| 450 | m.OuterMounts = append(m.OuterMounts, Mount{Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true}, Mount{Source: in.Shell, Target: PiShell, ReadOnly: true}) |
| 451 | if in.ExtraCA != "" { |
| 452 | m.OuterMounts = append(m.OuterMounts, Mount{Source: in.ExtraCA, Target: piTestCA, ReadOnly: true}) |
| 453 | } |
| 454 | for _, mount := range m.OuterMounts { |
| 455 | if mount.Target == PiTree { |
| 456 | continue |
| 457 | } |
| 458 | f, err := piFile(mount) |
| 459 | if err != nil { |
| 460 | return Policy{}, err |
| 461 | } |
| 462 | m.Files = append(m.Files, f) |
| 463 | } |
| 464 | for _, f := range m.Files { |
| 465 | if f.Mount.Target == PiShell && f.SHA256 != digest(PiShellSource()) { |
| 466 | return Policy{}, ErrPolicy |
| 467 | } |
| 468 | if f.Mount.Target == PiExtension && f.SHA256 != PiExtensionSHA256() { |
| 469 | return Policy{}, ErrPolicy |
| 470 | } |
| 471 | } |
| 472 | for _, name := range []string{"settings.json", "models.json", "mcp.json"} { |
| 473 | f, err := piFile(Mount{Source: filepath.Join(in.Home, "agent", name), Target: PiAgentDir + "/" + name, ReadOnly: true}) |
| 474 | if err != nil { |
| 475 | return Policy{}, err |
| 476 | } |
| 477 | m.Files = append(m.Files, f) |
| 478 | } |
| 479 | if m.Files[0].SHA256 != in.NodeSHA256 { |
| 480 | return Policy{}, ErrTree |
| 481 | } |
| 482 | if err := TreeRootSafe(in.Tree); err != nil { |
| 483 | return Policy{}, err |
| 484 | } |
| 485 | tree, err := TreeSHA256(in.Tree) |
| 486 | if err != nil || tree != in.TreeSHA256 { |
| 487 | return Policy{}, ErrTree |
| 488 | } |
| 489 | m.Trees = []treePin{{Mount: m.OuterMounts[1], SHA256: tree}} |
| 490 | if err := piGoPolicy(in, &m); err != nil { |
| 491 | return Policy{}, err |
| 492 | } |
| 493 | raw, hash, err := hashJSON(m) |
| 494 | if err != nil { |
| 495 | return Policy{}, err |
| 496 | } |
| 497 | return Policy{goLease: in.GoLease, Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: m.Env, Settings: settings, MCP: mcp}, nil |
| 498 | } |
| 499 | |
| 500 | // piSessionID is an id Pi accepts for --session-id, never a path. |
| 501 | func piSessionID(id string) bool { |
| 502 | if len(id) < 8 || len(id) > 64 { |
| 503 | return false |
| 504 | } |
| 505 | for _, r := range id { |
| 506 | if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r == '-') { |
| 507 | return false |
| 508 | } |
| 509 | } |
| 510 | return true |
| 511 | } |
| 512 | |
| 513 | func piManifest(p Policy) (effectiveManifest, bool) { |
| 514 | var m effectiveManifest |
| 515 | return m, p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && m.Version == piPolicyVersion |
| 516 | } |
| 517 | |
| 518 | // IsPi says the policy is a Pi launch's (BuildPiPolicy). |
| 519 | func (p Policy) IsPi() bool { _, ok := piManifest(p); return ok } |
| 520 | |
| 521 | // Harness is the policy's harness when it is not the provider's own CLI |
| 522 | // (Pi, OpenCode). |
| 523 | func (p Policy) Harness() string { m, _ := harnessManifest(p); return m.Harness } |
| 524 | |
| 525 | // KeyEnv is the variable a Pi or OpenCode launch receives its key in. |
| 526 | func (p Policy) KeyEnv() string { m, _ := harnessManifest(p); return m.KeyEnv } |
| 527 | |
| 528 | // attestPi holds a launch to its Pi policy, checked again from disk: the |
| 529 | // argv, environment and mounts it certified, the pinned files and tree |
| 530 | // unchanged, the config files as hashed, the selection's provider and |
| 531 | // model, the workspace, the runtime home, and a tool socket for its |
| 532 | // Equipo tools. |
| 533 | func attestPi(l Launch, argv []string) (string, error) { |
| 534 | p := l.Policy |
| 535 | m, ok := piManifest(p) |
| 536 | if !ok || p.Hash != p.ManifestHash || l.AttemptKey == "" || l.ToolSocket == "" || l.Workspace != m.Workspace || l.Binding.Home != m.RuntimeHome || l.Binding.Provider != "" || !l.Binding.Token || l.Binding.DedicatedHome { |
| 537 | return "", ErrPolicy |
| 538 | } |
| 539 | if l.Selection.Provider != m.Provider || l.Selection.Model == "" || !slices.Contains(m.Argv, l.Selection.Model) || !reflect.DeepEqual(argv, m.Argv) || !reflect.DeepEqual(p.Env, m.Env) || !reflect.DeepEqual(p.Mounts, m.OuterMounts) || !reflect.DeepEqual(m.NamespaceArgs, NamespaceArguments()) { |
| 540 | return "", ErrPolicy |
| 541 | } |
| 542 | if i := slices.Index(m.Argv, "--model"); i < 0 || i+1 >= len(m.Argv) || m.Argv[i+1] != l.Selection.Model { |
| 543 | return "", ErrPolicy |
| 544 | } |
| 545 | resume := "" |
| 546 | if i := slices.Index(m.Argv, "--session-id"); i >= 0 && i+1 < len(m.Argv) { |
| 547 | resume = m.Argv[i+1] |
| 548 | } |
| 549 | if l.ResumeSessionID != "" && l.ResumeSessionID != resume { |
| 550 | return "", ErrPolicy |
| 551 | } |
| 552 | for _, f := range m.Files { |
| 553 | if gotoolchain.Target(f.Mount.Target) { |
| 554 | held, err := p.OpenGoTree(l.Binding, f.Mount) |
| 555 | if err != nil { |
| 556 | return "", err |
| 557 | } |
| 558 | held.Close() |
| 559 | continue |
| 560 | } |
| 561 | current, err := piFile(f.Mount) |
| 562 | if err != nil || current.SHA256 != f.SHA256 { |
| 563 | return "", ErrPolicy |
| 564 | } |
| 565 | } |
| 566 | for _, t := range m.Trees { |
| 567 | if err := TreeRootSafe(t.Mount.Source); err != nil { |
| 568 | return "", err |
| 569 | } |
| 570 | sum, err := TreeSHA256(t.Mount.Source) |
| 571 | if err != nil || sum != t.SHA256 { |
| 572 | return "", ErrTree |
| 573 | } |
| 574 | } |
| 575 | models, settings, mcp, err := readPiConfig(m.RuntimeHome) |
| 576 | if err != nil || !bytes.Equal(models, m.Catalog) || !bytes.Equal(settings, m.Settings) || !bytes.Equal(mcp, m.MCP) { |
| 577 | return "", ErrPolicy |
| 578 | } |
| 579 | _, hash, err := hashJSON(struct{ Manifest, Attempt string }{p.ManifestHash, l.AttemptKey}) |
| 580 | return hash, err |
| 581 | } |
| 582 | |
| 583 | // piSecretEnv is a Pi or OpenCode launch's key, read from the |
| 584 | // connection's home. |
| 585 | func piSecretEnv(l Launch) (map[string]string, error) { |
| 586 | name := l.Policy.KeyEnv() |
| 587 | if name == "" || !l.Binding.Token || l.Binding.CredentialHome == "" { |
| 588 | return nil, ErrPolicy |
| 589 | } |
| 590 | raw, err := ReadToken(l.Binding.CredentialHome) |
| 591 | if err != nil { |
| 592 | return nil, err |
| 593 | } |
| 594 | defer clear(raw) |
| 595 | return map[string]string{name: string(raw)}, nil |
| 596 | } |
| 597 | |
| 598 | // PiArgv is a Pi policy's certified argv (nil for any other policy). |
| 599 | func (p Policy) PiArgv() []string { |
| 600 | m, ok := piManifest(p) |
| 601 | if !ok { |
| 602 | return nil |
| 603 | } |
| 604 | return slices.Clone(m.Argv) |
| 605 | } |
| 606 | |
| 607 | // PiTree is a Pi policy's package tree: its source and pinned digest. |
| 608 | // The containment hashes the tree again through the descriptor it |
| 609 | // mounts, so what the namespace sees is what was pinned. |
| 610 | func (p Policy) PiTree() (source, sha string, ok bool) { |
| 611 | m, ok := piManifest(p) |
| 612 | if !ok || len(m.Trees) != 1 { |
| 613 | return "", "", false |
| 614 | } |
| 615 | return m.Trees[0].Mount.Source, m.Trees[0].SHA256, true |
| 616 | } |
| 617 | |
| 618 | func (p Policy) CheckGateTreeSHA(mount Mount) string { |
| 619 | var m effectiveManifest |
| 620 | if !p.CheckGateTree(mount) || json.Unmarshal(p.Manifest, &m) != nil { |
| 621 | return "" |
| 622 | } |
| 623 | for _, t := range m.Trees { |
| 624 | if t.Mount == mount { |
| 625 | return t.SHA256 |
| 626 | } |
| 627 | } |
| 628 | return "" |
| 629 | } |
| 630 | |