package provider import ( "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "io" "net/netip" "os" "path/filepath" "reflect" "slices" "sort" "strings" "amadan.net/oficina/equipo/internal/runner/provider/gotoolchain" "golang.org/x/sys/unix" ) const PolicyVersion = "direct-v1" const SettingsPath = "/config/equipo-settings.json" const CoordinatorCatalogPath = "/config/equipo-coordinator-models.json" const MCPPath = "/config/equipo-mcp.json" type PolicyInputs struct { NativeTools []string `json:",omitempty"` Action string AuthHost string RuntimeFiles []Mount DeniedPaths, EgressHosts []string ProviderVersion, LauncherVersion, BwrapVersion string Catalog json.RawMessage `json:",omitempty"` Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage Tools []string // Adapters supply the exact argv and any permitted nonsecret environment. Argv []string Env map[string]string Workspace, Scratch string InstructionFiles []Mount } type fileDigest struct { Mount Mount SHA256 string } type effectiveManifest struct { NativeTools []string `json:",omitempty"` Action string `json:",omitempty"` AuthHost string OuterMounts, GeneratedMounts []Mount NamespaceArgs []string Version string BindingID, Provider, AccountID, CredentialHome string Identity Identity ProviderVersion, LauncherVersion, BwrapVersion string Argv []string Env map[string]string Files []fileDigest DeniedPaths, EgressHosts, Tools []string Catalog json.RawMessage `json:",omitempty"` Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage Workspace, Scratch, RuntimeHome, ConfigHome string Instructions []fileDigest HooksDisabled, PluginsDisabled, TurnOverridesOmitted bool MaskedDirectories []string Proxy string // A harness that is not the provider's own CLI (Pi): its name, the // variable its key is delivered in, and its pinned package trees. // Empty for every other policy, so their hashes are unchanged. Harness string `json:",omitempty"` KeyEnv string `json:",omitempty"` Trees []treePin `json:",omitempty"` } // treePin is a package tree mounted whole, by its committed digest. type treePin struct { Mount Mount SHA256 string } func digest(raw []byte) string { s := sha256.Sum256(raw); return hex.EncodeToString(s[:]) } func hashJSON(value any) ([]byte, string, error) { raw, e := json.Marshal(value) return raw, digest(raw), e } // Canonical JSON rejects duplicate keys so the harness and attestation cannot // interpret the same configuration differently. Numbers retain their precision. func canonical(raw json.RawMessage) (json.RawMessage, error) { if len(raw) == 0 { raw = json.RawMessage(`{}`) } d := json.NewDecoder(bytes.NewReader(raw)) d.UseNumber() value, e := jsonValue(d) if e != nil { return nil, ErrPolicy } if _, e = d.Token(); e != io.EOF { return nil, ErrPolicy } if _, ok := value.(map[string]any); !ok { return nil, ErrPolicy } out, e := json.Marshal(value) return out, e } func jsonValue(d *json.Decoder) (any, error) { token, e := d.Token() if e != nil { return nil, e } delim, ok := token.(json.Delim) if !ok { return token, nil } switch delim { case '{': m := map[string]any{} for d.More() { key, e := d.Token() if e != nil { return nil, e } k, ok := key.(string) if !ok { return nil, ErrPolicy } if _, ok = m[k]; ok { return nil, ErrPolicy } v, e := jsonValue(d) if e != nil { return nil, e } m[k] = v } _, e = d.Token() return m, e case '[': a := []any{} for d.More() { v, e := jsonValue(d) if e != nil { return nil, e } a = append(a, v) } _, e = d.Token() return a, e } return nil, ErrPolicy } func validTurnPolicy(raw json.RawMessage) bool { var value map[string]any if json.Unmarshal(raw, &value) != nil { return false } // Only non-authority turn parameters are allowed. Adding an SDK field requires // a deliberate policy revision; unknown fields cannot become hidden overrides. for key := range value { switch key { case "effort", "summary": default: return false } } return true } func nonsecretJSON(raw json.RawMessage) bool { var value any if json.Unmarshal(raw, &value) != nil { return false } var safe func(any) bool safe = func(v any) bool { switch x := v.(type) { case map[string]any: for k, v := range x { lower := strings.ToLower(k) if k == "token_budget" && v == false { continue } if strings.Contains(lower, "token") || strings.Contains(lower, "secret") || strings.Contains(lower, "password") || strings.Contains(lower, "api_key") || strings.Contains(lower, "apikey") || lower == "authorization" { return false } if !safe(v) { return false } } case []any: for _, v := range x { if !safe(v) { return false } } } return true } return safe(value) } func hashFiles(mounts []Mount, b Binding) ([]fileDigest, error) { out := make([]fileDigest, 0, len(mounts)) seen := map[string]bool{} for _, m := range mounts { if credentialSource(m.Source, b) { return nil, ErrPolicy } if !m.ReadOnly || !cleanPath(m.Source) || !cleanPath(m.Target) || seen[m.Target] || withinPath(m.Source, b.CredentialHome) || withinPath(m.Source, b.Home) { return nil, ErrPolicy } if !(strings.HasPrefix(m.Target, "/opt/") || strings.HasPrefix(m.Target, "/config/") || strings.HasPrefix(m.Target, "/etc/claude-code/") || strings.HasPrefix(m.Target, "/etc/codex/")) { return nil, ErrPolicy } if gotoolchain.Target(m.Target) { f, e := goTree(m, b) if e != nil { return nil, e } out = append(out, f) seen[m.Target] = true continue } fd, e := openNoLinks(m.Source, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK) if e != nil { return nil, ErrPolicy } f := os.NewFile(uintptr(fd), m.Source) var stat unix.Stat_t if unix.Fstat(fd, &stat) != nil || stat.Nlink != 1 { f.Close() return nil, ErrPolicy } info, e := f.Stat() if e != nil || !info.Mode().IsRegular() { f.Close() return nil, ErrPolicy } h := sha256.New() _, e = io.Copy(h, f) f.Close() if e != nil { return nil, ErrPolicy } out = append(out, fileDigest{Mount: m, SHA256: hex.EncodeToString(h.Sum(nil))}) seen[m.Target] = true } return out, nil } func BuildPolicy(b Binding, in PolicyInputs) (Policy, error) { var native []string // A Research step has no native tools either: only what the provider // registers whenever MCP is configured, pinned as for the coordinator. if CoordinatorAction(in.Action) || ResearchAction(in.Action) || in.Action == GlanceAction { native = CoordinatorNativeTools(b.Provider) } if !slices.Equal(in.NativeTools, native) { return Policy{}, ErrPolicy } if !b.VerifiedDedicatedHome() { return Policy{}, ErrIdentity } if in.ProviderVersion == "" || in.LauncherVersion == "" || in.BwrapVersion == "" || len(in.RuntimeFiles) == 0 || len(in.Argv) == 0 || !cleanPath(in.Argv[0]) || len(in.EgressHosts) == 0 { return Policy{}, ErrPolicy } for _, path := range []string{in.Workspace, in.Scratch} { f, e := pinDirectory(path) if e != nil { return Policy{}, ErrPolicy } f.Close() for _, protected := range append([]string{b.Home, b.CredentialHome, b.RuntimeRoot}, in.DeniedPaths...) { if withinPath(path, protected) || withinPath(protected, path) { return Policy{}, ErrPolicy } } } if withinPath(in.Workspace, in.Scratch) || withinPath(in.Scratch, in.Workspace) { return Policy{}, ErrPolicy } settings, e := canonical(in.Settings) if e != nil { return Policy{}, e } mcp, e := canonical(in.MCP) if e != nil { return Policy{}, e } thread, e := canonical(in.ThreadPolicy) if e != nil { return Policy{}, e } turn, e := canonical(in.TurnPolicy) if e != nil || !validTurnPolicy(turn) { return Policy{}, ErrPolicy } for _, raw := range []json.RawMessage{settings, mcp, thread, turn} { if !nonsecretJSON(raw) { return Policy{}, ErrPolicy } } env := map[string]string{"LANG": "C.UTF-8", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"} if b.Provider == "codex" { env["CODEX_HOME"] = "/home/runner" } else { env["CLAUDE_CONFIG_DIR"] = "/home/runner" env["CLAUDE_SECURESTORAGE_CONFIG_DIR"] = "/home/runner" env["CLAUDE_TMPDIR"] = "/tmp" env["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"] = "1" env["DISABLE_AUTOUPDATER"] = "1" } for k, v := range in.Env { if (k != "LANG" && k != "LC_ALL" && k != "TERM") || strings.ContainsRune(v, 0) { return Policy{}, ErrPolicy } env[k] = v } for _, file := range append(append([]Mount(nil), in.RuntimeFiles...), in.InstructionFiles...) { if withinPath(file.Source, in.Workspace) || withinPath(file.Source, in.Scratch) { return Policy{}, ErrPolicy } } for _, file := range in.RuntimeFiles { if gotoolchain.Target(file.Target) { if in.Action != "implement" { return Policy{}, ErrPolicy } for _, protected := range append([]string{b.Home, b.CredentialHome, b.RuntimeRoot, in.Workspace, in.Scratch}, in.DeniedPaths...) { if withinPath(file.Source, protected) || withinPath(protected, file.Source) { return Policy{}, ErrPolicy } } for k, v := range gotoolchain.Environment(b.Provider) { env[k] = v } } } files, e := hashFiles(in.RuntimeFiles, b) if e != nil { return Policy{}, e } instructions, e := hashFiles(in.InstructionFiles, b) if e != nil { return Policy{}, e } denied := append([]string(nil), in.DeniedPaths...) denied = append(denied, b.CredentialHome, "/home/runner") sort.Strings(denied) for _, path := range denied { if !cleanPath(path) { return Policy{}, ErrPolicy } } binaryPresent := false for _, file := range files { if file.Mount.Target == in.Argv[0] { binaryPresent = true } } if !binaryPresent { return Policy{}, ErrPolicy } if in.AuthHost != "" && (!validAuthHost(in.AuthHost) || !slices.Contains(in.EgressHosts, in.AuthHost)) { return Policy{}, ErrPolicy } hosts := append([]string(nil), in.EgressHosts...) sort.Strings(hosts) for i, h := range hosts { if _, e := netip.ParseAddr(h); e == nil { return Policy{}, ErrPolicy } if h == "" || strings.ContainsAny(h, "/:*@ \t\n") || h != strings.ToLower(h) || (i > 0 && h == hosts[i-1]) { return Policy{}, ErrPolicy } } tools := append([]string(nil), in.Tools...) for i, v := range tools { if v == "" { return Policy{}, ErrPolicy } for _, prior := range tools[:i] { if prior == v { return Policy{}, ErrPolicy } } } fullEnv := map[string]string{"PATH": "/usr/bin:/bin:/opt", "HOME": "/home/runner", "TMPDIR": "/tmp"} for k, v := range env { fullEnv[k] = v } for _, k := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"} { fullEnv[k] = "http://127.0.0.1:18080" } 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"} readOnly := false if in.Action != "" { profile, err := Profile(in.Action) if err != nil { return Policy{}, err } readOnly = profile.ReadOnly } 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"}} m.GeneratedMounts = generatedMounts(b) if len(in.Catalog) > 0 { if b.Provider != "codex" || in.Action == "" || !json.Valid(in.Catalog) { return Policy{}, ErrPolicy } m.GeneratedMounts = append(m.GeneratedMounts, Mount{Source: filepath.Join(b.provenance.config, "equipo-coordinator-models.json"), Target: CoordinatorCatalogPath, ReadOnly: true}) } if CoordinatorAction(in.Action) { m.OuterMounts = append(m.OuterMounts[:1], m.OuterMounts[2:]...) } m.NamespaceArgs = NamespaceArguments() raw, manifestHash, e := hashJSON(m) if e != nil { return Policy{}, e } _, instructionHash, _ := hashJSON(instructions) // Only validated attempt directories become roles. Account paths, protected // paths, argv, binaries and every other runtime input remain exact. m = policyTemplate(m) _, policyHash, e := hashJSON(m) if e != nil { return Policy{}, e } dir, e := b.provenance.configDir() if e != nil { return Policy{}, e } defer dir.Close() if atomicPrivate(dir, "equipo-settings.json", settings) != nil || atomicPrivate(dir, "equipo-mcp.json", mcp) != nil { return Policy{}, ErrPolicy } mounts := append(append([]Mount(nil), in.RuntimeFiles...), in.InstructionFiles...) mounts = append(mounts, generatedMounts(b)...) if len(in.Catalog) > 0 { mounts = append(mounts, Mount{Source: filepath.Join(b.provenance.config, "equipo-coordinator-models.json"), Target: CoordinatorCatalogPath, ReadOnly: true}) } if len(in.Catalog) > 0 && atomicPrivate(dir, "equipo-coordinator-models.json", in.Catalog) != nil { return Policy{}, ErrPolicy } p := Policy{Hash: policyHash, ManifestHash: manifestHash, InstructionHash: instructionHash, Manifest: raw, Mounts: mounts, Env: env, Settings: settings, MCP: mcp, ThreadPolicy: thread, TurnPolicy: turn} b.provenance.mu.Lock() b.provenance.policy = &Policy{Manifest: bytes.Clone(raw), ManifestHash: manifestHash} b.provenance.mu.Unlock() return p, nil } // ValidateSources verifies the current generated, managed and runtime files. func (p Policy) ValidateSources(b Binding) error { var m effectiveManifest if p.ManifestHash == "" || digest(p.Manifest) != p.ManifestHash || json.Unmarshal(p.Manifest, &m) != nil { return ErrPolicy } expected := append(append([]fileDigest(nil), m.Files...), m.Instructions...) mounts := make([]Mount, 0, len(expected)) for _, f := range expected { mounts = append(mounts, f.Mount) } current, e := hashFiles(mounts, b) if e != nil || !reflect.DeepEqual(current, expected) { return ErrPolicy } if b.provenance == nil || m.ConfigHome != b.provenance.config { return ErrPolicy } dir, e := b.provenance.configDir() if e != nil { return e } defer dir.Close() generated := map[string][]byte{"equipo-settings.json": m.Settings, "equipo-mcp.json": m.MCP} if len(m.Catalog) > 0 { generated["equipo-coordinator-models.json"] = m.Catalog } for name, want := range generated { raw, e := readPrivate(dir, name) if e != nil || !bytes.Equal(raw, want) { return ErrPolicy } } return nil } type ConfigReadback struct { Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage Layers []string HooksDisabled, PluginsDisabled, RemoteControl bool } func (p Policy) ValidateReadback(r ConfigReadback) error { var m effectiveManifest if json.Unmarshal(p.Manifest, &m) != nil { return ErrPolicy } layers := []string{"equipo"} for _, file := range m.Files { if strings.HasPrefix(file.Mount.Target, "/etc/claude-code/") || strings.HasPrefix(file.Mount.Target, "/etc/codex/") { layers = append(layers, "managed:"+file.Mount.Target) } } sort.Strings(layers) actual := append([]string(nil), r.Layers...) sort.Strings(actual) if r.RemoteControl || !r.HooksDisabled || !r.PluginsDisabled || !reflect.DeepEqual(actual, layers) { return ErrPolicy } for _, pair := range [][2]json.RawMessage{{p.Settings, r.Settings}, {p.MCP, r.MCP}, {p.ThreadPolicy, r.ThreadPolicy}, {p.TurnPolicy, r.TurnPolicy}} { a, e := canonical(pair[0]) if e != nil { return e } b, e := canonical(pair[1]) if e != nil || !bytes.Equal(a, b) { return ErrPolicy } } return nil } // AttestLaunch binds a concrete attempt to the already built policy. Containment // persists this hash separately from the reusable policy certificate hash. func AttestLaunch(l Launch, argv []string) (string, error) { if l.Policy.IsPi() { return attestPi(l, argv) } if l.Policy.IsOpenCode() { return attestOpenCode(l, argv) } if l.Policy.IsCheck() { return attestCheck(l, argv) } if l.Policy.IsSignIn() { return attestSignIn(l, argv) } p := l.Policy if p.ManifestHash == "" { // Legacy check jobs have no direct-provider manifest during the cutover. if l.Selection.Provider != "" || l.Binding.DedicatedHome { return "", ErrPolicy } _, h, e := hashJSON(struct { Launch Launch Argv []string }{l, argv}) return h, e } if !l.Binding.VerifiedDedicatedHome() || l.Binding.provenance.validateLaunch() != nil { return "", ErrIdentity } if digest(p.Manifest) != p.ManifestHash { return "", ErrPolicy } var m effectiveManifest if json.Unmarshal(p.Manifest, &m) != nil { return "", ErrPolicy } 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) { return "", ErrIdentity } for _, pair := range [][2]json.RawMessage{{m.Settings, p.Settings}, {m.MCP, p.MCP}, {m.ThreadPolicy, p.ThreadPolicy}, {m.TurnPolicy, p.TurnPolicy}} { if !bytes.Equal(pair[0], pair[1]) { return "", ErrPolicy } } mounts := []Mount{} for _, f := range append(append([]fileDigest(nil), m.Files...), m.Instructions...) { mounts = append(mounts, f.Mount) } expectedMounts := append(mounts, generatedMounts(l.Binding)...) if len(m.Catalog) > 0 { expectedMounts = append(expectedMounts, Mount{Source: filepath.Join(l.Binding.provenance.config, "equipo-coordinator-models.json"), Target: CoordinatorCatalogPath, ReadOnly: true}) } if !reflect.DeepEqual(expectedMounts, p.Mounts) { return "", ErrPolicy } expectedEnv := map[string]string{} for k, v := range m.Env { switch k { case "PATH", "HOME", "TMPDIR", "HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy": default: expectedEnv[k] = v } } if p.GoToolchain() { for k, v := range gotoolchain.Environment(l.Binding.Provider) { if m.Env[k] != v { return "", ErrPolicy } expectedEnv[k] = v } } if !reflect.DeepEqual(expectedEnv, p.Env) { return "", ErrPolicy } if e := p.ValidateSources(l.Binding); e != nil { return "", e } _, instructionHash, _ := hashJSON(m.Instructions) if instructionHash != p.InstructionHash { return "", ErrPolicy } m = policyTemplate(m) _, policyHash, _ := hashJSON(m) if policyHash != p.Hash { return "", ErrPolicy } _, hash, e := hashJSON(struct { ManifestHash, AttemptKey, ResumeSessionID string Selection Selection }{p.ManifestHash, l.AttemptKey, l.ResumeSessionID, l.Selection}) return hash, e } func (p Policy) ValidateNetwork(name string, hosts []string) error { if p.ManifestHash == "" { return nil } var m effectiveManifest if json.Unmarshal(p.Manifest, &m) != nil { return ErrPolicy } actual := append([]string(nil), hosts...) sort.Strings(actual) if m.Provider != name || !reflect.DeepEqual(actual, m.EgressHosts) { return ErrPolicy } return nil } func generatedMounts(b Binding) []Mount { 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}} } // ValidateRuntimeBinaries requires the host's actual launcher and bubblewrap // binaries to be among the files certified by the adapter's policy inputs. func (p Policy) ValidateRuntimeBinaries(paths ...string) error { if p.ManifestHash == "" { return nil } var m effectiveManifest if json.Unmarshal(p.Manifest, &m) != nil { return ErrPolicy } for _, path := range paths { found := false for _, f := range m.Files { if f.Mount.Source == path { found = true } } if !found { return ErrPolicy } } return nil } func (p Policy) ValidateFileDigest(path, hash string) error { if p.ManifestHash == "" { return nil } var m effectiveManifest if json.Unmarshal(p.Manifest, &m) != nil { return ErrPolicy } for _, f := range append(m.Files, m.Instructions...) { if f.Mount.Source == path && f.SHA256 == hash { return nil } } if len(m.Catalog) > 0 && path == filepath.Join(m.ConfigHome, "equipo-coordinator-models.json") && digest(m.Catalog) == hash { return nil } if path == filepath.Join(m.ConfigHome, "equipo-settings.json") && digest(m.Settings) == hash { return nil } if path == filepath.Join(m.ConfigHome, "equipo-mcp.json") && digest(m.MCP) == hash { return nil } return ErrPolicy } // NamespaceArguments is shared with containment so changes to isolation flags // also change the reusable policy hash. func NamespaceArguments() []string { 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"} } func policyTemplate(m effectiveManifest) effectiveManifest { // Session identity is journaled in the concrete manifest. Both invocation // modes use the same certified thread policy and sandbox configuration. if m.Provider == "claude" && len(m.Argv) >= 3 { n := len(m.Argv) flag, id := m.Argv[n-2], m.Argv[n-1] if (flag == "--session-id" || flag == "--resume") && len(id) == 36 && id[8] == '-' && id[13] == '-' && id[18] == '-' && id[23] == '-' { if raw, e := hex.DecodeString(strings.ReplaceAll(id, "-", "")); e == nil && len(raw) == 16 { m.Argv = append([]string(nil), m.Argv[:n-2]...) } } } // The runtime login directory is generated for each lease. Bind its exact // path in ManifestHash, and its role in the reusable certificate, including // occurrences in adapter settings and command-line permission profiles. raw, _ := json.Marshal(m) raw = []byte(templatePath(string(raw), m.RuntimeHome, "$RUNTIME_HOME")) var normalized any decoder := json.NewDecoder(bytes.NewReader(raw)) decoder.UseNumber() if decoder.Decode(&normalized) != nil { panic("invalid policy template") } raw, _ = json.Marshal(normalized) m = effectiveManifest{} if json.Unmarshal(raw, &m) != nil { panic("invalid normalized policy") } sort.Strings(m.DeniedPaths) m.OuterMounts = append([]Mount(nil), m.OuterMounts...) m.GeneratedMounts = append([]Mount(nil), m.GeneratedMounts...) for i := range m.OuterMounts { switch m.OuterMounts[i].Target { case "/workspace": m.OuterMounts[i].Source = "$WORKSPACE" case "/home/runner": m.OuterMounts[i].Source = "$RUNTIME_HOME" case "/tmp": m.OuterMounts[i].Source = "$SCRATCH" } } for i := range m.GeneratedMounts { m.GeneratedMounts[i].Source = filepath.Join("$CONFIG_HOME", filepath.Base(m.GeneratedMounts[i].Source)) } m.Workspace = "$WORKSPACE" m.Scratch = "$SCRATCH" m.RuntimeHome = "$RUNTIME_HOME" m.ConfigHome = "$CONFIG_HOME" m.Instructions = nil return m } func credentialSource(path string, b Binding) bool { switch filepath.Base(path) { case "auth.json", ".credentials.json", IdentityFile: return true } if b.provenance == nil { return true } rules := b.provenance.rules if rules.RefusesPath(path) || refusedMountAlias(path, rules) { return true } for parent := filepath.Dir(path); parent != "/"; parent = filepath.Dir(parent) { info, e := os.Stat(parent) if e != nil || rules.refusedInode(info) { return true } } return false } func templatePath(s, path, role string) string { if path == "" { return s } var out strings.Builder for { i := strings.Index(s, path) if i < 0 { out.WriteString(s) break } end := i + len(path) boundary := end == len(s) || strings.ContainsRune("/\\\")", rune(s[end])) out.WriteString(s[:i]) if boundary { out.WriteString(role) } else { out.WriteString(path) } s = s[end:] } return out.String() } func (p Policy) ReadOnlyWorkspace() bool { var m effectiveManifest if json.Unmarshal(p.Manifest, &m) != nil { return true } if m.Action == "" { return false } profile, err := Profile(m.Action) return err != nil || profile.ReadOnly } // Converse reports whether the policy is the thin coordinator's or the // Assistant's, which share a launch shape: its // workspace is its desk, mounted read-only. func (p Policy) Converse() bool { var m effectiveManifest return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && (m.Action == "converse" || m.Action == "assist") } func (p Policy) Coordinator() bool { var m effectiveManifest return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && CoordinatorAction(m.Action) } // Research reports whether the policy is a Research step's: containment // gives it a minimal /etc and no host /etc overlay. func (p Policy) Research() bool { var m effectiveManifest return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && ResearchAction(m.Action) } // Glance reports whether the policy is a glance's: no tools, the // coordinator's surface on Codex. func (p Policy) Glance() bool { var m effectiveManifest return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && m.Action == GlanceAction } // ResearchReader reports whether the policy may have a task's kept // research images bound read-only at /research (Engineering, Review). func (p Policy) ResearchReader() bool { var m effectiveManifest return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && ResearchReaderAction(m.Action) } // RenderReader reports whether the policy may have its step's captures // bound read-only at /render (the Design step only). func (p Policy) RenderReader() bool { var m effectiveManifest return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && RenderReaderAction(m.Action) } // validAuthHost accepts one lower-case DNS name: no scheme, port, path, // wildcard or user. func validAuthHost(host string) bool { if !strings.Contains(host, ".") || strings.ContainsAny(host, "/:@* \t\n") || host != strings.ToLower(host) { return false } for _, label := range strings.Split(host, ".") { if label == "" || strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") { return false } for _, r := range label { if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') { return false } } } return true }