package workspace import ( "context" "errors" "io" "io/fs" "os" "os/exec" "path/filepath" "strings" ) // Task tree errors. var ( // ErrNoChanges means the step left the tree as it found it. ErrNoChanges = errors.New("workspace: no changes") // ErrTreeRefused means the tree holds something the runner will not // commit: a .git entry at any depth, or a device, pipe or socket. ErrTreeRefused = errors.New("workspace: tree refused") ) // TaskTree is one step's working copy. Dir is all a namespace sees: the // files at the base commit, no .git. GitDir is the runner's private // repository beside it (objects borrowed from the project clone), where // the runner itself commits what changed. No hook, helper, filter or // config from the repository or the namespace ever runs. type TaskTree struct { Dir, GitDir, Git, Branch, Base string absentSandboxPaths []string } func (t TaskTree) git(ctx context.Context, stdin io.Reader, extra []string, args ...string) (string, error) { cmd := exec.CommandContext(ctx, t.Git, append([]string{"-c", "core.symlinks=true", "-c", "core.autocrlf=false", "-c", "core.untrackedCache=false", "-c", "core.quotePath=false", "-c", "gc.auto=0"}, args...)...) cmd.Dir = t.GitDir env := safeEnv() env["HOME"] = "/nonexistent" env["GIT_DIR"] = t.GitDir env["GIT_WORK_TREE"] = t.Dir env["GIT_CEILING_DIRECTORIES"] = filepath.Dir(t.GitDir) for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } cmd.Env = append(cmd.Env, extra...) cmd.Stdin, cmd.Stderr = stdin, io.Discard out, err := cmd.Output() return strings.TrimSpace(string(out)), err } // PrepareTaskTree checks out base from the bare project clone into dir, // with the branch pointing at base in a fresh private repository. Both // paths are replaced if a previous attempt left them. func PrepareTaskTree(ctx context.Context, git, clone, base, branch, dir, gitDir string) (TaskTree, error) { t := TaskTree{Dir: dir, GitDir: gitDir, Git: git, Branch: branch, Base: base} // No base: the repository has no commits yet. The tree starts empty // on the task branch, unborn, and its first commit has no parent. if !filepath.IsAbs(dir) || !filepath.IsAbs(gitDir) || !filepath.IsAbs(clone) || base != "" && !objectID.MatchString(base) || branch == "" || strings.HasPrefix(branch, "-") { return t, ErrTreeRefused } for _, p := range []string{dir, gitDir} { if err := os.RemoveAll(p); err != nil { return t, err } } if err := os.MkdirAll(filepath.Dir(gitDir), 0700); err != nil { return t, err } init := exec.CommandContext(ctx, git, "init", "-q", "--bare", "--template=", "--object-format="+objectFormat(base), gitDir) init.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null"} if err := init.Run(); err != nil { return t, err } objects := filepath.Join(clone, "objects") if info, err := os.Lstat(objects); err != nil || !info.IsDir() { return t, ErrTreeRefused } if err := os.MkdirAll(filepath.Join(gitDir, "objects", "info"), 0700); err != nil { return t, err } if err := os.WriteFile(filepath.Join(gitDir, "objects", "info", "alternates"), []byte(objects+"\n"), 0600); err != nil { return t, err } // A shallow clone (the context index fetches with depth 1) ends its // history at a boundary; the private repository keeps the same one. if raw, err := os.ReadFile(filepath.Join(clone, "shallow")); err == nil { if err := os.WriteFile(filepath.Join(gitDir, "shallow"), raw, 0600); err != nil { return t, err } } else if !errors.Is(err, os.ErrNotExist) { return t, err } if base == "" { if err := os.MkdirAll(dir, 0700); err != nil { return t, err } if _, err := t.git(ctx, nil, nil, "symbolic-ref", "HEAD", "refs/heads/"+branch); err != nil { return t, err } err := t.recordSandboxPaths() return t, err } if id, err := t.git(ctx, nil, nil, "rev-parse", "--verify", "--end-of-options", base+"^{commit}"); err != nil || id != base { return t, ErrTreeRefused } if err := os.MkdirAll(dir, 0700); err != nil { return t, err } if _, err := t.git(ctx, nil, nil, "read-tree", "--end-of-options", base); err != nil { return t, err } if _, err := t.git(ctx, nil, nil, "checkout-index", "-a", "-f"); err != nil { return t, err } if _, err := t.git(ctx, nil, nil, "update-ref", "refs/heads/"+branch, base); err != nil { return t, err } if _, err := t.git(ctx, nil, nil, "symbolic-ref", "HEAD", "refs/heads/"+branch); err != nil { return t, err } err := t.recordSandboxPaths() return t, err } // check refuses a tree that holds a .git entry at any depth (it would // become a gitlink or a nested repository) or a special file. func (t TaskTree) check() error { files := 0 return filepath.WalkDir(t.Dir, func(p string, d fs.DirEntry, err error) error { if err != nil { return ErrTreeRefused } if p == t.Dir { return nil } if strings.EqualFold(d.Name(), ".git") { return ErrTreeRefused } if files++; files > 500_000 { return ErrTreeRefused } switch m := d.Type(); { case m.IsDir(), m.IsRegular(), m&fs.ModeSymlink != 0: return nil } return ErrTreeRefused }) } // Commit records everything the step changed as one commit on the base, // made by the runner (the model never runs git here). ErrNoChanges when // the tree matches the base. func (t TaskTree) Commit(ctx context.Context, message, name, email string) (string, error) { if err := t.check(); err != nil { return "", err } if err := t.removeSandboxMasks(); err != nil { return "", err } if _, err := t.git(ctx, nil, nil, "add", "-A", "--", "."); err != nil { return "", err } tree, err := t.git(ctx, nil, nil, "write-tree") if err != nil || !objectID.MatchString(tree) { return "", ErrTreeRefused } // Without a base the tree is compared with the empty tree, and the // commit is the repository's first (no parent). var baseTree string parent := []string{} if t.Base == "" { baseTree, err = t.git(ctx, strings.NewReader(""), nil, "hash-object", "-t", "tree", "--stdin") } else { baseTree, err = t.git(ctx, nil, nil, "rev-parse", "--verify", "--end-of-options", t.Base+"^{tree}") parent = []string{"-p", t.Base} } if err != nil { return "", err } if tree == baseTree { return "", ErrNoChanges } who := []string{"GIT_AUTHOR_NAME=" + name, "GIT_AUTHOR_EMAIL=" + email, "GIT_COMMITTER_NAME=" + name, "GIT_COMMITTER_EMAIL=" + email} sha, err := t.git(ctx, strings.NewReader(message), who, append([]string{"commit-tree", tree}, parent...)...) if err != nil || !objectID.MatchString(sha) { return "", ErrTreeRefused } if _, err := t.git(ctx, nil, nil, "update-ref", "refs/heads/"+t.Branch, sha); err != nil { return "", err } return sha, nil } // ChangedFiles lists the paths a commit changed against its base; with // no base, against its parent, and every path of an initial commit. func (t TaskTree) ChangedFiles(ctx context.Context, sha string) ([]string, error) { args := []string{"diff-tree", "--no-commit-id", "--name-only", "-r", "--no-renames", "--no-ext-diff", "--no-textconv"} if t.Base == "" { args = append(args, "--root", sha) } else { args = append(args, t.Base, sha) } out, err := t.git(ctx, nil, nil, args...) if err != nil { return nil, err } if out == "" { return nil, nil } return strings.Split(out, "\n"), nil } // Remove deletes the working copy and the private repository. func (t TaskTree) Remove() error { return errors.Join(os.RemoveAll(t.Dir), os.RemoveAll(t.GitDir)) } // Rebase puts a change on top of the tree's base: the three-way merge of // the base and commit, with from (the base the change was made on) as // their merge base, replaces the working copy. Files that conflict carry // git's conflict markers; their paths are returned for the specialist to // resolve. The runner still commits on the base, so the new commit is // the change, rebased. No merge driver or attribute from the repository // runs (system and global config are off). func (t *TaskTree) Rebase(ctx context.Context, from, commit string) ([]string, error) { if !objectID.MatchString(from) || !objectID.MatchString(commit) || !objectID.MatchString(t.Base) { return nil, ErrTreeRefused } for _, c := range []string{from, commit} { if id, err := t.git(ctx, nil, nil, "rev-parse", "--verify", "--end-of-options", c+"^{commit}"); err != nil || id != c { return nil, ErrTreeRefused } } out, err := t.git(ctx, nil, nil, "merge-tree", "--write-tree", "--name-only", "--no-messages", "-z", "--merge-base="+from, t.Base, commit) var exit *exec.ExitError if err != nil && !(errors.As(err, &exit) && exit.ExitCode() == 1) { return nil, err } fields := strings.Split(strings.TrimRight(out, "\x00"), "\x00") tree := fields[0] if !objectID.MatchString(tree) { return nil, ErrTreeRefused } var conflicts []string for _, p := range fields[1:] { if p != "" && (len(conflicts) == 0 || conflicts[len(conflicts)-1] != p) { conflicts = append(conflicts, p) } } entries, err := os.ReadDir(t.Dir) if err != nil { return nil, err } for _, e := range entries { if err := os.RemoveAll(filepath.Join(t.Dir, e.Name())); err != nil { return nil, err } } if _, err := t.git(ctx, nil, nil, "read-tree", "--end-of-options", tree); err != nil { return nil, err } if _, err := t.git(ctx, nil, nil, "checkout-index", "-a", "-f"); err != nil { return nil, err } return conflicts, t.recordSandboxPaths() }