| 1 | package pi |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "runtime" |
| 12 | "strings" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 15 | ) |
| 16 | |
| 17 | // Install is where a runner's Pi is: the pinned Node program and the |
| 18 | // installed node_modules tree, with the digests a launch requires |
| 19 | // (Pins for this platform; a test passes its fake's). |
| 20 | type Install struct { |
| 21 | Node, Tree, NodeSHA256, TreeSHA256 string |
| 22 | } |
| 23 | |
| 24 | // Pinned fills the digests from this platform's pins. |
| 25 | func (i Install) Pinned() (Install, bool) { |
| 26 | tree, node, ok := Pins(runtime.GOARCH) |
| 27 | if !ok { |
| 28 | return i, false |
| 29 | } |
| 30 | if i.NodeSHA256 == "" { |
| 31 | i.NodeSHA256 = node.BinarySHA256 |
| 32 | } |
| 33 | if i.TreeSHA256 == "" { |
| 34 | i.TreeSHA256 = tree |
| 35 | } |
| 36 | return i, i.Node != "" && i.Tree != "" |
| 37 | } |
| 38 | |
| 39 | // Paths are an install root's Node and tree as the installer lays them |
| 40 | // out: <root>/node/bin/node and <root>/pi/node_modules. |
| 41 | func Paths(root string) (node, tree string) { |
| 42 | return filepath.Join(root, "node", "bin", "node"), filepath.Join(root, "pi", "node_modules") |
| 43 | } |
| 44 | |
| 45 | // Run is one Pi launch's inputs, before the policy is built. |
| 46 | type Run struct { |
| 47 | Install |
| 48 | Bwrap, ToolProxy, Scratch string |
| 49 | GoRoot, ModuleCache string |
| 50 | Workspace, Action string |
| 51 | Provider, Model string |
| 52 | Equipo []string |
| 53 | Resume string |
| 54 | EgressHosts []string |
| 55 | ExtraCA string |
| 56 | } |
| 57 | |
| 58 | // Prepare makes the attempt's runtime home (under scratchRoot/homes, |
| 59 | // 0700: the containment mounts only a home there), writes Pi's config |
| 60 | // into its agent directory and Equipo's extension into the policy |
| 61 | // scratch, and returns the policy inputs. Cleanup removes the home. |
| 62 | func Prepare(scratchRoot string, r Run) (provider.PiPolicyInputs, func(), error) { |
| 63 | homes := filepath.Join(scratchRoot, "homes") |
| 64 | if err := os.MkdirAll(homes, 0700); err != nil { |
| 65 | return provider.PiPolicyInputs{}, nil, err |
| 66 | } |
| 67 | var b [6]byte |
| 68 | rand.Read(b[:]) |
| 69 | home := filepath.Join(homes, "pi-"+hex.EncodeToString(b[:])) |
| 70 | if err := os.Mkdir(home, 0700); err != nil { |
| 71 | return provider.PiPolicyInputs{}, nil, err |
| 72 | } |
| 73 | goLease := &provider.GoLease{} |
| 74 | cleanup := func() { goLease.Close(); os.RemoveAll(home) } |
| 75 | for _, d := range []string{"agent", "sessions"} { |
| 76 | if err := os.Mkdir(filepath.Join(home, d), 0700); err != nil { |
| 77 | cleanup() |
| 78 | return provider.PiPolicyInputs{}, nil, err |
| 79 | } |
| 80 | } |
| 81 | ext := filepath.Join(r.Scratch, "equipo.ts") |
| 82 | if err := os.WriteFile(ext, Extension(), 0600); err != nil { |
| 83 | cleanup() |
| 84 | return provider.PiPolicyInputs{}, nil, err |
| 85 | } |
| 86 | shell := filepath.Join(r.Scratch, "bash") |
| 87 | if err := os.WriteFile(shell, provider.PiShellSource(), 0700); err != nil { |
| 88 | cleanup() |
| 89 | return provider.PiPolicyInputs{}, nil, err |
| 90 | } |
| 91 | keyEnv := provider.PiKeyEnvs[r.Provider] |
| 92 | in := provider.PiPolicyInputs{Node: r.Node, NodeSHA256: r.NodeSHA256, Tree: r.Tree, TreeSHA256: r.TreeSHA256, Bwrap: r.Bwrap, ToolProxy: r.ToolProxy, Extension: ext, |
| 93 | Shell: shell, GoRoot: r.GoRoot, ModuleCache: r.ModuleCache, GoLease: goLease, Home: home, Workspace: r.Workspace, Action: r.Action, Provider: r.Provider, Model: r.Model, KeyEnv: keyEnv, Tools: Tools(r.Action, r.Equipo), Resume: r.Resume, |
| 94 | EgressHosts: r.EgressHosts, Models: Models(r.Provider, r.Model), Settings: Settings, MCP: MCP, ExtraCA: r.ExtraCA} |
| 95 | if err := provider.WritePiConfig(in); err != nil { |
| 96 | cleanup() |
| 97 | return provider.PiPolicyInputs{}, nil, err |
| 98 | } |
| 99 | return in, cleanup, nil |
| 100 | } |
| 101 | |
| 102 | // ErrNoSession: the session's transcript is not where it should be. |
| 103 | var ErrNoSession = errors.New("pi: no such session") |
| 104 | |
| 105 | func validID(id string) bool { |
| 106 | return len(id) >= 8 && len(id) <= 64 && strings.Trim(id, "0123456789abcdefghijklmnopqrstuvwxyz-") == "" |
| 107 | } |
| 108 | |
| 109 | // sessionFile is the one transcript of session id in dir (Pi names it |
| 110 | // <time>_<id>.jsonl). |
| 111 | func sessionFile(dir, id string) (string, error) { |
| 112 | if !validID(id) { |
| 113 | return "", ErrNoSession |
| 114 | } |
| 115 | matches, _ := filepath.Glob(filepath.Join(dir, "*_"+id+".jsonl")) |
| 116 | if len(matches) != 1 { |
| 117 | return "", ErrNoSession |
| 118 | } |
| 119 | info, err := os.Lstat(matches[0]) |
| 120 | if err != nil || !info.Mode().IsRegular() { |
| 121 | return "", ErrNoSession |
| 122 | } |
| 123 | return matches[0], nil |
| 124 | } |
| 125 | |
| 126 | // KeepSession copies a run's transcript from its runtime home into dir, |
| 127 | // for a question to resume, and returns its size. |
| 128 | func KeepSession(home, id, dir string) (int64, error) { |
| 129 | from, err := sessionFile(filepath.Join(home, "sessions"), id) |
| 130 | if err != nil { |
| 131 | return 0, err |
| 132 | } |
| 133 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 134 | return 0, err |
| 135 | } |
| 136 | if old, err := sessionFile(dir, id); err == nil { |
| 137 | os.Remove(old) |
| 138 | } |
| 139 | return copyFile(from, filepath.Join(dir, filepath.Base(from))) |
| 140 | } |
| 141 | |
| 142 | // RestoreSession puts a kept transcript into a fresh runtime home. |
| 143 | func RestoreSession(dir, id, home string) error { |
| 144 | from, err := sessionFile(dir, id) |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| 148 | _, err = copyFile(from, filepath.Join(home, "sessions", filepath.Base(from))) |
| 149 | return err |
| 150 | } |
| 151 | |
| 152 | // HasSession reports whether dir keeps session id. |
| 153 | func HasSession(dir, id string) bool { _, err := sessionFile(dir, id); return err == nil } |
| 154 | |
| 155 | func copyFile(from, to string) (int64, error) { |
| 156 | in, err := os.Open(from) |
| 157 | if err != nil { |
| 158 | return 0, err |
| 159 | } |
| 160 | defer in.Close() |
| 161 | tmp := to + ".tmp" |
| 162 | out, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| 163 | if err != nil { |
| 164 | return 0, err |
| 165 | } |
| 166 | n, err := io.Copy(out, in) |
| 167 | if err == nil { |
| 168 | err = out.Sync() |
| 169 | } |
| 170 | if cerr := out.Close(); err == nil { |
| 171 | err = cerr |
| 172 | } |
| 173 | if err == nil { |
| 174 | err = os.Rename(tmp, to) |
| 175 | } |
| 176 | if err != nil { |
| 177 | os.Remove(tmp) |
| 178 | } |
| 179 | return n, err |
| 180 | } |
| 181 | |
| 182 | // NewSessionID is an id for a new session (--session-id). |
| 183 | func NewSessionID() string { |
| 184 | var b [16]byte |
| 185 | rand.Read(b[:]) |
| 186 | h := hex.EncodeToString(b[:]) |
| 187 | return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:] |
| 188 | } |
| 189 | |
| 190 | // Verify holds an install root to this platform's pins: the Node |
| 191 | // program's digest and the whole tree's (sealed, every file, mode and |
| 192 | // link). A runner checks it at install and before it starts; every |
| 193 | // launch checks both again (provider.BuildPiPolicy and its attestation). |
| 194 | func Verify(root string) error { |
| 195 | treePin, nodePin, ok := Pins(runtime.GOARCH) |
| 196 | if !ok { |
| 197 | return ErrUnpinned |
| 198 | } |
| 199 | node, tree := Paths(root) |
| 200 | raw, err := os.ReadFile(node) |
| 201 | if err != nil { |
| 202 | return ErrUnpinned |
| 203 | } |
| 204 | sum := sha256.Sum256(raw) |
| 205 | if hex.EncodeToString(sum[:]) != nodePin.BinarySHA256 { |
| 206 | return ErrUnpinned |
| 207 | } |
| 208 | if provider.TreeRootSafe(tree) != nil { |
| 209 | return ErrUnpinned |
| 210 | } |
| 211 | got, err := TreeSHA256(tree) |
| 212 | if err != nil || got != treePin { |
| 213 | return ErrUnpinned |
| 214 | } |
| 215 | return nil |
| 216 | } |
| 217 | |