package workspace import ( "bytes" "context" "crypto/sha1" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/url" "os" "os/exec" "path/filepath" "reflect" "regexp" "strings" "sync" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type PreparedBug = runnerproto.PreparedBug type GitCandidate = team.GitCandidate type Remote struct{ URL, GitPassword, GitUsername string } // Username preserves the hub's historical Basic authentication user. func (r Remote) Username() string { if r.GitUsername == "" { return "x" } return r.GitUsername } var ErrGitPassword = errors.New("configure a repository git password (PAT) in EQUIPO_AMADAN_CREDENTIAL_PATH") // ErrHubUnavailable: the forge could not be asked whether the agent may // write to the repository now (no answer, an error status, an unreadable // list). Nothing was sent; unlike a denial, it is worth trying again. var ErrHubUnavailable = errors.New("the forge could not be reached to confirm write access; nothing was sent") type ForgeRead interface { Resolve(context.Context, string) (Remote, error) } type SecurityPaths struct { RunnerState, RunnerConfig, Journal, Bearer, Cleanup, ForgeCredential, LegacyHome, SSH string ProviderHomes []string // PreviewCredential is the preview credential file, "" when previews // are off. PreviewCredential string } func (p SecurityPaths) all() []string { return append(p.Credentials(), p.ProviderHomes...) } // Credentials are the protected single paths: never mounted into, or // read from, a sandbox. The preview credential only when set. func (p SecurityPaths) Credentials() []string { out := []string{p.RunnerState, p.RunnerConfig, p.Journal, p.Bearer, p.Cleanup, p.ForgeCredential, p.LegacyHome, p.SSH} if p.PreviewCredential != "" { out = append(out, p.PreviewCredential) } return out } type Config struct { Protected SecurityPaths PrivateRoot, WorkspaceRoot, GitPath string Forge ForgeRead Policy func(context.Context, provider.Selection) (provider.ReadPolicy, error) Definitions func(context.Context, team.TargetBinding, string) (PreparedBug, error) } type Manager struct { cfg Config mu sync.Mutex } type Workspace struct { ID, Path string Record provider.Workspace ArtifactHashes []string Isolation team.IsolationSnapshot key string } type attempt struct { ReadOnly bool ContentHash string Local bool ConfigHash string AssignmentHash string Hash string Request provider.WorkspaceRequest Workspace provider.Workspace Target team.TargetBinding ArtifactHashes []string Isolation team.IsolationSnapshot } var objectID = regexp.MustCompile(`^(?:[a-f0-9]{40}|[a-f0-9]{64})$`) var packFile = regexp.MustCompile(`^pack-[a-f0-9]{40}(?:[a-f0-9]{24})?\.(pack|idx|rev)$`) func New(cfg Config) (*Manager, error) { return newManager(cfg) } func newManager(cfg Config) (*Manager, error) { if cfg.Forge == nil || cfg.Policy == nil || cfg.Definitions == nil || !filepath.IsAbs(cfg.GitPath) { return nil, provider.ErrContract } for _, p := range []string{cfg.PrivateRoot, cfg.WorkspaceRoot} { if !filepath.IsAbs(p) || filepath.Clean(p) != p { return nil, provider.ErrPolicy } } if contains(cfg.PrivateRoot, cfg.WorkspaceRoot) || contains(cfg.WorkspaceRoot, cfg.PrivateRoot) { return nil, provider.ErrPolicy } if len(cfg.Protected.ProviderHomes) == 0 { return nil, provider.ErrPolicy } cfg.Protected.ProviderHomes = append([]string(nil), cfg.Protected.ProviderHomes...) for _, p := range cfg.Protected.all() { if _, e := canonical(p); e != nil { return nil, provider.ErrPolicy } } for _, p := range []string{cfg.PrivateRoot, cfg.WorkspaceRoot} { if resolved, e := canonical(p); e != nil || resolved != p { return nil, provider.ErrPolicy } if err := os.MkdirAll(p, 0700); err != nil { return nil, provider.ErrPolicy } info, err := os.Stat(p) if err != nil || info.Mode().Perm()&0077 != 0 { return nil, provider.ErrPolicy } resolved, err := filepath.EvalSymlinks(p) if err != nil || resolved != p { return nil, provider.ErrPolicy } } return &Manager{cfg: cfg}, nil } func digest(v any) string { b, _ := json.Marshal(v) s := sha256.Sum256(b) return hex.EncodeToString(s[:]) } func contains(root, p string) bool { rel, e := filepath.Rel(root, p) return e == nil && (rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))) } func canonical(p string) (string, error) { if !filepath.IsAbs(p) || filepath.Clean(p) != p { return "", provider.ErrPolicy } tail := "" for ancestor := p; ; ancestor = filepath.Dir(ancestor) { r, e := filepath.EvalSymlinks(ancestor) if e == nil { return filepath.Join(r, tail), nil } if !os.IsNotExist(e) || ancestor == filepath.Dir(ancestor) { return "", provider.ErrPolicy } tail = filepath.Join(filepath.Base(ancestor), tail) } } func allowed(p string, policy provider.ReadPolicy) bool { r, e := canonical(p) if e != nil || policy.ConfigHash == "" || len(policy.DeniedPaths) == 0 { return false } for _, deny := range policy.DeniedPaths { d, e := canonical(deny) if e != nil || contains(d, r) { return false } } return true } func safeEnv() map[string]string { return map[string]string{"PATH": "/usr/bin:/bin", "LANG": "C", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_SYSTEM": "/dev/null", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_TERMINAL_PROMPT": "0", "GIT_NO_REPLACE_OBJECTS": "1", "GIT_ATTR_NOSYSTEM": "1", "GIT_CONFIG_COUNT": "9", "GIT_CONFIG_KEY_0": "core.hooksPath", "GIT_CONFIG_VALUE_0": "/dev/null", "GIT_CONFIG_KEY_1": "credential.helper", "GIT_CONFIG_VALUE_1": "", "GIT_CONFIG_KEY_2": "core.fsmonitor", "GIT_CONFIG_VALUE_2": "false", "GIT_CONFIG_KEY_3": "protocol.allow", "GIT_CONFIG_VALUE_3": "never", "GIT_CONFIG_KEY_4": "core.attributesFile", "GIT_CONFIG_VALUE_4": "/dev/null", "GIT_CONFIG_KEY_5": "core.sshCommand", "GIT_CONFIG_VALUE_5": "/bin/false", "GIT_CONFIG_KEY_6": "commit.gpgSign", "GIT_CONFIG_VALUE_6": "false", "GIT_CONFIG_KEY_7": "maintenance.auto", "GIT_CONFIG_VALUE_7": "false", "GIT_CONFIG_KEY_8": "gc.autoDetach", "GIT_CONFIG_VALUE_8": "false"} } func GitEnvironment() map[string]string { return safeEnv() } func (w Workspace) Environment() map[string]string { return GitEnvironment() } func (m *Manager) git(ctx context.Context, dir string, input []byte, extra map[string]string, args ...string) ([]byte, error) { cmd := exec.CommandContext(ctx, m.cfg.GitPath, args...) cmd.Dir = dir env := safeEnv() env["HOME"] = "/nonexistent" for k, v := range extra { env[k] = v } for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } cmd.Stdin = bytes.NewReader(input) cmd.Stderr = io.Discard b, err := cmd.Output() if err != nil { return nil, provider.ErrContract } return b, nil } func (m *Manager) run(ctx context.Context, dir string, args ...string) (string, error) { b, e := m.git(ctx, dir, nil, nil, args...) return strings.TrimSpace(string(b)), e } func (m *Manager) validTarget(ctx context.Context, t team.TargetBinding, base bool) bool { if t.Kind != team.TargetRepository || t.Repository == "" || strings.ContainsAny(t.Repository, "\r\n\x00") || t.Ref == t.DefaultRef || t.Subject != "" || base && !objectID.MatchString(t.BaseRevision) { return false } for _, r := range []string{t.Ref, t.DefaultRef} { if r == "" || r == "HEAD" || r == "@" || strings.HasPrefix(r, "refs/") || strings.HasPrefix(r, "-") { return false } if _, e := m.run(ctx, m.cfg.PrivateRoot, "check-ref-format", "refs/heads/"+r); e != nil { return false } } return true } func (m *Manager) init(ctx context.Context, dir, format string, bare bool) error { args := []string{"init", "--template=", "--object-format=" + format} if bare { args = append(args, "--bare") } args = append(args, dir) if _, e := m.run(ctx, m.cfg.PrivateRoot, args...); e != nil { return e } for _, kv := range [][2]string{{"core.hooksPath", "/dev/null"}, {"credential.helper", ""}, {"core.fsmonitor", "false"}, {"core.attributesFile", "/dev/null"}, {"protocol.allow", "never"}, {"commit.gpgSign", "false"}} { if _, e := m.run(ctx, dir, "config", "--local", kv[0], kv[1]); e != nil { return e } } return nil } func objectFormat(id string) string { if len(id) == 64 { return "sha256" } return "sha1" } func (m *Manager) fetch(ctx context.Context, t team.TargetBinding) (string, string, error) { remote, err := m.cfg.Forge.Resolve(ctx, t.Repository) if errors.Is(err, ErrGitPassword) { return "", "", ErrGitPassword } if err != nil { return "", "", provider.ErrContract } protocol := "" if filepath.IsAbs(remote.URL) { r, e := canonical(remote.URL) if e != nil || r != remote.URL || remote.GitPassword != "" { return "", "", provider.ErrPolicy } protocol = "file" } else { u, e := url.Parse(remote.URL) if e != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || strings.ContainsAny(remote.URL+remote.GitPassword, "\r\n\x00") { return "", "", provider.ErrPolicy } if remote.GitPassword == "" { return "", "", ErrGitPassword } protocol = "https" } repo := filepath.Join(m.cfg.PrivateRoot, "project-"+digest(t.Repository)) if _, err := os.Stat(repo); os.IsNotExist(err) { if err = m.init(ctx, repo, objectFormat(t.BaseRevision), true); err != nil { return "", "", err } } else if err != nil { return "", "", provider.ErrContract } ref := t.BaseRevision if ref == "" { ref = "refs/heads/" + t.DefaultRef } env := map[string]string{} if remote.GitPassword != "" { env["GIT_CONFIG_COUNT"] = "10" env["GIT_CONFIG_KEY_9"] = "http.extraHeader" env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(remote.Username()+":"+remote.GitPassword)) } if _, err := m.git(ctx, repo, nil, env, "-c", "protocol."+protocol+".allow=always", "-c", "http.followRedirects=false", "fetch", "--no-auto-maintenance", "--no-tags", "--no-recurse-submodules", "--", remote.URL, ref); err != nil { return "", "", err } base, err := m.run(ctx, repo, "rev-parse", "--verify", "FETCH_HEAD^{commit}") if err != nil || !objectID.MatchString(base) || t.BaseRevision != "" && base != t.BaseRevision { return "", "", provider.ErrIdentity } return repo, base, nil } func (m *Manager) Prepare(ctx context.Context, target team.TargetBinding) (PreparedBug, error) { m.mu.Lock() defer m.mu.Unlock() if !m.validTarget(ctx, target, target.BaseRevision != "") { return PreparedBug{}, provider.ErrContract } repo, base, err := m.fetch(ctx, target) if err != nil { return PreparedBug{}, err } target.BaseRevision = base p, err := m.cfg.Definitions(ctx, target, repo) if err != nil { return PreparedBug{}, fmt.Errorf("%w: preparation definition/baseline: %w", provider.ErrContract, err) } s := sha256.Sum256(p.CheckDefinition) if len(p.CheckDefinition) == 0 || len(p.CheckDefinition) > team.MaxArtifactBytes || hex.EncodeToString(s[:]) != p.CheckDefinitionHash || len(p.BaselineTestSetHash) != 64 || !objectID.MatchString(p.BaselineTestSetHash) { return PreparedBug{}, provider.ErrContract } p.Repository = target.Repository p.DefaultBranch = target.DefaultRef p.BaseCommit = base p.CheckDefinition = bytes.Clone(p.CheckDefinition) return p, nil } func selection(a runnerproto.Assignment) provider.Selection { s := a.Selection return provider.Selection{ConnectionID: s.ConnectionID, Provider: s.Provider, Family: s.Family, Model: s.Model, AccountID: s.AccountID} } func (m *Manager) preflight(ctx context.Context, a runnerproto.Assignment) (provider.ReadPolicy, error) { s := selection(a) p, e := m.cfg.Policy(ctx, s) if e != nil { return p, provider.ErrPolicy } p.DeniedPaths = append([]string(nil), p.DeniedPaths...) for _, protected := range append(m.cfg.Protected.all(), m.cfg.PrivateRoot) { resolved, e := canonical(protected) if e != nil { return p, provider.ErrPolicy } for _, path := range []string{protected, resolved} { covered := false for _, d := range p.DeniedPaths { if !filepath.IsAbs(d) || filepath.Clean(d) != d { return p, provider.ErrPolicy } if contains(d, path) { covered = true } } if !covered { return p, provider.ErrPolicy } } } if !allowed(m.cfg.WorkspaceRoot, p) { return p, provider.ErrPolicy } return p, nil } func save(path string, v any) error { b, e := json.Marshal(v) if e != nil { return provider.ErrContract } f, e := os.CreateTemp(filepath.Dir(path), ".receipt-") if e != nil { return provider.ErrContract } name := f.Name() defer os.Remove(name) if _, e = f.Write(b); e == nil { e = f.Sync() } closeErr := f.Close() if e != nil || closeErr != nil { return provider.ErrContract } if os.Rename(name, path) != nil { return provider.ErrContract } d, e := os.Open(filepath.Dir(path)) if e != nil { return provider.ErrContract } defer d.Close() if d.Sync() != nil { return provider.ErrContract } return nil } func load(path string, v any) error { b, e := os.ReadFile(path) if e != nil { return e } if json.Unmarshal(b, v) != nil { return provider.ErrContract } return nil } func (m *Manager) Create(ctx context.Context, a runnerproto.Assignment, brief runnerproto.RunnerBrief) (Workspace, error) { m.mu.Lock() defer m.mu.Unlock() var zero Workspace if brief.Target.Kind == team.TargetProjectRead || brief.Step.Action == "scope" { return m.createRead(ctx, a, brief) } if a.ID == "" || a.TaskID == "" || a.WorkspaceKey == "" || a.StepKey == "" || !reflect.DeepEqual(a.Selection, brief.Selection) || !m.validTarget(ctx, brief.Target, true) { return zero, provider.ErrContract } if a.StepKey == "implement" && len(brief.ArtifactHashes) == 0 { return zero, provider.ErrContract } for _, h := range brief.ArtifactHashes { if len(h) != 64 || !objectID.MatchString(h) { return zero, provider.ErrContract } } policy, err := m.preflight(ctx, a) if err != nil { return zero, err } hash := digest(struct { Assignment runnerproto.Assignment Brief runnerproto.RunnerBrief Policy provider.ReadPolicy }{a, brief, policy}) dir := filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(a.WorkspaceKey)) record := filepath.Join(dir, "attempt.json") var at attempt err = load(record, &at) if os.IsNotExist(err) { if err = os.Mkdir(dir, 0700); err != nil { return zero, provider.ErrUncertain } repo, _, e := m.fetch(ctx, brief.Target) if e != nil { return zero, e } source := filepath.Join(m.cfg.WorkspaceRoot, "source-"+digest(a.WorkspaceKey)) if !allowed(source, policy) { return zero, provider.ErrPolicy } if _, e := os.Lstat(source); !os.IsNotExist(e) { return zero, provider.ErrUncertain } if e = m.init(ctx, source, objectFormat(brief.Target.BaseRevision), false); e != nil { return zero, e } if e = copyObjects(filepath.Join(repo, "objects"), filepath.Join(source, ".git", "objects")); e != nil { return zero, e } if _, e = m.run(ctx, source, "checkout", "--detach", brief.Target.BaseRevision); e != nil { return zero, e } { path := filepath.Join(m.cfg.WorkspaceRoot, "attempt-"+digest(a.WorkspaceKey)) if _, e = m.run(ctx, source, "worktree", "add", "-b", brief.Target.Ref, path, brief.Target.BaseRevision); e != nil { return zero, e } // Detach the worktree metadata from the source before exposing the checkout. gitfile, e := regular(filepath.Join(path, ".git")) if e != nil { return zero, e } metadata := strings.TrimSpace(strings.TrimPrefix(string(gitfile), "gitdir: ")) index, e := regular(filepath.Join(metadata, "index")) if e != nil { return zero, e } if e = os.Remove(filepath.Join(path, ".git")); e != nil { return zero, e } if e = m.init(ctx, path, objectFormat(brief.Target.BaseRevision), false); e != nil { return zero, e } if e = copyObjects(filepath.Join(source, ".git", "objects"), filepath.Join(path, ".git", "objects")); e != nil { return zero, e } if _, e = m.run(ctx, path, "symbolic-ref", "HEAD", "refs/heads/"+brief.Target.Ref); e != nil { return zero, e } if _, e = m.run(ctx, path, "update-ref", "refs/heads/"+brief.Target.Ref, brief.Target.BaseRevision); e != nil { return zero, e } if e = os.WriteFile(filepath.Join(path, ".git", "index"), index, 0600); e != nil { return zero, e } config, e := regular(filepath.Join(path, ".git", "config")) if e != nil { return zero, e } at = attempt{Local: true, ConfigHash: digest(config), AssignmentHash: digest(a), Hash: hash, Request: provider.WorkspaceRequest{Path: path, ReadPolicy: policy}, Workspace: provider.Workspace{WorkspaceID: a.WorkspaceKey, Path: path}, Target: brief.Target, ArtifactHashes: append([]string(nil), brief.ArtifactHashes...), Isolation: a.Selection.Isolation} if e = m.validateWorkspace(at); e != nil { return zero, e } if e = save(record, at); e != nil { return zero, e } if e = os.RemoveAll(source); e != nil { return zero, e } return localWorkspace(at, a.WorkspaceKey), nil } } else if err != nil { return zero, provider.ErrUncertain } if at.Hash != hash { return zero, provider.ErrIdentity } if !at.Local || at.Workspace.WorkspaceID == "" { return zero, provider.ErrIdentity } if err = m.validateWorkspace(at); err != nil { return zero, err } return localWorkspace(at, a.WorkspaceKey), nil } func regular(path string) ([]byte, error) { s, e := os.Lstat(path) if e != nil || !s.Mode().IsRegular() { return nil, provider.ErrIdentity } b, e := os.ReadFile(path) if e != nil { return nil, provider.ErrIdentity } return b, nil } func localWorkspace(at attempt, key string) Workspace { return Workspace{Record: at.Workspace, ID: at.Workspace.WorkspaceID, Path: at.Workspace.Path, ArtifactHashes: append([]string(nil), at.ArtifactHashes...), Isolation: at.Isolation, key: key} } func (m *Manager) gitdir(at attempt) (string, error) { if !at.Local { return "", provider.ErrIdentity } return m.localGitdir(at) } func (m *Manager) validateWorkspace(at attempt) error { if at.ReadOnly { return validateRead(at) } for _, p := range []string{at.Workspace.Path, at.Request.Path, filepath.Join(at.Request.Path, ".git")} { r, e := canonical(p) if e != nil || r != p || !allowed(p, at.Request.ReadPolicy) { return provider.ErrPolicy } } _, e := m.gitdir(at) return e } func (m *Manager) head(at attempt) (string, error) { dir, e := m.gitdir(at) if e != nil { return "", e } b, e := regular(filepath.Join(dir, "HEAD")) ref := "refs/heads/" + at.Target.Ref if e != nil || strings.TrimSpace(string(b)) != "ref: "+ref { return "", provider.ErrIdentity } common := filepath.Join(at.Request.Path, ".git") p := filepath.Join(common, ref) resolved, e := canonical(p) if e != nil || resolved != p { return "", provider.ErrIdentity } b, e = regular(p) if e == nil { id := strings.TrimSpace(string(b)) if objectID.MatchString(id) { return id, nil } return "", provider.ErrIdentity } b, e = regular(filepath.Join(common, "packed-refs")) if e != nil { return "", e } for _, line := range strings.Split(string(b), "\n") { parts := strings.Split(line, " ") if len(parts) == 2 && parts[1] == ref && objectID.MatchString(parts[0]) { return parts[0], nil } } return "", provider.ErrIdentity } func copyObjects(from, to string) error { return filepath.WalkDir(from, func(p string, d os.DirEntry, err error) error { if err != nil { return provider.ErrIdentity } rel, e := filepath.Rel(from, p) if e != nil || d.Type()&os.ModeSymlink != 0 { return provider.ErrIdentity } if d.IsDir() { if rel != "." && rel != "info" && rel != "pack" && !(len(rel) == 2 && strings.Trim(rel, "0123456789abcdef") == "") { return provider.ErrIdentity } if os.MkdirAll(filepath.Join(to, rel), 0700) != nil { return provider.ErrContract } return nil } if !d.Type().IsRegular() { return provider.ErrIdentity } parts := strings.Split(rel, string(filepath.Separator)) valid := len(parts) == 2 && ((len(parts[0]) == 2 && objectID.MatchString(parts[0]+parts[1])) || (parts[0] == "pack" && packFile.MatchString(parts[1]))) if !valid { return provider.ErrIdentity } in, e := os.Open(p) if e != nil { return provider.ErrIdentity } defer in.Close() out, e := os.OpenFile(filepath.Join(to, rel), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) if e != nil { return provider.ErrContract } _, e = io.Copy(out, in) closeErr := out.Close() if e != nil || closeErr != nil { return provider.ErrContract } return nil }) } func (m *Manager) clean(ctx context.Context, repo, path, commit string) error { b, e := m.git(ctx, repo, nil, nil, "ls-tree", "-rz", "--full-tree", commit) if e != nil { return e } type entry struct{ mode, id string } tracked := map[string]entry{} dirs := map[string]bool{} for _, item := range bytes.Split(b, []byte{0}) { if len(item) == 0 { continue } parts := bytes.SplitN(item, []byte{'\t'}, 2) if len(parts) != 2 { return provider.ErrIdentity } fields := strings.Fields(string(parts[0])) name := string(parts[1]) if len(fields) != 3 || fields[1] != "blob" || filepath.Clean(name) != name || filepath.IsAbs(name) || name == ".git" || strings.HasPrefix(name, "../") { return provider.ErrIdentity } tracked[name] = entry{fields[0], fields[2]} for d := filepath.Dir(name); d != "."; d = filepath.Dir(d) { dirs[d] = true } } seen := 0 e = filepath.WalkDir(path, func(p string, d os.DirEntry, err error) error { if err != nil { return provider.ErrIdentity } rel, e := filepath.Rel(path, p) if e != nil { return provider.ErrIdentity } if rel == "." { return nil } if rel == ".git" { if d.IsDir() { return filepath.SkipDir } return nil } if d.IsDir() { if !dirs[rel] { return provider.ErrIdentity } return nil } ent, ok := tracked[rel] if !ok { return provider.ErrIdentity } var data []byte switch ent.mode { case "120000": if d.Type()&os.ModeSymlink == 0 { return provider.ErrIdentity } link, e := os.Readlink(p) if e != nil || filepath.IsAbs(link) { return provider.ErrIdentity } resolved, e := canonical(filepath.Clean(filepath.Join(filepath.Dir(p), link))) if e != nil || !contains(path, resolved) { return provider.ErrIdentity } data = []byte(link) case "100644", "100755": if !d.Type().IsRegular() { return provider.ErrIdentity } s, e := d.Info() if e != nil || ((s.Mode()&0111) != 0) != (ent.mode == "100755") { return provider.ErrIdentity } data, e = os.ReadFile(p) if e != nil { return provider.ErrIdentity } default: return provider.ErrIdentity } framed := append([]byte(fmt.Sprintf("blob %d\x00", len(data))), data...) id := "" if len(ent.id) == 40 { s := sha1.Sum(framed) id = hex.EncodeToString(s[:]) } else { s := sha256.Sum256(framed) id = hex.EncodeToString(s[:]) } if id != ent.id { return provider.ErrIdentity } seen++ return nil }) if e != nil || seen != len(tracked) { return provider.ErrIdentity } return nil } func (m *Manager) CaptureCandidate(ctx context.Context, w Workspace, target team.TargetBinding) (GitCandidate, error) { m.mu.Lock() defer m.mu.Unlock() var zero GitCandidate var at attempt if w.key == "" || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Record || (at.Local && (w.ID != at.Workspace.WorkspaceID || w.Path != at.Workspace.Path)) || at.Target != target { return zero, provider.ErrIdentity } if e := m.validateWorkspace(at); e != nil { return zero, e } commit, e := m.head(at) if e != nil { return zero, e } staging, e := os.MkdirTemp(m.cfg.PrivateRoot, "capture-") if e != nil { return zero, provider.ErrContract } defer os.RemoveAll(staging) if e = m.init(ctx, staging, objectFormat(target.BaseRevision), true); e != nil { return zero, e } if e = copyObjects(filepath.Join(at.Request.Path, ".git", "objects"), filepath.Join(staging, "objects")); e != nil { return zero, e } if _, e = m.run(ctx, staging, "merge-base", "--is-ancestor", target.BaseRevision, commit); e != nil { return zero, provider.ErrIdentity } tree, e := m.run(ctx, staging, "rev-parse", "--verify", commit+"^{tree}") if e != nil || !objectID.MatchString(tree) { return zero, provider.ErrIdentity } gitdir, e := m.gitdir(at) if e != nil { return zero, e } index, e := regular(filepath.Join(gitdir, "index")) if e != nil { return zero, e } if os.WriteFile(filepath.Join(staging, "index"), index, 0600) != nil { return zero, provider.ErrContract } if _, e = m.run(ctx, staging, "diff-index", "--cached", "--quiet", "--no-ext-diff", "--no-textconv", commit, "--"); e != nil { return zero, provider.ErrIdentity } if e = m.clean(ctx, staging, w.Path, commit); e != nil { return zero, e } again, e := m.head(at) if e != nil || again != commit { return zero, provider.ErrIdentity } c := GitCandidate{Repository: target.Repository, BaseCommit: target.BaseRevision, Commit: commit, Tree: tree} if _, e = m.run(ctx, staging, "update-ref", "refs/heads/candidate", commit); e != nil { return zero, e } if _, e = m.run(ctx, staging, "fsck", "--strict", "--no-reflogs"); e != nil { return zero, provider.ErrIdentity } if _, e = m.run(ctx, staging, "-c", "core.fsync=all", "-c", "repack.writeBitmaps=false", "repack", "-adn"); e != nil { return zero, e } entries, e := os.ReadDir(filepath.Join(staging, "objects")) if e != nil { return zero, provider.ErrContract } for _, entry := range entries { if len(entry.Name()) == 2 && strings.Trim(entry.Name(), "0123456789abcdef") == "" { if os.RemoveAll(filepath.Join(staging, "objects", entry.Name())) != nil { return zero, provider.ErrContract } } } destination := filepath.Join(m.cfg.PrivateRoot, "candidate-"+digest(c)) if _, e = os.Stat(destination); e == nil { var saved GitCandidate if load(filepath.Join(destination, "candidate.json"), &saved) != nil || saved != c { return zero, provider.ErrIdentity } return c, nil } if e = save(filepath.Join(staging, "candidate.json"), c); e != nil { return zero, e } if os.Rename(staging, destination) != nil { return zero, provider.ErrContract } parent, e := os.Open(m.cfg.PrivateRoot) if e != nil { return zero, provider.ErrUncertain } defer parent.Close() if parent.Sync() != nil { return zero, provider.ErrUncertain } return c, nil } func (m *Manager) ExportCandidate(ctx context.Context, c GitCandidate, destination string) error { m.mu.Lock() defer m.mu.Unlock() source := filepath.Join(m.cfg.PrivateRoot, "candidate-"+digest(c)) var saved GitCandidate if load(filepath.Join(source, "candidate.json"), &saved) != nil || saved != c { return provider.ErrIdentity } r, e := canonical(destination) if e != nil || r != destination || !allowed(destination, provider.ReadPolicy{ConfigHash: "export", DeniedPaths: append(m.cfg.Protected.all(), m.cfg.PrivateRoot)}) { return provider.ErrPolicy } if _, e = os.Lstat(destination); !os.IsNotExist(e) { return provider.ErrIdentity } if e = os.Mkdir(destination, 0700); e != nil { return provider.ErrContract } ok := false defer func() { if !ok { _ = os.RemoveAll(destination) } }() if e = m.init(ctx, destination, objectFormat(c.Commit), false); e != nil { return e } if e = copyObjects(filepath.Join(source, "objects"), filepath.Join(destination, ".git", "objects")); e != nil { return e } tree, e := m.run(ctx, destination, "rev-parse", c.Commit+"^{tree}") if e != nil || tree != c.Tree { return provider.ErrIdentity } if _, e = m.run(ctx, destination, "checkout", "--detach", c.Commit); e != nil { return e } if e = m.clean(ctx, destination, destination, c.Commit); e != nil { return e } ok = true return nil } func (m *Manager) ValidateTurn(ctx context.Context, a runnerproto.Assignment, w Workspace) error { m.mu.Lock() defer m.mu.Unlock() var at attempt if w.key == "" || w.key != a.WorkspaceKey || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Record || (at.Local && (w.ID != at.Workspace.WorkspaceID || w.Path != at.Workspace.Path)) || at.AssignmentHash != digest(a) { return provider.ErrIdentity } policy, err := m.preflight(ctx, a) if err != nil { return err } if !reflect.DeepEqual(policy, at.Request.ReadPolicy) { return provider.ErrPolicy } return m.validateWorkspace(at) } // CheckoutCandidate installs only a previously captured immutable candidate in // a fresh review workspace before any agent is created. func (m *Manager) CheckoutCandidate(ctx context.Context, w Workspace, c GitCandidate) error { return m.ContinueCandidate(ctx, w, c, false) } func (m *Manager) ContinueCandidate(ctx context.Context, w Workspace, c GitCandidate, build bool) error { m.mu.Lock() defer m.mu.Unlock() var at attempt if w.key == "" || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Record || (at.Local && (w.ID != at.Workspace.WorkspaceID || w.Path != at.Workspace.Path)) || at.Target.Repository != c.Repository || at.Target.BaseRevision != c.BaseCommit { return provider.ErrIdentity } if err := m.validateWorkspace(at); err != nil { return err } source := filepath.Join(m.cfg.PrivateRoot, "candidate-"+digest(c)) var saved GitCandidate if load(filepath.Join(source, "candidate.json"), &saved) != nil || saved != c { return provider.ErrIdentity } if err := copyObjects(filepath.Join(source, "objects"), filepath.Join(at.Request.Path, ".git", "objects")); err != nil { return err } args := []string{"checkout", "--detach", c.Commit} if build { args = []string{"checkout", "-B", at.Target.Ref, c.Commit} } if _, err := m.run(ctx, w.Path, args...); err != nil { return err } tree, err := m.run(ctx, w.Path, "rev-parse", "HEAD^{tree}") if err != nil || tree != c.Tree { return provider.ErrIdentity } return m.clean(ctx, at.Request.Path, w.Path, c.Commit) } func (m *Manager) PreparationDirectory() string { return m.cfg.PrivateRoot }