package provider import ( "bytes" _ "embed" "encoding/json" "fmt" "io" "os" "path/filepath" "reflect" "slices" "sort" "strings" "amadan.net/oficina/equipo/internal/runner/provider/gotoolchain" "golang.org/x/sys/unix" ) const checkPolicyVersion = "checks-v1" type CheckPolicyInputs struct { Workspace, Binary, RunnerBinary, Bwrap, GoRoot, ModuleCache string GateFiles []Mount Argv []string Env map[string]string } // BuildCheckPolicy admits no provider home, network, or writable host cache. func BuildCheckPolicy(in CheckPolicyInputs) (Policy, error) { home, err := os.UserHomeDir() if err != nil { return Policy{}, ErrPolicy } m := effectiveManifest{Version: checkPolicyVersion, Workspace: in.Workspace, Argv: in.Argv, Env: in.Env, NamespaceArgs: NamespaceArguments()} for _, path := range []string{in.Workspace, in.GoRoot, in.ModuleCache} { if path == "" && path != in.Workspace { // The Go toolchain and module cache are optional (thin checks // on a runner without them). continue } if path == "/" || path == "/tmp" || withinPath(home, path) { return Policy{}, fmt.Errorf("%w: check directory %q includes a broad host directory", ErrPolicy, path) } f, err := pinDirectory(path) if err != nil { return Policy{}, fmt.Errorf("%w: check directory %q must be a canonical directory without symlinks", err, path) } f.Close() } // Pinned files first (the Codex binary only when given; thin checks // run the repository's gate directly), then the Go trees. files := []Mount{{Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true}} if in.Binary != "" { files = append([]Mount{{Source: in.Binary, Target: "/opt/codex", ReadOnly: true}}, files...) } for _, mount := range in.GateFiles { if !mount.ReadOnly || !validGateTarget(mount.Target) || withinPath(in.Workspace, mount.Source) || withinPath(mount.Source, in.Workspace) { return Policy{}, ErrPolicy } files = append(files, mount) } m.OuterMounts = files if in.GoRoot != "" { m.OuterMounts = append(m.OuterMounts, Mount{Source: in.GoRoot, Target: "/opt/go", ReadOnly: true}) } if in.ModuleCache != "" { m.OuterMounts = append(m.OuterMounts, Mount{Source: in.ModuleCache, Target: "/opt/go-mod", ReadOnly: true}) } if in.Env != nil { for k, v := range gotoolchain.Environment() { if supplied, ok := in.Env[k]; ok && supplied != v { return Policy{}, ErrPolicy } } m.Env = map[string]string{} for k, v := range in.Env { m.Env[k] = v } for k, v := range gotoolchain.Environment() { m.Env[k] = v } } for _, mount := range files { fd, err := openNoLinks(mount.Source, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK) if err != nil { return Policy{}, ErrPolicy } f := os.NewFile(uintptr(fd), mount.Source) info, err := f.Stat() f.Close() if err == nil && info.IsDir() && validGateTarget(mount.Target) { sum, err := TreeSHA256(mount.Source) if err != nil { return Policy{}, err } m.Trees = append(m.Trees, treePin{Mount: mount, SHA256: sum}) continue } if err != nil || !info.Mode().IsRegular() { return Policy{}, ErrPolicy } raw, err := os.ReadFile(mount.Source) if err != nil { return Policy{}, err } m.Files = append(m.Files, fileDigest{Mount: mount, SHA256: digest(raw)}) } raw, hash, err := hashJSON(m) if err != nil { return Policy{}, err } return Policy{Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: m.Env}, nil } func (p Policy) IsCheck() bool { var m effectiveManifest return json.Unmarshal(p.Manifest, &m) == nil && m.Version == checkPolicyVersion } // CheckGateMount identifies a workspace file hashed by the check policy. func (p Policy) CheckGateMount(mount Mount) bool { if !p.IsCheck() || !mount.ReadOnly || !validGateTarget(mount.Target) { return false } var m effectiveManifest if json.Unmarshal(p.Manifest, &m) != nil { return false } for _, f := range m.Files { if f.Mount == mount { return true } } for _, t := range m.Trees { if t.Mount == mount { return true } } return false } func (p Policy) CheckGateTree(mount Mount) bool { var m effectiveManifest if !p.CheckGateMount(mount) || json.Unmarshal(p.Manifest, &m) != nil { return false } for _, t := range m.Trees { if t.Mount == mount { return true } } return false } func validGateTarget(target string) bool { if !strings.HasPrefix(target, "/workspace/") || filepath.Clean(target) != target || strings.ContainsAny(target, "\\\x00") { return false } relative := strings.TrimPrefix(target, "/workspace/") return relative != ".git" && !strings.HasPrefix(relative, ".git/") } func attestCheck(l Launch, argv []string) (string, error) { p := l.Policy var m effectiveManifest 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()) { return "", ErrPolicy } for _, f := range m.Files { raw, err := os.ReadFile(f.Mount.Source) if err != nil || digest(raw) != f.SHA256 { return "", ErrPolicy } } for _, t := range m.Trees { sum, err := TreeSHA256(t.Mount.Source) if err != nil || sum != t.SHA256 { return "", ErrPolicy } } for _, mount := range p.Mounts { if !mount.ReadOnly || !filepath.IsAbs(mount.Source) { return "", ErrPolicy } } _, hash, err := hashJSON(struct{ Manifest, Attempt string }{p.ManifestHash, l.AttemptKey}) return hash, err } // The Pi harness's effective policy (connectors spec §3 and §4.1, slice // S2), built and attested here like a check's: no account lease, every // input exact. Pi loads only what this names: Node and the Pi tree as // pinned, Equipo's extension and Pi's built-in MCP support (every other // extension, skill, prompt template, theme, context file and project // resource switched off by flag), its config directory in the attempt's // own runtime home with the three files the runner wrote and this hashed, // sessions in that home, and the tools the role pins. The key is not in // it: it reaches the namespace as KeyEnv through the secret pipe. const piPolicyVersion = "pi-v2" // Paths inside a Pi namespace. const ( PiNode = "/opt/node" PiTree = "/opt/pi/node_modules" PiCLI = PiTree + "/@earendil-works/pi-coding-agent/dist/bundle/cli.js" PiExtension = "/config/pi/equipo.ts" PiAgentDir = "/home/runner/agent" PiSessions = "/home/runner/sessions" piTestCA = "/opt/test-ca.pem" ) // PiKeyEnvs are the variables a Pi launch may receive its key in, one per // provider behind Pi. var PiKeyEnvs = map[string]string{"tensorx": "TENSORX_API_KEY"} // PiBaseURLs are the OpenAI-compatible base URLs of the providers behind // Pi (the provider table's upstream and API path). var PiBaseURLs = map[string]string{"tensorx": "https://api.tensorx.ai/v1"} // piExtension is Equipo's own Pi extension (pi_extension.ts), the only // one Pi loads beside its built-in MCP support: the tool gate. A Pi // policy pins its digest. // //go:embed pi_extension.ts var piExtension []byte // PiExtensionSource is the extension's source. func PiExtensionSource() []byte { return bytes.Clone(piExtension) } // PiExtensionSHA256 is its digest. func PiExtensionSHA256() string { return digest(piExtension) } // PiSettings is settings.json: project trust never granted, whatever a // flag or a project says. var PiSettings = json.RawMessage(`{"defaultProjectTrust":"never","shellPath":"/config/pi/bash"}`) // PiMCP is mcp.json: Equipo's own tools only, through the tool proxy on // the attempt's socket, declared to the model directly (no codemode, no // tool search). var PiMCP = json.RawMessage(`{"autoEnableCodemode":false,"mcpServers":{"equipo":{"command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"],"exposure":"direct"}}}`) // PiModels is models.json for one provider behind Pi: its base URL, the // chat completions API, the key by its variable (never the key) and the // connection's one model. func PiModels(provider, model string) json.RawMessage { 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}}}}}) return raw } // piTools are the tools a Pi role may pin: Pi's built-ins, and the step's // own Equipo tools over MCP, each named exactly. var piReadTools = []string{"read", "grep", "find", "ls"} var piWriteTools = []string{"bash", "edit", "write"} // PiPolicyInputs are one Pi launch's inputs. Node, Tree, Bwrap, // ToolProxy and Extension are host paths; Home is the attempt's runtime // home (under the scratch root's homes), whose agent directory holds // Models, Settings and MCP as WritePiConfig wrote them. type PiPolicyInputs struct { Node, NodeSHA256, Tree, TreeSHA256 string Bwrap, ToolProxy, Extension string Shell, GoRoot, ModuleCache string GoLease *GoLease Home, Workspace, Action string Provider, Model, KeyEnv string Tools, EgressHosts []string Resume string Models, Settings, MCP json.RawMessage // ExtraCA is a test build's certificate authority for its fake // provider (TestCAAllowed); a release build refuses one. ExtraCA string } // testCA is set by the test build only (testca_testbuild.go). var testCA bool // TestCAAllowed reports whether this build lets a Pi launch trust a test // certificate authority: only a test build does. func TestCAAllowed() bool { return testCA } // PiArgv is Pi's exact argv inside the namespace: RPC mode, project // trust refused, offline, no context files, no extension but Equipo's // and the built-in MCP support, no skills, prompt templates or themes, // sessions in the runtime home, the connection's provider and model, the // pinned tools, and the session to keep or resume. func PiArgv(in PiPolicyInputs) []string { 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, ",")} if in.Resume != "" { argv = append(argv, "--session-id", in.Resume) } return argv } // piEnv is Pi's environment: its config directory, every startup fetch // off (version check, catalogue, telemetry), and the extension's gate. func piEnv(in PiPolicyInputs) map[string]string { 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, ",")} env["EQUIPO_PI_CONFINE"] = "/workspace" if in.ExtraCA != "" { env["NODE_EXTRA_CA_CERTS"] = piTestCA } return env } // PiBinding is the binding of a Pi launch: the connection, its prepared // runtime home and the home holding its key (never mounted). func PiBinding(local, home, keyHome string) Binding { return Binding{ID: local, Home: home, CredentialHome: keyHome, Token: true} } // WritePiConfig writes the three config files into the runtime home's // agent directory, 0600, as the policy will hash them. func WritePiConfig(in PiPolicyInputs) error { dir, err := pinDirectory(filepath.Join(in.Home, "agent")) if err != nil { return err } defer dir.Close() for name, raw := range map[string]json.RawMessage{"models.json": in.Models, "settings.json": in.Settings, "mcp.json": in.MCP} { c, err := canonical(raw) if err != nil { return err } if err := atomicPrivate(dir, name, c); err != nil { return err } } return nil } // validPiTools: names only, each once; Pi's built-ins and Equipo's own // MCP tools; no write or shell tool in a read-only role. func validPiTools(tools []string, readOnly bool) bool { if len(tools) == 0 { return false } seen := map[string]bool{} for _, t := range tools { name, mcp := strings.CutPrefix(t, "mcp__equipo__") switch { case seen[t]: return false case mcp: if name == "" || strings.Trim(name, "abcdefghijklmnopqrstuvwxyz_") != "" { return false } case slices.Contains(piReadTools, t): case slices.Contains(piWriteTools, t): if readOnly { return false } default: return false } seen[t] = true } return true } func piFile(m Mount) (fileDigest, error) { fd, err := openNoLinks(m.Source, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK) if err != nil { return fileDigest{}, ErrPolicy } f := os.NewFile(uintptr(fd), m.Source) defer f.Close() info, err := f.Stat() if err != nil || !info.Mode().IsRegular() { return fileDigest{}, ErrPolicy } raw, err := io.ReadAll(f) if err != nil { return fileDigest{}, ErrPolicy } return fileDigest{Mount: m, SHA256: digest(raw)}, nil } // readPiConfig reads the three config files back from the home. func readPiConfig(home string) (models, settings, mcp json.RawMessage, err error) { dir, err := pinDirectory(filepath.Join(home, "agent")) if err != nil { return nil, nil, nil, err } defer dir.Close() out := make([]json.RawMessage, 3) for i, name := range []string{"models.json", "settings.json", "mcp.json"} { raw, err := readPrivate(dir, name) if err != nil { return nil, nil, nil, ErrPolicy } if out[i], err = canonical(raw); err != nil { return nil, nil, nil, err } } return out[0], out[1], out[2], nil } // BuildPiPolicy checks a Pi launch's inputs and certifies them. func BuildPiPolicy(in PiPolicyInputs) (Policy, error) { profile, err := Profile(in.Action) if err != nil || (in.Action != "implement" && in.Action != "inspect" && in.Action != "answer") { return Policy{}, ErrPolicy } 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 { return Policy{}, ErrPolicy } if in.Resume != "" && !piSessionID(in.Resume) { return Policy{}, ErrPolicy } if in.ExtraCA != "" && !TestCAAllowed() { return Policy{}, ErrPolicy } for _, path := range []string{in.Home, in.Workspace} { f, err := pinDirectory(path) if err != nil { return Policy{}, ErrPolicy } f.Close() } if withinPath(in.Workspace, in.Home) || withinPath(in.Home, in.Workspace) { return Policy{}, ErrPolicy } models, settings, mcp, err := readPiConfig(in.Home) if err != nil { return Policy{}, err } // Exactly Equipo's configuration, rebuilt here from the provider and // model: no other setting, MCP server, command, argument or exposure, // and no other field in models.json. if PiBaseURLs[in.Provider] == "" { return Policy{}, ErrPolicy } for _, pair := range [][3]json.RawMessage{{models, in.Models, PiModels(in.Provider, in.Model)}, {settings, in.Settings, PiSettings}, {mcp, in.MCP, PiMCP}} { given, err := canonical(pair[1]) if err != nil || !bytes.Equal(pair[0], given) { return Policy{}, ErrPolicy } want, err := canonical(pair[2]) if err != nil || !bytes.Equal(pair[0], want) { return Policy{}, ErrPolicy } } 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} m.EgressHosts = slices.Clone(in.EgressHosts) sort.Strings(m.EgressHosts) 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}} m.OuterMounts = append(m.OuterMounts, Mount{Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true}, Mount{Source: in.Shell, Target: PiShell, ReadOnly: true}) if in.ExtraCA != "" { m.OuterMounts = append(m.OuterMounts, Mount{Source: in.ExtraCA, Target: piTestCA, ReadOnly: true}) } for _, mount := range m.OuterMounts { if mount.Target == PiTree { continue } f, err := piFile(mount) if err != nil { return Policy{}, err } m.Files = append(m.Files, f) } for _, f := range m.Files { if f.Mount.Target == PiShell && f.SHA256 != digest(PiShellSource()) { return Policy{}, ErrPolicy } if f.Mount.Target == PiExtension && f.SHA256 != PiExtensionSHA256() { return Policy{}, ErrPolicy } } for _, name := range []string{"settings.json", "models.json", "mcp.json"} { f, err := piFile(Mount{Source: filepath.Join(in.Home, "agent", name), Target: PiAgentDir + "/" + name, ReadOnly: true}) if err != nil { return Policy{}, err } m.Files = append(m.Files, f) } if m.Files[0].SHA256 != in.NodeSHA256 { return Policy{}, ErrTree } if err := TreeRootSafe(in.Tree); err != nil { return Policy{}, err } tree, err := TreeSHA256(in.Tree) if err != nil || tree != in.TreeSHA256 { return Policy{}, ErrTree } m.Trees = []treePin{{Mount: m.OuterMounts[1], SHA256: tree}} if err := piGoPolicy(in, &m); err != nil { return Policy{}, err } raw, hash, err := hashJSON(m) if err != nil { return Policy{}, err } return Policy{goLease: in.GoLease, Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: m.Env, Settings: settings, MCP: mcp}, nil } // piSessionID is an id Pi accepts for --session-id, never a path. func piSessionID(id string) bool { if len(id) < 8 || len(id) > 64 { return false } for _, r := range id { if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r == '-') { return false } } return true } func piManifest(p Policy) (effectiveManifest, bool) { var m effectiveManifest return m, p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && m.Version == piPolicyVersion } // IsPi says the policy is a Pi launch's (BuildPiPolicy). func (p Policy) IsPi() bool { _, ok := piManifest(p); return ok } // Harness is the policy's harness when it is not the provider's own CLI // (Pi, OpenCode). func (p Policy) Harness() string { m, _ := harnessManifest(p); return m.Harness } // KeyEnv is the variable a Pi or OpenCode launch receives its key in. func (p Policy) KeyEnv() string { m, _ := harnessManifest(p); return m.KeyEnv } // attestPi holds a launch to its Pi policy, checked again from disk: the // argv, environment and mounts it certified, the pinned files and tree // unchanged, the config files as hashed, the selection's provider and // model, the workspace, the runtime home, and a tool socket for its // Equipo tools. func attestPi(l Launch, argv []string) (string, error) { p := l.Policy m, ok := piManifest(p) 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 { return "", ErrPolicy } 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()) { return "", ErrPolicy } if i := slices.Index(m.Argv, "--model"); i < 0 || i+1 >= len(m.Argv) || m.Argv[i+1] != l.Selection.Model { return "", ErrPolicy } resume := "" if i := slices.Index(m.Argv, "--session-id"); i >= 0 && i+1 < len(m.Argv) { resume = m.Argv[i+1] } if l.ResumeSessionID != "" && l.ResumeSessionID != resume { return "", ErrPolicy } for _, f := range m.Files { if gotoolchain.Target(f.Mount.Target) { held, err := p.OpenGoTree(l.Binding, f.Mount) if err != nil { return "", err } held.Close() continue } current, err := piFile(f.Mount) if err != nil || current.SHA256 != f.SHA256 { return "", ErrPolicy } } for _, t := range m.Trees { if err := TreeRootSafe(t.Mount.Source); err != nil { return "", err } sum, err := TreeSHA256(t.Mount.Source) if err != nil || sum != t.SHA256 { return "", ErrTree } } models, settings, mcp, err := readPiConfig(m.RuntimeHome) if err != nil || !bytes.Equal(models, m.Catalog) || !bytes.Equal(settings, m.Settings) || !bytes.Equal(mcp, m.MCP) { return "", ErrPolicy } _, hash, err := hashJSON(struct{ Manifest, Attempt string }{p.ManifestHash, l.AttemptKey}) return hash, err } // piSecretEnv is a Pi or OpenCode launch's key, read from the // connection's home. func piSecretEnv(l Launch) (map[string]string, error) { name := l.Policy.KeyEnv() if name == "" || !l.Binding.Token || l.Binding.CredentialHome == "" { return nil, ErrPolicy } raw, err := ReadToken(l.Binding.CredentialHome) if err != nil { return nil, err } defer clear(raw) return map[string]string{name: string(raw)}, nil } // PiArgv is a Pi policy's certified argv (nil for any other policy). func (p Policy) PiArgv() []string { m, ok := piManifest(p) if !ok { return nil } return slices.Clone(m.Argv) } // PiTree is a Pi policy's package tree: its source and pinned digest. // The containment hashes the tree again through the descriptor it // mounts, so what the namespace sees is what was pinned. func (p Policy) PiTree() (source, sha string, ok bool) { m, ok := piManifest(p) if !ok || len(m.Trees) != 1 { return "", "", false } return m.Trees[0].Mount.Source, m.Trees[0].SHA256, true } func (p Policy) CheckGateTreeSHA(mount Mount) string { var m effectiveManifest if !p.CheckGateTree(mount) || json.Unmarshal(p.Manifest, &m) != nil { return "" } for _, t := range m.Trees { if t.Mount == mount { return t.SHA256 } } return "" }