package thin import ( "context" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "path" "path/filepath" "slices" "strings" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/workspace" ) const gateContract = ".equipo/gates.json" const maxGateBytes = 4 << 20 var errBaseGate = errors.New("base gate evidence unavailable") type baseGateFile struct { body []byte mode os.FileMode } func standardGate(name string) bool { return name == gateContract || name == ".amadan/ci" || name == ".amadan/ci.d" || strings.HasPrefix(name, ".amadan/ci.d/") || slices.Contains([]string{"Makefile", "makefile", "GNUmakefile"}, path.Base(name)) || path.Ext(name) == ".mk" } func gateGit(ctx context.Context, git, gitDir string, limit int, args ...string) ([]byte, error) { cmd := exec.CommandContext(ctx, git, append([]string{"--git-dir=" + gitDir}, args...)...) env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } out, clipped, err := boundedOutput(cmd, limit) if err != nil || clipped { return nil, errBaseGate } return out, nil } func gateListing(ctx context.Context, git, gitDir, sha string) (map[string]string, error) { if !shaPattern.MatchString(sha) { return nil, errBaseGate } raw, err := gateGit(ctx, git, gitDir, 4<<20, "ls-tree", "-rtz", "--full-tree", sha) if err != nil { return nil, err } out := map[string]string{} for _, line := range strings.Split(strings.TrimSuffix(string(raw), "\x00"), "\x00") { if line == "" { continue } head, name, ok := strings.Cut(line, "\t") fields := strings.Fields(head) if !ok || len(fields) != 3 || !safeGatePath(name) { return nil, errBaseGate } if fields[0] != "040000" { out[name] = fields[0] } } return out, nil } func safeGatePath(name string) bool { return name != "" && name != "." && path.Clean(name) == name && !strings.HasPrefix(name, "/") && !strings.HasPrefix(name, "../") && !strings.ContainsAny(name, "\x00\\\n\r") && name != ".git" && !strings.HasPrefix(name, ".git/") } // readBaseGates reads only immutable base objects. The contract names every // supporting file the gate consumes; standard gate selectors are always pinned. func readBaseGates(ctx context.Context, git, gitDir, base string) (map[string]baseGateFile, error) { listing, err := gateListing(ctx, git, gitDir, base) if err != nil { return nil, err } read := func(name string) (baseGateFile, error) { mode := listing[name] if mode != "100644" && mode != "100755" { return baseGateFile{}, errBaseGate } raw, err := gateGit(ctx, git, gitDir, maxGateBytes, "cat-file", "blob", base+":"+name) perm := os.FileMode(0600) if mode == "100755" { perm = 0700 } return baseGateFile{raw, perm}, err } contract, err := read(gateContract) if err != nil { return nil, err } var spec struct { Version int `json:"version"` Files []string `json:"files"` } dec := json.NewDecoder(strings.NewReader(string(contract.body))) dec.DisallowUnknownFields() if dec.Decode(&spec) != nil || spec.Version != 1 || spec.Files == nil || len(spec.Files) > 2048 { return nil, errBaseGate } if dec.Decode(new(any)) != io.EOF { return nil, errBaseGate } names := map[string]bool{gateContract: true} for name := range listing { if standardGate(name) { names[name] = true } } for _, name := range spec.Files { if !safeGatePath(name) { return nil, errBaseGate } if _, exists := listing[name]; exists { names[name] = true continue } found := false for child := range listing { if strings.HasPrefix(child, name+"/") { names[child] = true found = true } } if !found { return nil, errBaseGate } names[name] = true } out := map[string]baseGateFile{} total := 0 for name := range names { if _, exists := listing[name]; !exists { out[name] = baseGateFile{mode: os.ModeDir | 0700} continue } f, err := read(name) if err != nil { return nil, err } total += len(f.body) if total > 32<<20 { return nil, errBaseGate } out[name] = f } return out, nil } // installBaseGates replaces candidate gate selectors, including newly added // selectors, before choosing a gate. Separate copies become read-only mounts. func installBaseGates(ctx context.Context, tree workspace.TaskTree, candidate string, files map[string]baseGateFile, trusted string) (gate, error) { listing, err := gateListing(ctx, tree.Git, tree.GitDir, candidate) if err != nil { return gate{}, err } root, err := os.OpenRoot(tree.Dir) if err != nil { return gate{}, err } defer root.Close() names := make([]string, 0, len(files)) for name := range files { names = append(names, name) } slices.Sort(names) for name := range listing { if gatePathCovered(files, name) { if err := root.RemoveAll(name); err != nil { return gate{}, err } } } pins := make([]provider.Mount, 0, len(files)) for _, name := range names { f := files[name] if f.mode.IsDir() { if err := root.RemoveAll(name); err != nil { return gate{}, err } if err := root.MkdirAll(name, 0700); err != nil { return gate{}, err } if err := os.MkdirAll(filepath.Join(trusted, name), 0700); err != nil { return gate{}, err } continue } // No candidate symlink is followed when preparing a mount destination. parent := "" for _, part := range strings.Split(path.Dir(name), "/") { if part == "." { continue } parent = path.Join(parent, part) info, err := root.Lstat(parent) if os.IsNotExist(err) { err = root.Mkdir(parent, 0700) } else if err == nil && !info.IsDir() { return gate{}, errBaseGate } if err != nil { return gate{}, err } } if err := root.RemoveAll(name); err != nil { return gate{}, err } if err := root.WriteFile(name, f.body, f.mode); err != nil { return gate{}, err } src := filepath.Join(trusted, filepath.FromSlash(name)) if err := os.MkdirAll(filepath.Dir(src), 0700); err != nil { return gate{}, err } if err := os.WriteFile(src, f.body, f.mode); err != nil { return gate{}, err } if !gateDirectoryContains(files, name) { pins = append(pins, provider.Mount{Source: src, Target: "/workspace/" + name, ReadOnly: true}) } } for _, name := range names { if files[name].mode.IsDir() && !gateDirectoryContains(files, name) { if err := provider.SealTree(filepath.Join(trusted, name)); err != nil { return gate{}, err } pins = append(pins, provider.Mount{Source: filepath.Join(trusted, name), Target: "/workspace/" + name, ReadOnly: true}) } } g, ok := findGate(trusted) if !ok { return gate{}, errBaseGate } g.pins = pins if g.name == ".amadan/ci.d" { // A candidate cannot add a new step after preparation and have a glob run it. var script strings.Builder script.WriteString("set -eu\n") for _, name := range names { if strings.HasPrefix(name, ".amadan/ci.d/") && path.Dir(name) == ".amadan/ci.d" { fmt.Fprintf(&script, "%s\n", shellGatePath("./"+name)) } } g.argv = []string{"/usr/bin/bash", "-c", script.String()} } return g, nil } func shellGatePath(name string) string { return "'" + strings.ReplaceAll(name, "'", "'\"'\"'") + "'" } func gateDirectoryContains(files map[string]baseGateFile, name string) bool { for dir, f := range files { if f.mode.IsDir() && strings.HasPrefix(name, dir+"/") { return true } } return false } func gatePathCovered(files map[string]baseGateFile, name string) bool { _, listed := files[name] return listed || standardGate(name) || gateDirectoryContains(files, name) } func removeBaseGates(dir string) { _ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error { if err == nil && d.IsDir() { _ = os.Chmod(p, 0700) } return err }) _ = os.RemoveAll(dir) }