| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path" |
| 12 | "path/filepath" |
| 13 | "slices" |
| 14 | "strings" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 17 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 18 | ) |
| 19 | |
| 20 | const gateContract = ".equipo/gates.json" |
| 21 | const maxGateBytes = 4 << 20 |
| 22 | |
| 23 | var errBaseGate = errors.New("base gate evidence unavailable") |
| 24 | |
| 25 | type baseGateFile struct { |
| 26 | body []byte |
| 27 | mode os.FileMode |
| 28 | } |
| 29 | |
| 30 | func standardGate(name string) bool { |
| 31 | 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" |
| 32 | } |
| 33 | |
| 34 | func gateGit(ctx context.Context, git, gitDir string, limit int, args ...string) ([]byte, error) { |
| 35 | cmd := exec.CommandContext(ctx, git, append([]string{"--git-dir=" + gitDir}, args...)...) |
| 36 | env := workspace.GitEnvironment() |
| 37 | env["HOME"] = "/nonexistent" |
| 38 | for k, v := range env { |
| 39 | cmd.Env = append(cmd.Env, k+"="+v) |
| 40 | } |
| 41 | out, clipped, err := boundedOutput(cmd, limit) |
| 42 | if err != nil || clipped { |
| 43 | return nil, errBaseGate |
| 44 | } |
| 45 | return out, nil |
| 46 | } |
| 47 | |
| 48 | func gateListing(ctx context.Context, git, gitDir, sha string) (map[string]string, error) { |
| 49 | if !shaPattern.MatchString(sha) { |
| 50 | return nil, errBaseGate |
| 51 | } |
| 52 | raw, err := gateGit(ctx, git, gitDir, 4<<20, "ls-tree", "-rtz", "--full-tree", sha) |
| 53 | if err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | out := map[string]string{} |
| 57 | for _, line := range strings.Split(strings.TrimSuffix(string(raw), "\x00"), "\x00") { |
| 58 | if line == "" { |
| 59 | continue |
| 60 | } |
| 61 | head, name, ok := strings.Cut(line, "\t") |
| 62 | fields := strings.Fields(head) |
| 63 | if !ok || len(fields) != 3 || !safeGatePath(name) { |
| 64 | return nil, errBaseGate |
| 65 | } |
| 66 | if fields[0] != "040000" { |
| 67 | out[name] = fields[0] |
| 68 | } |
| 69 | } |
| 70 | return out, nil |
| 71 | } |
| 72 | |
| 73 | func safeGatePath(name string) bool { |
| 74 | 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/") |
| 75 | } |
| 76 | |
| 77 | // readBaseGates reads only immutable base objects. The contract names every |
| 78 | // supporting file the gate consumes; standard gate selectors are always pinned. |
| 79 | func readBaseGates(ctx context.Context, git, gitDir, base string) (map[string]baseGateFile, error) { |
| 80 | listing, err := gateListing(ctx, git, gitDir, base) |
| 81 | if err != nil { |
| 82 | return nil, err |
| 83 | } |
| 84 | read := func(name string) (baseGateFile, error) { |
| 85 | mode := listing[name] |
| 86 | if mode != "100644" && mode != "100755" { |
| 87 | return baseGateFile{}, errBaseGate |
| 88 | } |
| 89 | raw, err := gateGit(ctx, git, gitDir, maxGateBytes, "cat-file", "blob", base+":"+name) |
| 90 | perm := os.FileMode(0600) |
| 91 | if mode == "100755" { |
| 92 | perm = 0700 |
| 93 | } |
| 94 | return baseGateFile{raw, perm}, err |
| 95 | } |
| 96 | contract, err := read(gateContract) |
| 97 | if err != nil { |
| 98 | return nil, err |
| 99 | } |
| 100 | var spec struct { |
| 101 | Version int `json:"version"` |
| 102 | Files []string `json:"files"` |
| 103 | } |
| 104 | dec := json.NewDecoder(strings.NewReader(string(contract.body))) |
| 105 | dec.DisallowUnknownFields() |
| 106 | if dec.Decode(&spec) != nil || spec.Version != 1 || spec.Files == nil || len(spec.Files) > 2048 { |
| 107 | return nil, errBaseGate |
| 108 | } |
| 109 | if dec.Decode(new(any)) != io.EOF { |
| 110 | return nil, errBaseGate |
| 111 | } |
| 112 | names := map[string]bool{gateContract: true} |
| 113 | for name := range listing { |
| 114 | if standardGate(name) { |
| 115 | names[name] = true |
| 116 | } |
| 117 | } |
| 118 | for _, name := range spec.Files { |
| 119 | if !safeGatePath(name) { |
| 120 | return nil, errBaseGate |
| 121 | } |
| 122 | if _, exists := listing[name]; exists { |
| 123 | names[name] = true |
| 124 | continue |
| 125 | } |
| 126 | found := false |
| 127 | for child := range listing { |
| 128 | if strings.HasPrefix(child, name+"/") { |
| 129 | names[child] = true |
| 130 | found = true |
| 131 | } |
| 132 | } |
| 133 | if !found { |
| 134 | return nil, errBaseGate |
| 135 | } |
| 136 | names[name] = true |
| 137 | } |
| 138 | out := map[string]baseGateFile{} |
| 139 | total := 0 |
| 140 | for name := range names { |
| 141 | if _, exists := listing[name]; !exists { |
| 142 | out[name] = baseGateFile{mode: os.ModeDir | 0700} |
| 143 | continue |
| 144 | } |
| 145 | f, err := read(name) |
| 146 | if err != nil { |
| 147 | return nil, err |
| 148 | } |
| 149 | total += len(f.body) |
| 150 | if total > 32<<20 { |
| 151 | return nil, errBaseGate |
| 152 | } |
| 153 | out[name] = f |
| 154 | } |
| 155 | return out, nil |
| 156 | } |
| 157 | |
| 158 | // installBaseGates replaces candidate gate selectors, including newly added |
| 159 | // selectors, before choosing a gate. Separate copies become read-only mounts. |
| 160 | func installBaseGates(ctx context.Context, tree workspace.TaskTree, candidate string, files map[string]baseGateFile, trusted string) (gate, error) { |
| 161 | listing, err := gateListing(ctx, tree.Git, tree.GitDir, candidate) |
| 162 | if err != nil { |
| 163 | return gate{}, err |
| 164 | } |
| 165 | root, err := os.OpenRoot(tree.Dir) |
| 166 | if err != nil { |
| 167 | return gate{}, err |
| 168 | } |
| 169 | defer root.Close() |
| 170 | names := make([]string, 0, len(files)) |
| 171 | for name := range files { |
| 172 | names = append(names, name) |
| 173 | } |
| 174 | slices.Sort(names) |
| 175 | for name := range listing { |
| 176 | if gatePathCovered(files, name) { |
| 177 | if err := root.RemoveAll(name); err != nil { |
| 178 | return gate{}, err |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | pins := make([]provider.Mount, 0, len(files)) |
| 183 | for _, name := range names { |
| 184 | f := files[name] |
| 185 | if f.mode.IsDir() { |
| 186 | if err := root.RemoveAll(name); err != nil { |
| 187 | return gate{}, err |
| 188 | } |
| 189 | if err := root.MkdirAll(name, 0700); err != nil { |
| 190 | return gate{}, err |
| 191 | } |
| 192 | if err := os.MkdirAll(filepath.Join(trusted, name), 0700); err != nil { |
| 193 | return gate{}, err |
| 194 | } |
| 195 | continue |
| 196 | } |
| 197 | // No candidate symlink is followed when preparing a mount destination. |
| 198 | parent := "" |
| 199 | for _, part := range strings.Split(path.Dir(name), "/") { |
| 200 | if part == "." { |
| 201 | continue |
| 202 | } |
| 203 | parent = path.Join(parent, part) |
| 204 | info, err := root.Lstat(parent) |
| 205 | if os.IsNotExist(err) { |
| 206 | err = root.Mkdir(parent, 0700) |
| 207 | } else if err == nil && !info.IsDir() { |
| 208 | return gate{}, errBaseGate |
| 209 | } |
| 210 | if err != nil { |
| 211 | return gate{}, err |
| 212 | } |
| 213 | } |
| 214 | if err := root.RemoveAll(name); err != nil { |
| 215 | return gate{}, err |
| 216 | } |
| 217 | if err := root.WriteFile(name, f.body, f.mode); err != nil { |
| 218 | return gate{}, err |
| 219 | } |
| 220 | src := filepath.Join(trusted, filepath.FromSlash(name)) |
| 221 | if err := os.MkdirAll(filepath.Dir(src), 0700); err != nil { |
| 222 | return gate{}, err |
| 223 | } |
| 224 | if err := os.WriteFile(src, f.body, f.mode); err != nil { |
| 225 | return gate{}, err |
| 226 | } |
| 227 | if !gateDirectoryContains(files, name) { |
| 228 | pins = append(pins, provider.Mount{Source: src, Target: "/workspace/" + name, ReadOnly: true}) |
| 229 | } |
| 230 | } |
| 231 | for _, name := range names { |
| 232 | if files[name].mode.IsDir() && !gateDirectoryContains(files, name) { |
| 233 | if err := provider.SealTree(filepath.Join(trusted, name)); err != nil { |
| 234 | return gate{}, err |
| 235 | } |
| 236 | pins = append(pins, provider.Mount{Source: filepath.Join(trusted, name), Target: "/workspace/" + name, ReadOnly: true}) |
| 237 | } |
| 238 | } |
| 239 | g, ok := findGate(trusted) |
| 240 | if !ok { |
| 241 | return gate{}, errBaseGate |
| 242 | } |
| 243 | g.pins = pins |
| 244 | if g.name == ".amadan/ci.d" { |
| 245 | // A candidate cannot add a new step after preparation and have a glob run it. |
| 246 | var script strings.Builder |
| 247 | script.WriteString("set -eu\n") |
| 248 | for _, name := range names { |
| 249 | if strings.HasPrefix(name, ".amadan/ci.d/") && path.Dir(name) == ".amadan/ci.d" { |
| 250 | fmt.Fprintf(&script, "%s\n", shellGatePath("./"+name)) |
| 251 | } |
| 252 | } |
| 253 | g.argv = []string{"/usr/bin/bash", "-c", script.String()} |
| 254 | } |
| 255 | return g, nil |
| 256 | } |
| 257 | |
| 258 | func shellGatePath(name string) string { return "'" + strings.ReplaceAll(name, "'", "'\"'\"'") + "'" } |
| 259 | |
| 260 | func gateDirectoryContains(files map[string]baseGateFile, name string) bool { |
| 261 | for dir, f := range files { |
| 262 | if f.mode.IsDir() && strings.HasPrefix(name, dir+"/") { |
| 263 | return true |
| 264 | } |
| 265 | } |
| 266 | return false |
| 267 | } |
| 268 | func gatePathCovered(files map[string]baseGateFile, name string) bool { |
| 269 | _, listed := files[name] |
| 270 | return listed || standardGate(name) || gateDirectoryContains(files, name) |
| 271 | } |
| 272 | |
| 273 | func removeBaseGates(dir string) { |
| 274 | _ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error { |
| 275 | if err == nil && d.IsDir() { |
| 276 | _ = os.Chmod(p, 0700) |
| 277 | } |
| 278 | return err |
| 279 | }) |
| 280 | _ = os.RemoveAll(dir) |
| 281 | } |
| 282 | |