| 1 | package workspace |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "errors" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "reflect" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 17 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 18 | "amadan.net/oficina/equipo/internal/testci" |
| 19 | ) |
| 20 | |
| 21 | var ctx = context.Background() |
| 22 | |
| 23 | func git(t *testing.T, dir string, args ...string) string { |
| 24 | t.Helper() |
| 25 | testci.Tools(t, "git", "python3") |
| 26 | c := exec.Command("/usr/bin/git", append([]string{"-c", "core.hooksPath=/dev/null"}, args...)...) |
| 27 | c.Dir = dir |
| 28 | c.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=fixture", "GIT_AUTHOR_EMAIL=fixture@example.test", "GIT_COMMITTER_NAME=fixture", "GIT_COMMITTER_EMAIL=fixture@example.test"} |
| 29 | out, err := c.CombinedOutput() |
| 30 | if err != nil { |
| 31 | t.Fatalf("git %v: %v %s", args, err, out) |
| 32 | } |
| 33 | return strings.TrimSpace(string(out)) |
| 34 | } |
| 35 | func put(t *testing.T, p, s string) { |
| 36 | t.Helper() |
| 37 | if err := os.WriteFile(p, []byte(s), 0600); err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | type forgeFake struct { |
| 43 | remote Remote |
| 44 | repositories []string |
| 45 | } |
| 46 | |
| 47 | func (f *forgeFake) Resolve(_ context.Context, repository string) (Remote, error) { |
| 48 | f.repositories = append(f.repositories, repository) |
| 49 | return f.remote, nil |
| 50 | } |
| 51 | |
| 52 | type fixture struct { |
| 53 | m *Manager |
| 54 | cfg Config |
| 55 | forge *forgeFake |
| 56 | target team.TargetBinding |
| 57 | a runnerproto.Assignment |
| 58 | brief runnerproto.RunnerBrief |
| 59 | root, seed, remote string |
| 60 | } |
| 61 | |
| 62 | func setup(t *testing.T) *fixture { |
| 63 | return setupWithFormat(t, "sha1") |
| 64 | } |
| 65 | func setupWithFormat(t *testing.T, format string) *fixture { |
| 66 | t.Helper() |
| 67 | root := t.TempDir() |
| 68 | seed := filepath.Join(root, "seed") |
| 69 | remote := filepath.Join(root, "remote.git") |
| 70 | if err := os.Mkdir(seed, 0700); err != nil { |
| 71 | t.Fatal(err) |
| 72 | } |
| 73 | git(t, seed, "init", "--object-format="+format, "-b", "main") |
| 74 | put(t, filepath.Join(seed, "file"), "base\n") |
| 75 | git(t, seed, "add", ".") |
| 76 | git(t, seed, "commit", "-m", "base") |
| 77 | base := git(t, seed, "rev-parse", "HEAD") |
| 78 | git(t, root, "clone", "--bare", seed, remote) |
| 79 | forge := &forgeFake{remote: Remote{URL: remote}} |
| 80 | private := filepath.Join(root, "private") |
| 81 | public := filepath.Join(root, "public") |
| 82 | protected := filepath.Join(root, "protected") |
| 83 | if err := os.Mkdir(protected, 0700); err != nil { |
| 84 | t.Fatal(err) |
| 85 | } |
| 86 | cfg := Config{PrivateRoot: private, WorkspaceRoot: public, GitPath: "/usr/bin/git", Forge: forge, Policy: func(context.Context, provider.Selection) (provider.ReadPolicy, error) { |
| 87 | return provider.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{private, protected}}, nil |
| 88 | }, Definitions: func(_ context.Context, _ team.TargetBinding, _ string) (PreparedBug, error) { |
| 89 | b := []byte(`{"command":"test"}`) |
| 90 | sum := sha256.Sum256(b) |
| 91 | return PreparedBug{CheckDefinition: b, CheckDefinitionHash: hex.EncodeToString(sum[:]), BaselineTestSetHash: strings.Repeat("a", 64)}, nil |
| 92 | }} |
| 93 | cfg.Protected = SecurityPaths{RunnerState: protected + "/state", RunnerConfig: protected + "/config", Journal: protected + "/journal", Bearer: protected + "/bearer", Cleanup: protected + "/cleanup", ForgeCredential: protected + "/forge", LegacyHome: protected + "/paseo", SSH: protected + "/ssh", ProviderHomes: []string{protected + "/provider"}} |
| 94 | m, err := newManager(cfg) |
| 95 | if err != nil { |
| 96 | t.Fatal(err) |
| 97 | } |
| 98 | target := team.TargetBinding{Kind: team.TargetRepository, Repository: "amadan.test/team/repo", DefaultRef: "main", Ref: "equipo/task", BaseRevision: base} |
| 99 | sel := runnerproto.Selection{ConnectionID: "connection", Provider: "claude", Family: "anthropic", Model: "model", AccountID: "account", Revision: 1, Isolation: team.IsolationSnapshot{Status: "confined"}} |
| 100 | a := runnerproto.Assignment{ID: "assignment", TaskID: "task", StepKey: "reproduce", WorkspaceKey: "attempt-1", Selection: sel} |
| 101 | return &fixture{m, cfg, forge, target, a, runnerproto.RunnerBrief{Target: target, Selection: sel}, root, seed, remote} |
| 102 | } |
| 103 | func (f *fixture) create(t *testing.T) Workspace { |
| 104 | t.Helper() |
| 105 | w, err := f.m.Create(ctx, f.a, f.brief) |
| 106 | if err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | return w |
| 110 | } |
| 111 | func TestWorkspacePinsBaseRejectsInvalidTarget(t *testing.T) { |
| 112 | for _, kind := range []string{"default", "bad hash", "ref option", "missing base", "wrong selection"} { |
| 113 | t.Run(kind, func(t *testing.T) { |
| 114 | f := setup(t) |
| 115 | switch kind { |
| 116 | case "default": |
| 117 | f.brief.Target.Ref = f.target.DefaultRef |
| 118 | case "bad hash": |
| 119 | f.brief.Target.BaseRevision = "HEAD" |
| 120 | case "ref option": |
| 121 | f.brief.Target.Ref = "--upload-pack=bad" |
| 122 | case "missing base": |
| 123 | f.brief.Target.BaseRevision = strings.Repeat("f", 40) |
| 124 | case "wrong selection": |
| 125 | f.brief.Selection.ConnectionID = "other" |
| 126 | } |
| 127 | if _, err := f.m.Create(ctx, f.a, f.brief); err == nil { |
| 128 | t.Fatalf("invalid target accepted: %s", kind) |
| 129 | } |
| 130 | }) |
| 131 | } |
| 132 | } |
| 133 | func TestWorkspacePinsBasePrepareDefault(t *testing.T) { |
| 134 | f := setup(t) |
| 135 | f.target.BaseRevision = "" |
| 136 | p, err := f.m.Prepare(ctx, f.target) |
| 137 | if err != nil || p.BaseCommit != f.brief.Target.BaseRevision { |
| 138 | t.Fatalf("default prepare: %+v %v", p, err) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | var _ interface { |
| 143 | Prepare(context.Context, team.TargetBinding) (runnerproto.PreparedBug, error) |
| 144 | } = (*Manager)(nil) |
| 145 | |
| 146 | func TestCandidateCaptureSHA256(t *testing.T) { |
| 147 | f := setupWithFormat(t, "sha256") |
| 148 | w := f.create(t) |
| 149 | put(t, filepath.Join(w.Path, "file"), "fixed sha256\n") |
| 150 | git(t, w.Path, "commit", "-am", "fix") |
| 151 | c, err := f.m.CaptureCandidate(ctx, w, f.target) |
| 152 | if err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | if len(c.Commit) != 64 || len(c.Tree) != 64 || len(c.BaseCommit) != 64 { |
| 156 | t.Fatal("sha256 object identity lost") |
| 157 | } |
| 158 | if err := f.m.ExportCandidate(ctx, c, filepath.Join(f.root, "sha256-review")); err != nil { |
| 159 | t.Fatal(err) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | func TestWorkspacePinsBase(t *testing.T) { |
| 164 | f := setup(t) |
| 165 | put(t, filepath.Join(f.seed, "file"), "moving default\n") |
| 166 | git(t, f.seed, "commit", "-am", "move") |
| 167 | git(t, f.seed, "push", f.remote, "main") |
| 168 | p, err := f.m.Prepare(ctx, f.target) |
| 169 | if err != nil || p.BaseCommit != f.target.BaseRevision || p.Repository != f.target.Repository { |
| 170 | t.Fatalf("prepare: %+v %v", p, err) |
| 171 | } |
| 172 | w := f.create(t) |
| 173 | if got := git(t, w.Path, "rev-parse", "HEAD"); got != f.target.BaseRevision { |
| 174 | t.Fatalf("base moved: %s", got) |
| 175 | } |
| 176 | f.a.WorkspaceKey = "attempt-2" |
| 177 | f.a.StepKey = "implement" |
| 178 | f.brief.ArtifactHashes = []string{strings.Repeat("b", 64)} |
| 179 | next := f.create(t) |
| 180 | if next.Path == w.Path || !reflect.DeepEqual(next.ArtifactHashes, f.brief.ArtifactHashes) || git(t, next.Path, "rev-parse", "HEAD") != f.target.BaseRevision { |
| 181 | t.Fatal("implementation did not get fresh base and frozen reproduction") |
| 182 | } |
| 183 | f.brief.ArtifactHashes = nil |
| 184 | f.a.WorkspaceKey = "attempt-3" |
| 185 | if _, err := f.m.Create(ctx, f.a, f.brief); err == nil { |
| 186 | t.Fatal("implementation without frozen reproduction accepted") |
| 187 | } |
| 188 | } |
| 189 | func TestCandidateCaptureCleanAndImmutable(t *testing.T) { |
| 190 | for _, kind := range []string{"tracked", "staged", "untracked", "ignored", "symlink", "relative symlink", "wrong repository", "wrong ref", "not descendant", "wrong gitdir", "objects symlink", "alternates", "skip worktree"} { |
| 191 | t.Run(kind, func(t *testing.T) { |
| 192 | f := setup(t) |
| 193 | w := f.create(t) |
| 194 | target := f.target |
| 195 | switch kind { |
| 196 | case "tracked": |
| 197 | put(t, filepath.Join(w.Path, "file"), "dirty") |
| 198 | case "staged": |
| 199 | put(t, filepath.Join(w.Path, "file"), "staged") |
| 200 | git(t, w.Path, "add", ".") |
| 201 | put(t, filepath.Join(w.Path, "file"), "base\n") |
| 202 | case "untracked": |
| 203 | put(t, filepath.Join(w.Path, "extra"), "dirty") |
| 204 | case "ignored": |
| 205 | put(t, filepath.Join(w.Path, ".gitignore"), "ignored\n") |
| 206 | git(t, w.Path, "add", ".") |
| 207 | git(t, w.Path, "commit", "-m", "ignore") |
| 208 | put(t, filepath.Join(w.Path, "ignored"), "dirty") |
| 209 | case "symlink": |
| 210 | if err := os.Symlink(f.root, filepath.Join(w.Path, "escape")); err != nil { |
| 211 | t.Fatal(err) |
| 212 | } |
| 213 | git(t, w.Path, "add", ".") |
| 214 | git(t, w.Path, "commit", "-m", "escape") |
| 215 | case "relative symlink": |
| 216 | rel, err := filepath.Rel(w.Path, f.root) |
| 217 | if err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | if err := os.Symlink(rel, filepath.Join(w.Path, "escape")); err != nil { |
| 221 | t.Fatal(err) |
| 222 | } |
| 223 | git(t, w.Path, "add", ".") |
| 224 | git(t, w.Path, "commit", "-m", "escape") |
| 225 | case "wrong repository": |
| 226 | target.Repository = "other/repo" |
| 227 | case "wrong ref": |
| 228 | git(t, w.Path, "checkout", "-b", "wrong") |
| 229 | case "not descendant": |
| 230 | git(t, w.Path, "checkout", "--orphan", "other") |
| 231 | git(t, w.Path, "add", ".") |
| 232 | git(t, w.Path, "commit", "-m", "orphan") |
| 233 | git(t, w.Path, "branch", "-f", f.target.Ref, "HEAD") |
| 234 | git(t, w.Path, "checkout", f.target.Ref) |
| 235 | case "wrong gitdir": |
| 236 | foreign := filepath.Join(f.root, "foreign-work") |
| 237 | git(t, f.seed, "worktree", "add", "-b", f.target.Ref, foreign, f.target.BaseRevision) |
| 238 | b, err := os.ReadFile(filepath.Join(foreign, ".git")) |
| 239 | if err != nil { |
| 240 | t.Fatal(err) |
| 241 | } |
| 242 | if err := os.RemoveAll(filepath.Join(w.Path, ".git")); err != nil { |
| 243 | t.Fatal(err) |
| 244 | } |
| 245 | put(t, filepath.Join(w.Path, ".git"), string(b)) |
| 246 | case "objects symlink": |
| 247 | oid := git(t, f.seed, "rev-parse", "HEAD:file") |
| 248 | object := filepath.Join(w.Path, ".git", "objects", oid[:2], oid[2:]) |
| 249 | if err := os.Remove(object); err != nil { |
| 250 | t.Fatal(err) |
| 251 | } |
| 252 | if err := os.Symlink(filepath.Join(f.seed, ".git", "objects", oid[:2], oid[2:]), object); err != nil { |
| 253 | t.Fatal(err) |
| 254 | } |
| 255 | case "alternates": |
| 256 | put(t, filepath.Join(w.Path, ".git", "objects", "info", "alternates"), filepath.Join(f.seed, ".git", "objects")) |
| 257 | case "skip worktree": |
| 258 | git(t, w.Path, "update-index", "--skip-worktree", "file") |
| 259 | put(t, filepath.Join(w.Path, "file"), "hidden dirty") |
| 260 | } |
| 261 | if _, err := f.m.CaptureCandidate(ctx, w, target); err == nil { |
| 262 | t.Fatalf("unsafe candidate accepted: %s", kind) |
| 263 | } |
| 264 | }) |
| 265 | } |
| 266 | f := setup(t) |
| 267 | w := f.create(t) |
| 268 | put(t, filepath.Join(w.Path, "file"), "fixed\n") |
| 269 | git(t, w.Path, "commit", "-am", "fix") |
| 270 | unusedPath := filepath.Join(f.root, "unused") |
| 271 | put(t, unusedPath, "unused-private-fixture") |
| 272 | unused := git(t, w.Path, "hash-object", "-w", unusedPath) |
| 273 | c, err := f.m.CaptureCandidate(ctx, w, f.target) |
| 274 | if err != nil { |
| 275 | t.Fatal(err) |
| 276 | } |
| 277 | if c.Commit != git(t, w.Path, "rev-parse", "HEAD") || c.Tree != git(t, w.Path, "rev-parse", "HEAD^{tree}") { |
| 278 | t.Fatal("candidate identity mismatch") |
| 279 | } |
| 280 | if err := os.RemoveAll(f.cfg.WorkspaceRoot); err != nil { |
| 281 | t.Fatal(err) |
| 282 | } |
| 283 | for _, name := range []string{"review", "checks"} { |
| 284 | dest := filepath.Join(f.root, name) |
| 285 | if err := f.m.ExportCandidate(ctx, c, dest); err != nil { |
| 286 | t.Fatal(err) |
| 287 | } |
| 288 | cmd := exec.Command("/usr/bin/git", "-C", dest, "cat-file", "-e", unused) |
| 289 | if cmd.Run() == nil { |
| 290 | t.Fatal("unreachable builder object exported") |
| 291 | } |
| 292 | if got := git(t, dest, "rev-parse", "HEAD^{tree}"); got != c.Tree { |
| 293 | t.Fatal("staged tree changed") |
| 294 | } |
| 295 | } |
| 296 | bad := c |
| 297 | bad.Tree = strings.Repeat("a", 40) |
| 298 | if err := f.m.ExportCandidate(ctx, bad, filepath.Join(f.root, "bad")); err == nil { |
| 299 | t.Fatal("forged candidate exported") |
| 300 | } |
| 301 | } |
| 302 | func TestWorkspaceHasNoCredentials(t *testing.T) { |
| 303 | f := setup(t) |
| 304 | sentinel := "credential-sentinel-do-not-leak" |
| 305 | marker := filepath.Join(f.root, "executed") |
| 306 | poison := filepath.Join(f.root, "poison") |
| 307 | put(t, poison, "[include]\n path = /missing\n[core]\n hooksPath = "+f.root+"\n fsmonitor = touch "+marker+"\n[credential]\n helper = !touch "+marker+"\n[url \"ext::touch "+marker+"\"]\n insteadOf = "+f.remote+"\n") |
| 308 | t.Setenv("GIT_CONFIG_GLOBAL", poison) |
| 309 | t.Setenv("GIT_CONFIG_SYSTEM", poison) |
| 310 | t.Setenv("GIT_CONFIG_COUNT", "1") |
| 311 | t.Setenv("GIT_CONFIG_KEY_0", "core.fsmonitor") |
| 312 | t.Setenv("GIT_CONFIG_VALUE_0", "touch "+marker) |
| 313 | t.Setenv("EQUIPO_BEARER", sentinel) |
| 314 | put(t, filepath.Join(f.remote, "hooks", "post-checkout"), "#!/bin/sh\ntouch "+marker+"\n") |
| 315 | if err := os.Chmod(filepath.Join(f.remote, "hooks", "post-checkout"), 0700); err != nil { |
| 316 | t.Fatal(err) |
| 317 | } |
| 318 | w := f.create(t) |
| 319 | env := w.Environment() |
| 320 | for k, v := range env { |
| 321 | if strings.Contains(k+v, sentinel) || strings.Contains(k, "BEARER") { |
| 322 | t.Fatal("credential leaked to agent") |
| 323 | } |
| 324 | } |
| 325 | if env["GIT_CONFIG_NOSYSTEM"] != "1" || env["GIT_CONFIG_GLOBAL"] != "/dev/null" || env["GIT_CONFIG_COUNT"] == "" { |
| 326 | t.Fatal("agent git environment not isolated") |
| 327 | } |
| 328 | put(t, filepath.Join(w.Path, "file"), "candidate\n") |
| 329 | put(t, filepath.Join(w.Path, ".gitattributes"), "file filter=poison\n") |
| 330 | git(t, w.Path, "add", ".") |
| 331 | git(t, w.Path, "commit", "-m", "candidate") |
| 332 | // Includes, hooks, helpers, filters and fsmonitor in builder config must never be loaded by capture. |
| 333 | source := w.Path |
| 334 | file, err := os.OpenFile(filepath.Join(source, ".git", "config"), os.O_APPEND|os.O_WRONLY, 0600) |
| 335 | if err != nil { |
| 336 | t.Fatal(err) |
| 337 | } |
| 338 | _, err = file.WriteString("\n[include]\n path = " + poison + "\n[filter \"poison\"]\n clean = touch " + marker + "\n required = true\n") |
| 339 | file.Close() |
| 340 | if err != nil { |
| 341 | t.Fatal(err) |
| 342 | } |
| 343 | if _, err := f.m.CaptureCandidate(ctx, w, f.target); err == nil { |
| 344 | t.Fatal("modified builder config accepted") |
| 345 | } |
| 346 | if _, err := os.Stat(marker); !os.IsNotExist(err) { |
| 347 | t.Fatal("poison config executed") |
| 348 | } |
| 349 | data, err := os.ReadFile(filepath.Join(w.Path, ".git", "config")) |
| 350 | if err != nil { |
| 351 | t.Fatal(err) |
| 352 | } |
| 353 | data = data[:strings.Index(string(data), "\n[include]")] |
| 354 | if err = os.WriteFile(filepath.Join(w.Path, ".git", "config"), data, 0600); err != nil { |
| 355 | t.Fatal(err) |
| 356 | } |
| 357 | c, err := f.m.CaptureCandidate(ctx, w, f.target) |
| 358 | if err != nil { |
| 359 | t.Fatal(err) |
| 360 | } |
| 361 | dest := filepath.Join(f.root, "export") |
| 362 | if err := f.m.ExportCandidate(ctx, c, dest); err != nil { |
| 363 | t.Fatal(err) |
| 364 | } |
| 365 | for _, dir := range []string{f.cfg.WorkspaceRoot, dest} { |
| 366 | err := filepath.WalkDir(dir, func(p string, d os.DirEntry, e error) error { |
| 367 | if e != nil { |
| 368 | return e |
| 369 | } |
| 370 | if !d.IsDir() && d.Type().IsRegular() { |
| 371 | b, e := os.ReadFile(p) |
| 372 | if e != nil { |
| 373 | return e |
| 374 | } |
| 375 | if strings.Contains(string(b), sentinel) { |
| 376 | t.Fatalf("credential leaked to %s", p) |
| 377 | } |
| 378 | } |
| 379 | return nil |
| 380 | }) |
| 381 | if err != nil { |
| 382 | t.Fatal(err) |
| 383 | } |
| 384 | } |
| 385 | if _, err := os.Stat(marker); !os.IsNotExist(err) { |
| 386 | t.Fatal("poison git configuration executed") |
| 387 | } |
| 388 | f.forge.remote = Remote{URL: "https://user:secret@invalid.test/repo", GitPassword: sentinel} |
| 389 | f.target.Repository = "invalid" |
| 390 | if _, err := f.m.Prepare(ctx, f.target); err == nil || strings.Contains(err.Error(), sentinel) { |
| 391 | t.Fatal("credential URL accepted or diagnostic leaked") |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | func TestPreparationDiagnostic(t *testing.T) { |
| 396 | f := setup(t) |
| 397 | cause := errors.New("baseline setup cause") |
| 398 | f.m.cfg.Definitions = func(context.Context, team.TargetBinding, string) (PreparedBug, error) { return PreparedBug{}, cause } |
| 399 | _, err := f.m.Prepare(ctx, f.target) |
| 400 | if !errors.Is(err, provider.ErrContract) || !errors.Is(err, cause) || !strings.Contains(err.Error(), "preparation definition/baseline") { |
| 401 | t.Fatalf("preparation lost cause: %v", err) |
| 402 | } |
| 403 | } |
| 404 | |