| 1 | package provider |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "io" |
| 9 | "net/netip" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "reflect" |
| 13 | "slices" |
| 14 | "sort" |
| 15 | "strings" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/runner/provider/gotoolchain" |
| 18 | "golang.org/x/sys/unix" |
| 19 | ) |
| 20 | |
| 21 | const PolicyVersion = "direct-v1" |
| 22 | const SettingsPath = "/config/equipo-settings.json" |
| 23 | const CoordinatorCatalogPath = "/config/equipo-coordinator-models.json" |
| 24 | const MCPPath = "/config/equipo-mcp.json" |
| 25 | |
| 26 | type PolicyInputs struct { |
| 27 | NativeTools []string `json:",omitempty"` |
| 28 | Action string |
| 29 | AuthHost string |
| 30 | RuntimeFiles []Mount |
| 31 | DeniedPaths, EgressHosts []string |
| 32 | ProviderVersion, LauncherVersion, BwrapVersion string |
| 33 | Catalog json.RawMessage `json:",omitempty"` |
| 34 | Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage |
| 35 | Tools []string |
| 36 | // Adapters supply the exact argv and any permitted nonsecret environment. |
| 37 | Argv []string |
| 38 | Env map[string]string |
| 39 | Workspace, Scratch string |
| 40 | InstructionFiles []Mount |
| 41 | } |
| 42 | type fileDigest struct { |
| 43 | Mount Mount |
| 44 | SHA256 string |
| 45 | } |
| 46 | type effectiveManifest struct { |
| 47 | NativeTools []string `json:",omitempty"` |
| 48 | Action string `json:",omitempty"` |
| 49 | AuthHost string |
| 50 | OuterMounts, GeneratedMounts []Mount |
| 51 | NamespaceArgs []string |
| 52 | Version string |
| 53 | BindingID, Provider, AccountID, CredentialHome string |
| 54 | Identity Identity |
| 55 | ProviderVersion, LauncherVersion, BwrapVersion string |
| 56 | Argv []string |
| 57 | Env map[string]string |
| 58 | Files []fileDigest |
| 59 | DeniedPaths, EgressHosts, Tools []string |
| 60 | Catalog json.RawMessage `json:",omitempty"` |
| 61 | Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage |
| 62 | Workspace, Scratch, RuntimeHome, ConfigHome string |
| 63 | Instructions []fileDigest |
| 64 | HooksDisabled, PluginsDisabled, TurnOverridesOmitted bool |
| 65 | MaskedDirectories []string |
| 66 | Proxy string |
| 67 | // A harness that is not the provider's own CLI (Pi): its name, the |
| 68 | // variable its key is delivered in, and its pinned package trees. |
| 69 | // Empty for every other policy, so their hashes are unchanged. |
| 70 | Harness string `json:",omitempty"` |
| 71 | KeyEnv string `json:",omitempty"` |
| 72 | Trees []treePin `json:",omitempty"` |
| 73 | } |
| 74 | |
| 75 | // treePin is a package tree mounted whole, by its committed digest. |
| 76 | type treePin struct { |
| 77 | Mount Mount |
| 78 | SHA256 string |
| 79 | } |
| 80 | |
| 81 | func digest(raw []byte) string { s := sha256.Sum256(raw); return hex.EncodeToString(s[:]) } |
| 82 | func hashJSON(value any) ([]byte, string, error) { |
| 83 | raw, e := json.Marshal(value) |
| 84 | return raw, digest(raw), e |
| 85 | } |
| 86 | |
| 87 | // Canonical JSON rejects duplicate keys so the harness and attestation cannot |
| 88 | // interpret the same configuration differently. Numbers retain their precision. |
| 89 | func canonical(raw json.RawMessage) (json.RawMessage, error) { |
| 90 | if len(raw) == 0 { |
| 91 | raw = json.RawMessage(`{}`) |
| 92 | } |
| 93 | d := json.NewDecoder(bytes.NewReader(raw)) |
| 94 | d.UseNumber() |
| 95 | value, e := jsonValue(d) |
| 96 | if e != nil { |
| 97 | return nil, ErrPolicy |
| 98 | } |
| 99 | if _, e = d.Token(); e != io.EOF { |
| 100 | return nil, ErrPolicy |
| 101 | } |
| 102 | if _, ok := value.(map[string]any); !ok { |
| 103 | return nil, ErrPolicy |
| 104 | } |
| 105 | out, e := json.Marshal(value) |
| 106 | return out, e |
| 107 | } |
| 108 | func jsonValue(d *json.Decoder) (any, error) { |
| 109 | token, e := d.Token() |
| 110 | if e != nil { |
| 111 | return nil, e |
| 112 | } |
| 113 | delim, ok := token.(json.Delim) |
| 114 | if !ok { |
| 115 | return token, nil |
| 116 | } |
| 117 | switch delim { |
| 118 | case '{': |
| 119 | m := map[string]any{} |
| 120 | for d.More() { |
| 121 | key, e := d.Token() |
| 122 | if e != nil { |
| 123 | return nil, e |
| 124 | } |
| 125 | k, ok := key.(string) |
| 126 | if !ok { |
| 127 | return nil, ErrPolicy |
| 128 | } |
| 129 | if _, ok = m[k]; ok { |
| 130 | return nil, ErrPolicy |
| 131 | } |
| 132 | v, e := jsonValue(d) |
| 133 | if e != nil { |
| 134 | return nil, e |
| 135 | } |
| 136 | m[k] = v |
| 137 | } |
| 138 | _, e = d.Token() |
| 139 | return m, e |
| 140 | case '[': |
| 141 | a := []any{} |
| 142 | for d.More() { |
| 143 | v, e := jsonValue(d) |
| 144 | if e != nil { |
| 145 | return nil, e |
| 146 | } |
| 147 | a = append(a, v) |
| 148 | } |
| 149 | _, e = d.Token() |
| 150 | return a, e |
| 151 | } |
| 152 | return nil, ErrPolicy |
| 153 | } |
| 154 | func validTurnPolicy(raw json.RawMessage) bool { |
| 155 | var value map[string]any |
| 156 | if json.Unmarshal(raw, &value) != nil { |
| 157 | return false |
| 158 | } |
| 159 | // Only non-authority turn parameters are allowed. Adding an SDK field requires |
| 160 | // a deliberate policy revision; unknown fields cannot become hidden overrides. |
| 161 | for key := range value { |
| 162 | switch key { |
| 163 | case "effort", "summary": |
| 164 | default: |
| 165 | return false |
| 166 | } |
| 167 | } |
| 168 | return true |
| 169 | } |
| 170 | func nonsecretJSON(raw json.RawMessage) bool { |
| 171 | var value any |
| 172 | if json.Unmarshal(raw, &value) != nil { |
| 173 | return false |
| 174 | } |
| 175 | var safe func(any) bool |
| 176 | safe = func(v any) bool { |
| 177 | switch x := v.(type) { |
| 178 | case map[string]any: |
| 179 | for k, v := range x { |
| 180 | lower := strings.ToLower(k) |
| 181 | if k == "token_budget" && v == false { |
| 182 | continue |
| 183 | } |
| 184 | if strings.Contains(lower, "token") || strings.Contains(lower, "secret") || strings.Contains(lower, "password") || strings.Contains(lower, "api_key") || strings.Contains(lower, "apikey") || lower == "authorization" { |
| 185 | return false |
| 186 | } |
| 187 | if !safe(v) { |
| 188 | return false |
| 189 | } |
| 190 | } |
| 191 | case []any: |
| 192 | for _, v := range x { |
| 193 | if !safe(v) { |
| 194 | return false |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | return true |
| 199 | } |
| 200 | return safe(value) |
| 201 | } |
| 202 | func hashFiles(mounts []Mount, b Binding) ([]fileDigest, error) { |
| 203 | out := make([]fileDigest, 0, len(mounts)) |
| 204 | seen := map[string]bool{} |
| 205 | for _, m := range mounts { |
| 206 | if credentialSource(m.Source, b) { |
| 207 | return nil, ErrPolicy |
| 208 | } |
| 209 | if !m.ReadOnly || !cleanPath(m.Source) || !cleanPath(m.Target) || seen[m.Target] || withinPath(m.Source, b.CredentialHome) || withinPath(m.Source, b.Home) { |
| 210 | return nil, ErrPolicy |
| 211 | } |
| 212 | if !(strings.HasPrefix(m.Target, "/opt/") || strings.HasPrefix(m.Target, "/config/") || strings.HasPrefix(m.Target, "/etc/claude-code/") || strings.HasPrefix(m.Target, "/etc/codex/")) { |
| 213 | return nil, ErrPolicy |
| 214 | } |
| 215 | if gotoolchain.Target(m.Target) { |
| 216 | f, e := goTree(m, b) |
| 217 | if e != nil { |
| 218 | return nil, e |
| 219 | } |
| 220 | out = append(out, f) |
| 221 | seen[m.Target] = true |
| 222 | continue |
| 223 | } |
| 224 | fd, e := openNoLinks(m.Source, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK) |
| 225 | if e != nil { |
| 226 | return nil, ErrPolicy |
| 227 | } |
| 228 | f := os.NewFile(uintptr(fd), m.Source) |
| 229 | var stat unix.Stat_t |
| 230 | if unix.Fstat(fd, &stat) != nil || stat.Nlink != 1 { |
| 231 | f.Close() |
| 232 | return nil, ErrPolicy |
| 233 | } |
| 234 | info, e := f.Stat() |
| 235 | if e != nil || !info.Mode().IsRegular() { |
| 236 | f.Close() |
| 237 | return nil, ErrPolicy |
| 238 | } |
| 239 | h := sha256.New() |
| 240 | _, e = io.Copy(h, f) |
| 241 | f.Close() |
| 242 | if e != nil { |
| 243 | return nil, ErrPolicy |
| 244 | } |
| 245 | out = append(out, fileDigest{Mount: m, SHA256: hex.EncodeToString(h.Sum(nil))}) |
| 246 | seen[m.Target] = true |
| 247 | } |
| 248 | return out, nil |
| 249 | } |
| 250 | func BuildPolicy(b Binding, in PolicyInputs) (Policy, error) { |
| 251 | var native []string |
| 252 | // A Research step has no native tools either: only what the provider |
| 253 | // registers whenever MCP is configured, pinned as for the coordinator. |
| 254 | if CoordinatorAction(in.Action) || ResearchAction(in.Action) || in.Action == GlanceAction { |
| 255 | native = CoordinatorNativeTools(b.Provider) |
| 256 | } |
| 257 | if !slices.Equal(in.NativeTools, native) { |
| 258 | return Policy{}, ErrPolicy |
| 259 | } |
| 260 | |
| 261 | if !b.VerifiedDedicatedHome() { |
| 262 | return Policy{}, ErrIdentity |
| 263 | } |
| 264 | if in.ProviderVersion == "" || in.LauncherVersion == "" || in.BwrapVersion == "" || len(in.RuntimeFiles) == 0 || len(in.Argv) == 0 || !cleanPath(in.Argv[0]) || len(in.EgressHosts) == 0 { |
| 265 | return Policy{}, ErrPolicy |
| 266 | } |
| 267 | for _, path := range []string{in.Workspace, in.Scratch} { |
| 268 | f, e := pinDirectory(path) |
| 269 | if e != nil { |
| 270 | return Policy{}, ErrPolicy |
| 271 | } |
| 272 | f.Close() |
| 273 | for _, protected := range append([]string{b.Home, b.CredentialHome, b.RuntimeRoot}, in.DeniedPaths...) { |
| 274 | if withinPath(path, protected) || withinPath(protected, path) { |
| 275 | return Policy{}, ErrPolicy |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | if withinPath(in.Workspace, in.Scratch) || withinPath(in.Scratch, in.Workspace) { |
| 280 | return Policy{}, ErrPolicy |
| 281 | } |
| 282 | settings, e := canonical(in.Settings) |
| 283 | if e != nil { |
| 284 | return Policy{}, e |
| 285 | } |
| 286 | mcp, e := canonical(in.MCP) |
| 287 | if e != nil { |
| 288 | return Policy{}, e |
| 289 | } |
| 290 | thread, e := canonical(in.ThreadPolicy) |
| 291 | if e != nil { |
| 292 | return Policy{}, e |
| 293 | } |
| 294 | turn, e := canonical(in.TurnPolicy) |
| 295 | if e != nil || !validTurnPolicy(turn) { |
| 296 | return Policy{}, ErrPolicy |
| 297 | } |
| 298 | for _, raw := range []json.RawMessage{settings, mcp, thread, turn} { |
| 299 | if !nonsecretJSON(raw) { |
| 300 | return Policy{}, ErrPolicy |
| 301 | } |
| 302 | } |
| 303 | env := map[string]string{"LANG": "C.UTF-8", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"} |
| 304 | if b.Provider == "codex" { |
| 305 | env["CODEX_HOME"] = "/home/runner" |
| 306 | } else { |
| 307 | env["CLAUDE_CONFIG_DIR"] = "/home/runner" |
| 308 | env["CLAUDE_SECURESTORAGE_CONFIG_DIR"] = "/home/runner" |
| 309 | env["CLAUDE_TMPDIR"] = "/tmp" |
| 310 | env["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"] = "1" |
| 311 | env["DISABLE_AUTOUPDATER"] = "1" |
| 312 | } |
| 313 | for k, v := range in.Env { |
| 314 | if (k != "LANG" && k != "LC_ALL" && k != "TERM") || strings.ContainsRune(v, 0) { |
| 315 | return Policy{}, ErrPolicy |
| 316 | } |
| 317 | env[k] = v |
| 318 | } |
| 319 | for _, file := range append(append([]Mount(nil), in.RuntimeFiles...), in.InstructionFiles...) { |
| 320 | if withinPath(file.Source, in.Workspace) || withinPath(file.Source, in.Scratch) { |
| 321 | return Policy{}, ErrPolicy |
| 322 | } |
| 323 | } |
| 324 | for _, file := range in.RuntimeFiles { |
| 325 | if gotoolchain.Target(file.Target) { |
| 326 | if in.Action != "implement" { |
| 327 | return Policy{}, ErrPolicy |
| 328 | } |
| 329 | for _, protected := range append([]string{b.Home, b.CredentialHome, b.RuntimeRoot, in.Workspace, in.Scratch}, in.DeniedPaths...) { |
| 330 | if withinPath(file.Source, protected) || withinPath(protected, file.Source) { |
| 331 | return Policy{}, ErrPolicy |
| 332 | } |
| 333 | } |
| 334 | for k, v := range gotoolchain.Environment(b.Provider) { |
| 335 | env[k] = v |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | files, e := hashFiles(in.RuntimeFiles, b) |
| 340 | if e != nil { |
| 341 | return Policy{}, e |
| 342 | } |
| 343 | instructions, e := hashFiles(in.InstructionFiles, b) |
| 344 | if e != nil { |
| 345 | return Policy{}, e |
| 346 | } |
| 347 | denied := append([]string(nil), in.DeniedPaths...) |
| 348 | denied = append(denied, b.CredentialHome, "/home/runner") |
| 349 | sort.Strings(denied) |
| 350 | for _, path := range denied { |
| 351 | if !cleanPath(path) { |
| 352 | return Policy{}, ErrPolicy |
| 353 | } |
| 354 | } |
| 355 | binaryPresent := false |
| 356 | for _, file := range files { |
| 357 | if file.Mount.Target == in.Argv[0] { |
| 358 | binaryPresent = true |
| 359 | } |
| 360 | } |
| 361 | if !binaryPresent { |
| 362 | return Policy{}, ErrPolicy |
| 363 | } |
| 364 | if in.AuthHost != "" && (!validAuthHost(in.AuthHost) || !slices.Contains(in.EgressHosts, in.AuthHost)) { |
| 365 | return Policy{}, ErrPolicy |
| 366 | } |
| 367 | hosts := append([]string(nil), in.EgressHosts...) |
| 368 | sort.Strings(hosts) |
| 369 | for i, h := range hosts { |
| 370 | if _, e := netip.ParseAddr(h); e == nil { |
| 371 | return Policy{}, ErrPolicy |
| 372 | } |
| 373 | if h == "" || strings.ContainsAny(h, "/:*@ \t\n") || h != strings.ToLower(h) || (i > 0 && h == hosts[i-1]) { |
| 374 | return Policy{}, ErrPolicy |
| 375 | } |
| 376 | } |
| 377 | tools := append([]string(nil), in.Tools...) |
| 378 | for i, v := range tools { |
| 379 | if v == "" { |
| 380 | return Policy{}, ErrPolicy |
| 381 | } |
| 382 | for _, prior := range tools[:i] { |
| 383 | if prior == v { |
| 384 | return Policy{}, ErrPolicy |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | fullEnv := map[string]string{"PATH": "/usr/bin:/bin:/opt", "HOME": "/home/runner", "TMPDIR": "/tmp"} |
| 389 | for k, v := range env { |
| 390 | fullEnv[k] = v |
| 391 | } |
| 392 | for _, k := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"} { |
| 393 | fullEnv[k] = "http://127.0.0.1:18080" |
| 394 | } |
| 395 | m := effectiveManifest{NativeTools: slices.Clone(in.NativeTools), Action: in.Action, AuthHost: in.AuthHost, Version: PolicyVersion, BindingID: b.ID, Provider: b.Provider, AccountID: b.AccountID, CredentialHome: b.CredentialHome, Identity: b.Expected, ProviderVersion: in.ProviderVersion, LauncherVersion: in.LauncherVersion, BwrapVersion: in.BwrapVersion, Argv: append([]string(nil), in.Argv...), Env: fullEnv, Files: files, DeniedPaths: denied, EgressHosts: hosts, Tools: tools, Catalog: in.Catalog, Settings: settings, MCP: mcp, ThreadPolicy: thread, TurnPolicy: turn, Workspace: in.Workspace, Scratch: in.Scratch, RuntimeHome: b.Home, ConfigHome: b.provenance.config, Instructions: instructions, HooksDisabled: true, PluginsDisabled: true, TurnOverridesOmitted: true, MaskedDirectories: []string{"/etc/claude-code", "/etc/codex"}, Proxy: "http://127.0.0.1:18080"} |
| 396 | readOnly := false |
| 397 | if in.Action != "" { |
| 398 | profile, err := Profile(in.Action) |
| 399 | if err != nil { |
| 400 | return Policy{}, err |
| 401 | } |
| 402 | readOnly = profile.ReadOnly |
| 403 | } |
| 404 | m.OuterMounts = []Mount{{Source: "/usr", Target: "/usr", ReadOnly: true}, {Source: in.Workspace, Target: "/workspace", ReadOnly: readOnly}, {Source: b.Home, Target: "/home/runner"}, {Source: in.Scratch, Target: "/tmp"}} |
| 405 | m.GeneratedMounts = generatedMounts(b) |
| 406 | if len(in.Catalog) > 0 { |
| 407 | if b.Provider != "codex" || in.Action == "" || !json.Valid(in.Catalog) { |
| 408 | return Policy{}, ErrPolicy |
| 409 | } |
| 410 | m.GeneratedMounts = append(m.GeneratedMounts, Mount{Source: filepath.Join(b.provenance.config, "equipo-coordinator-models.json"), Target: CoordinatorCatalogPath, ReadOnly: true}) |
| 411 | } |
| 412 | if CoordinatorAction(in.Action) { |
| 413 | m.OuterMounts = append(m.OuterMounts[:1], m.OuterMounts[2:]...) |
| 414 | } |
| 415 | m.NamespaceArgs = NamespaceArguments() |
| 416 | raw, manifestHash, e := hashJSON(m) |
| 417 | if e != nil { |
| 418 | return Policy{}, e |
| 419 | } |
| 420 | _, instructionHash, _ := hashJSON(instructions) |
| 421 | // Only validated attempt directories become roles. Account paths, protected |
| 422 | // paths, argv, binaries and every other runtime input remain exact. |
| 423 | m = policyTemplate(m) |
| 424 | _, policyHash, e := hashJSON(m) |
| 425 | if e != nil { |
| 426 | return Policy{}, e |
| 427 | } |
| 428 | dir, e := b.provenance.configDir() |
| 429 | if e != nil { |
| 430 | return Policy{}, e |
| 431 | } |
| 432 | defer dir.Close() |
| 433 | if atomicPrivate(dir, "equipo-settings.json", settings) != nil || atomicPrivate(dir, "equipo-mcp.json", mcp) != nil { |
| 434 | return Policy{}, ErrPolicy |
| 435 | } |
| 436 | mounts := append(append([]Mount(nil), in.RuntimeFiles...), in.InstructionFiles...) |
| 437 | mounts = append(mounts, generatedMounts(b)...) |
| 438 | if len(in.Catalog) > 0 { |
| 439 | mounts = append(mounts, Mount{Source: filepath.Join(b.provenance.config, "equipo-coordinator-models.json"), Target: CoordinatorCatalogPath, ReadOnly: true}) |
| 440 | } |
| 441 | if len(in.Catalog) > 0 && atomicPrivate(dir, "equipo-coordinator-models.json", in.Catalog) != nil { |
| 442 | return Policy{}, ErrPolicy |
| 443 | } |
| 444 | p := Policy{Hash: policyHash, ManifestHash: manifestHash, InstructionHash: instructionHash, Manifest: raw, Mounts: mounts, Env: env, Settings: settings, MCP: mcp, ThreadPolicy: thread, TurnPolicy: turn} |
| 445 | b.provenance.mu.Lock() |
| 446 | b.provenance.policy = &Policy{Manifest: bytes.Clone(raw), ManifestHash: manifestHash} |
| 447 | b.provenance.mu.Unlock() |
| 448 | return p, nil |
| 449 | } |
| 450 | |
| 451 | // ValidateSources verifies the current generated, managed and runtime files. |
| 452 | func (p Policy) ValidateSources(b Binding) error { |
| 453 | var m effectiveManifest |
| 454 | if p.ManifestHash == "" || digest(p.Manifest) != p.ManifestHash || json.Unmarshal(p.Manifest, &m) != nil { |
| 455 | return ErrPolicy |
| 456 | } |
| 457 | expected := append(append([]fileDigest(nil), m.Files...), m.Instructions...) |
| 458 | mounts := make([]Mount, 0, len(expected)) |
| 459 | for _, f := range expected { |
| 460 | mounts = append(mounts, f.Mount) |
| 461 | } |
| 462 | current, e := hashFiles(mounts, b) |
| 463 | if e != nil || !reflect.DeepEqual(current, expected) { |
| 464 | return ErrPolicy |
| 465 | } |
| 466 | if b.provenance == nil || m.ConfigHome != b.provenance.config { |
| 467 | return ErrPolicy |
| 468 | } |
| 469 | dir, e := b.provenance.configDir() |
| 470 | if e != nil { |
| 471 | return e |
| 472 | } |
| 473 | defer dir.Close() |
| 474 | generated := map[string][]byte{"equipo-settings.json": m.Settings, "equipo-mcp.json": m.MCP} |
| 475 | if len(m.Catalog) > 0 { |
| 476 | generated["equipo-coordinator-models.json"] = m.Catalog |
| 477 | } |
| 478 | for name, want := range generated { |
| 479 | raw, e := readPrivate(dir, name) |
| 480 | if e != nil || !bytes.Equal(raw, want) { |
| 481 | return ErrPolicy |
| 482 | } |
| 483 | } |
| 484 | return nil |
| 485 | } |
| 486 | |
| 487 | type ConfigReadback struct { |
| 488 | Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage |
| 489 | Layers []string |
| 490 | HooksDisabled, PluginsDisabled, RemoteControl bool |
| 491 | } |
| 492 | |
| 493 | func (p Policy) ValidateReadback(r ConfigReadback) error { |
| 494 | var m effectiveManifest |
| 495 | if json.Unmarshal(p.Manifest, &m) != nil { |
| 496 | return ErrPolicy |
| 497 | } |
| 498 | layers := []string{"equipo"} |
| 499 | for _, file := range m.Files { |
| 500 | if strings.HasPrefix(file.Mount.Target, "/etc/claude-code/") || strings.HasPrefix(file.Mount.Target, "/etc/codex/") { |
| 501 | layers = append(layers, "managed:"+file.Mount.Target) |
| 502 | } |
| 503 | } |
| 504 | sort.Strings(layers) |
| 505 | actual := append([]string(nil), r.Layers...) |
| 506 | sort.Strings(actual) |
| 507 | if r.RemoteControl || !r.HooksDisabled || !r.PluginsDisabled || !reflect.DeepEqual(actual, layers) { |
| 508 | return ErrPolicy |
| 509 | } |
| 510 | for _, pair := range [][2]json.RawMessage{{p.Settings, r.Settings}, {p.MCP, r.MCP}, {p.ThreadPolicy, r.ThreadPolicy}, {p.TurnPolicy, r.TurnPolicy}} { |
| 511 | a, e := canonical(pair[0]) |
| 512 | if e != nil { |
| 513 | return e |
| 514 | } |
| 515 | b, e := canonical(pair[1]) |
| 516 | if e != nil || !bytes.Equal(a, b) { |
| 517 | return ErrPolicy |
| 518 | } |
| 519 | } |
| 520 | return nil |
| 521 | } |
| 522 | |
| 523 | // AttestLaunch binds a concrete attempt to the already built policy. Containment |
| 524 | // persists this hash separately from the reusable policy certificate hash. |
| 525 | func AttestLaunch(l Launch, argv []string) (string, error) { |
| 526 | if l.Policy.IsPi() { |
| 527 | return attestPi(l, argv) |
| 528 | } |
| 529 | if l.Policy.IsOpenCode() { |
| 530 | return attestOpenCode(l, argv) |
| 531 | } |
| 532 | if l.Policy.IsCheck() { |
| 533 | return attestCheck(l, argv) |
| 534 | } |
| 535 | if l.Policy.IsSignIn() { |
| 536 | return attestSignIn(l, argv) |
| 537 | } |
| 538 | p := l.Policy |
| 539 | if p.ManifestHash == "" { |
| 540 | // Legacy check jobs have no direct-provider manifest during the cutover. |
| 541 | if l.Selection.Provider != "" || l.Binding.DedicatedHome { |
| 542 | return "", ErrPolicy |
| 543 | } |
| 544 | _, h, e := hashJSON(struct { |
| 545 | Launch Launch |
| 546 | Argv []string |
| 547 | }{l, argv}) |
| 548 | return h, e |
| 549 | } |
| 550 | if !l.Binding.VerifiedDedicatedHome() || l.Binding.provenance.validateLaunch() != nil { |
| 551 | return "", ErrIdentity |
| 552 | } |
| 553 | if digest(p.Manifest) != p.ManifestHash { |
| 554 | return "", ErrPolicy |
| 555 | } |
| 556 | var m effectiveManifest |
| 557 | if json.Unmarshal(p.Manifest, &m) != nil { |
| 558 | return "", ErrPolicy |
| 559 | } |
| 560 | if l.AttemptKey == "" || m.Workspace != l.Workspace || m.RuntimeHome != l.Binding.Home || m.CredentialHome != l.Binding.CredentialHome || m.BindingID != l.Binding.ID || m.Identity != l.Binding.Expected || m.Provider != l.Selection.Provider || m.AccountID != l.Selection.AccountID || !reflect.DeepEqual(m.Argv, argv) { |
| 561 | return "", ErrIdentity |
| 562 | } |
| 563 | for _, pair := range [][2]json.RawMessage{{m.Settings, p.Settings}, {m.MCP, p.MCP}, {m.ThreadPolicy, p.ThreadPolicy}, {m.TurnPolicy, p.TurnPolicy}} { |
| 564 | if !bytes.Equal(pair[0], pair[1]) { |
| 565 | return "", ErrPolicy |
| 566 | } |
| 567 | } |
| 568 | mounts := []Mount{} |
| 569 | for _, f := range append(append([]fileDigest(nil), m.Files...), m.Instructions...) { |
| 570 | mounts = append(mounts, f.Mount) |
| 571 | } |
| 572 | expectedMounts := append(mounts, generatedMounts(l.Binding)...) |
| 573 | if len(m.Catalog) > 0 { |
| 574 | expectedMounts = append(expectedMounts, Mount{Source: filepath.Join(l.Binding.provenance.config, "equipo-coordinator-models.json"), Target: CoordinatorCatalogPath, ReadOnly: true}) |
| 575 | } |
| 576 | if !reflect.DeepEqual(expectedMounts, p.Mounts) { |
| 577 | return "", ErrPolicy |
| 578 | } |
| 579 | expectedEnv := map[string]string{} |
| 580 | for k, v := range m.Env { |
| 581 | switch k { |
| 582 | case "PATH", "HOME", "TMPDIR", "HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy": |
| 583 | default: |
| 584 | expectedEnv[k] = v |
| 585 | } |
| 586 | } |
| 587 | if p.GoToolchain() { |
| 588 | for k, v := range gotoolchain.Environment(l.Binding.Provider) { |
| 589 | if m.Env[k] != v { |
| 590 | return "", ErrPolicy |
| 591 | } |
| 592 | expectedEnv[k] = v |
| 593 | } |
| 594 | } |
| 595 | if !reflect.DeepEqual(expectedEnv, p.Env) { |
| 596 | return "", ErrPolicy |
| 597 | } |
| 598 | if e := p.ValidateSources(l.Binding); e != nil { |
| 599 | return "", e |
| 600 | } |
| 601 | _, instructionHash, _ := hashJSON(m.Instructions) |
| 602 | if instructionHash != p.InstructionHash { |
| 603 | return "", ErrPolicy |
| 604 | } |
| 605 | m = policyTemplate(m) |
| 606 | _, policyHash, _ := hashJSON(m) |
| 607 | if policyHash != p.Hash { |
| 608 | return "", ErrPolicy |
| 609 | } |
| 610 | _, hash, e := hashJSON(struct { |
| 611 | ManifestHash, AttemptKey, ResumeSessionID string |
| 612 | Selection Selection |
| 613 | }{p.ManifestHash, l.AttemptKey, l.ResumeSessionID, l.Selection}) |
| 614 | return hash, e |
| 615 | } |
| 616 | func (p Policy) ValidateNetwork(name string, hosts []string) error { |
| 617 | if p.ManifestHash == "" { |
| 618 | return nil |
| 619 | } |
| 620 | var m effectiveManifest |
| 621 | if json.Unmarshal(p.Manifest, &m) != nil { |
| 622 | return ErrPolicy |
| 623 | } |
| 624 | actual := append([]string(nil), hosts...) |
| 625 | sort.Strings(actual) |
| 626 | if m.Provider != name || !reflect.DeepEqual(actual, m.EgressHosts) { |
| 627 | return ErrPolicy |
| 628 | } |
| 629 | return nil |
| 630 | } |
| 631 | func generatedMounts(b Binding) []Mount { |
| 632 | return []Mount{{Source: filepath.Join(b.provenance.config, "equipo-settings.json"), Target: SettingsPath, ReadOnly: true}, {Source: filepath.Join(b.provenance.config, "equipo-mcp.json"), Target: MCPPath, ReadOnly: true}} |
| 633 | } |
| 634 | |
| 635 | // ValidateRuntimeBinaries requires the host's actual launcher and bubblewrap |
| 636 | // binaries to be among the files certified by the adapter's policy inputs. |
| 637 | func (p Policy) ValidateRuntimeBinaries(paths ...string) error { |
| 638 | if p.ManifestHash == "" { |
| 639 | return nil |
| 640 | } |
| 641 | var m effectiveManifest |
| 642 | if json.Unmarshal(p.Manifest, &m) != nil { |
| 643 | return ErrPolicy |
| 644 | } |
| 645 | for _, path := range paths { |
| 646 | found := false |
| 647 | for _, f := range m.Files { |
| 648 | if f.Mount.Source == path { |
| 649 | found = true |
| 650 | } |
| 651 | } |
| 652 | if !found { |
| 653 | return ErrPolicy |
| 654 | } |
| 655 | } |
| 656 | return nil |
| 657 | } |
| 658 | func (p Policy) ValidateFileDigest(path, hash string) error { |
| 659 | if p.ManifestHash == "" { |
| 660 | return nil |
| 661 | } |
| 662 | var m effectiveManifest |
| 663 | if json.Unmarshal(p.Manifest, &m) != nil { |
| 664 | return ErrPolicy |
| 665 | } |
| 666 | for _, f := range append(m.Files, m.Instructions...) { |
| 667 | if f.Mount.Source == path && f.SHA256 == hash { |
| 668 | return nil |
| 669 | } |
| 670 | } |
| 671 | if len(m.Catalog) > 0 && path == filepath.Join(m.ConfigHome, "equipo-coordinator-models.json") && digest(m.Catalog) == hash { |
| 672 | return nil |
| 673 | } |
| 674 | if path == filepath.Join(m.ConfigHome, "equipo-settings.json") && digest(m.Settings) == hash { |
| 675 | return nil |
| 676 | } |
| 677 | if path == filepath.Join(m.ConfigHome, "equipo-mcp.json") && digest(m.MCP) == hash { |
| 678 | return nil |
| 679 | } |
| 680 | return ErrPolicy |
| 681 | } |
| 682 | |
| 683 | // NamespaceArguments is shared with containment so changes to isolation flags |
| 684 | // also change the reusable policy hash. |
| 685 | func NamespaceArguments() []string { |
| 686 | return []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"} |
| 687 | } |
| 688 | func policyTemplate(m effectiveManifest) effectiveManifest { |
| 689 | // Session identity is journaled in the concrete manifest. Both invocation |
| 690 | // modes use the same certified thread policy and sandbox configuration. |
| 691 | if m.Provider == "claude" && len(m.Argv) >= 3 { |
| 692 | n := len(m.Argv) |
| 693 | flag, id := m.Argv[n-2], m.Argv[n-1] |
| 694 | if (flag == "--session-id" || flag == "--resume") && len(id) == 36 && id[8] == '-' && id[13] == '-' && id[18] == '-' && id[23] == '-' { |
| 695 | if raw, e := hex.DecodeString(strings.ReplaceAll(id, "-", "")); e == nil && len(raw) == 16 { |
| 696 | m.Argv = append([]string(nil), m.Argv[:n-2]...) |
| 697 | } |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | // The runtime login directory is generated for each lease. Bind its exact |
| 702 | // path in ManifestHash, and its role in the reusable certificate, including |
| 703 | // occurrences in adapter settings and command-line permission profiles. |
| 704 | raw, _ := json.Marshal(m) |
| 705 | raw = []byte(templatePath(string(raw), m.RuntimeHome, "$RUNTIME_HOME")) |
| 706 | var normalized any |
| 707 | decoder := json.NewDecoder(bytes.NewReader(raw)) |
| 708 | decoder.UseNumber() |
| 709 | if decoder.Decode(&normalized) != nil { |
| 710 | panic("invalid policy template") |
| 711 | } |
| 712 | raw, _ = json.Marshal(normalized) |
| 713 | m = effectiveManifest{} |
| 714 | if json.Unmarshal(raw, &m) != nil { |
| 715 | panic("invalid normalized policy") |
| 716 | } |
| 717 | sort.Strings(m.DeniedPaths) |
| 718 | m.OuterMounts = append([]Mount(nil), m.OuterMounts...) |
| 719 | m.GeneratedMounts = append([]Mount(nil), m.GeneratedMounts...) |
| 720 | for i := range m.OuterMounts { |
| 721 | switch m.OuterMounts[i].Target { |
| 722 | case "/workspace": |
| 723 | m.OuterMounts[i].Source = "$WORKSPACE" |
| 724 | case "/home/runner": |
| 725 | m.OuterMounts[i].Source = "$RUNTIME_HOME" |
| 726 | case "/tmp": |
| 727 | m.OuterMounts[i].Source = "$SCRATCH" |
| 728 | } |
| 729 | } |
| 730 | for i := range m.GeneratedMounts { |
| 731 | m.GeneratedMounts[i].Source = filepath.Join("$CONFIG_HOME", filepath.Base(m.GeneratedMounts[i].Source)) |
| 732 | } |
| 733 | m.Workspace = "$WORKSPACE" |
| 734 | m.Scratch = "$SCRATCH" |
| 735 | m.RuntimeHome = "$RUNTIME_HOME" |
| 736 | m.ConfigHome = "$CONFIG_HOME" |
| 737 | m.Instructions = nil |
| 738 | return m |
| 739 | } |
| 740 | |
| 741 | func credentialSource(path string, b Binding) bool { |
| 742 | switch filepath.Base(path) { |
| 743 | case "auth.json", ".credentials.json", IdentityFile: |
| 744 | return true |
| 745 | } |
| 746 | if b.provenance == nil { |
| 747 | return true |
| 748 | } |
| 749 | rules := b.provenance.rules |
| 750 | if rules.RefusesPath(path) || refusedMountAlias(path, rules) { |
| 751 | return true |
| 752 | } |
| 753 | for parent := filepath.Dir(path); parent != "/"; parent = filepath.Dir(parent) { |
| 754 | info, e := os.Stat(parent) |
| 755 | if e != nil || rules.refusedInode(info) { |
| 756 | return true |
| 757 | } |
| 758 | } |
| 759 | return false |
| 760 | } |
| 761 | |
| 762 | func templatePath(s, path, role string) string { |
| 763 | if path == "" { |
| 764 | return s |
| 765 | } |
| 766 | var out strings.Builder |
| 767 | for { |
| 768 | i := strings.Index(s, path) |
| 769 | if i < 0 { |
| 770 | out.WriteString(s) |
| 771 | break |
| 772 | } |
| 773 | end := i + len(path) |
| 774 | boundary := end == len(s) || strings.ContainsRune("/\\\")", rune(s[end])) |
| 775 | out.WriteString(s[:i]) |
| 776 | if boundary { |
| 777 | out.WriteString(role) |
| 778 | } else { |
| 779 | out.WriteString(path) |
| 780 | } |
| 781 | s = s[end:] |
| 782 | } |
| 783 | return out.String() |
| 784 | } |
| 785 | |
| 786 | func (p Policy) ReadOnlyWorkspace() bool { |
| 787 | var m effectiveManifest |
| 788 | if json.Unmarshal(p.Manifest, &m) != nil { |
| 789 | return true |
| 790 | } |
| 791 | if m.Action == "" { |
| 792 | return false |
| 793 | } |
| 794 | profile, err := Profile(m.Action) |
| 795 | return err != nil || profile.ReadOnly |
| 796 | } |
| 797 | |
| 798 | // Converse reports whether the policy is the thin coordinator's or the |
| 799 | // Assistant's, which share a launch shape: its |
| 800 | // workspace is its desk, mounted read-only. |
| 801 | func (p Policy) Converse() bool { |
| 802 | var m effectiveManifest |
| 803 | return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && (m.Action == "converse" || m.Action == "assist") |
| 804 | } |
| 805 | |
| 806 | func (p Policy) Coordinator() bool { |
| 807 | var m effectiveManifest |
| 808 | return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && CoordinatorAction(m.Action) |
| 809 | } |
| 810 | |
| 811 | // Research reports whether the policy is a Research step's: containment |
| 812 | // gives it a minimal /etc and no host /etc overlay. |
| 813 | func (p Policy) Research() bool { |
| 814 | var m effectiveManifest |
| 815 | return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && ResearchAction(m.Action) |
| 816 | } |
| 817 | |
| 818 | // Glance reports whether the policy is a glance's: no tools, the |
| 819 | // coordinator's surface on Codex. |
| 820 | func (p Policy) Glance() bool { |
| 821 | var m effectiveManifest |
| 822 | return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && m.Action == GlanceAction |
| 823 | } |
| 824 | |
| 825 | // ResearchReader reports whether the policy may have a task's kept |
| 826 | // research images bound read-only at /research (Engineering, Review). |
| 827 | func (p Policy) ResearchReader() bool { |
| 828 | var m effectiveManifest |
| 829 | return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && ResearchReaderAction(m.Action) |
| 830 | } |
| 831 | |
| 832 | // RenderReader reports whether the policy may have its step's captures |
| 833 | // bound read-only at /render (the Design step only). |
| 834 | func (p Policy) RenderReader() bool { |
| 835 | var m effectiveManifest |
| 836 | return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && RenderReaderAction(m.Action) |
| 837 | } |
| 838 | |
| 839 | // validAuthHost accepts one lower-case DNS name: no scheme, port, path, |
| 840 | // wildcard or user. |
| 841 | func validAuthHost(host string) bool { |
| 842 | if !strings.Contains(host, ".") || strings.ContainsAny(host, "/:@* \t\n") || host != strings.ToLower(host) { |
| 843 | return false |
| 844 | } |
| 845 | for _, label := range strings.Split(host, ".") { |
| 846 | if label == "" || strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") { |
| 847 | return false |
| 848 | } |
| 849 | for _, r := range label { |
| 850 | if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') { |
| 851 | return false |
| 852 | } |
| 853 | } |
| 854 | } |
| 855 | return true |
| 856 | } |
| 857 | |