| 1 | package workspace |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha1" |
| 7 | "crypto/sha256" |
| 8 | "encoding/base64" |
| 9 | "encoding/hex" |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "net/url" |
| 15 | "os" |
| 16 | "os/exec" |
| 17 | "path/filepath" |
| 18 | "reflect" |
| 19 | "regexp" |
| 20 | "strings" |
| 21 | "sync" |
| 22 | |
| 23 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 24 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 25 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 26 | ) |
| 27 | |
| 28 | type PreparedBug = runnerproto.PreparedBug |
| 29 | type GitCandidate = team.GitCandidate |
| 30 | type Remote struct{ URL, GitPassword, GitUsername string } |
| 31 | |
| 32 | // Username preserves the hub's historical Basic authentication user. |
| 33 | func (r Remote) Username() string { |
| 34 | if r.GitUsername == "" { |
| 35 | return "x" |
| 36 | } |
| 37 | return r.GitUsername |
| 38 | } |
| 39 | |
| 40 | var ErrGitPassword = errors.New("configure a repository git password (PAT) in EQUIPO_AMADAN_CREDENTIAL_PATH") |
| 41 | |
| 42 | // ErrHubUnavailable: the forge could not be asked whether the agent may |
| 43 | // write to the repository now (no answer, an error status, an unreadable |
| 44 | // list). Nothing was sent; unlike a denial, it is worth trying again. |
| 45 | var ErrHubUnavailable = errors.New("the forge could not be reached to confirm write access; nothing was sent") |
| 46 | |
| 47 | type ForgeRead interface { |
| 48 | Resolve(context.Context, string) (Remote, error) |
| 49 | } |
| 50 | type SecurityPaths struct { |
| 51 | RunnerState, RunnerConfig, Journal, Bearer, Cleanup, ForgeCredential, LegacyHome, SSH string |
| 52 | ProviderHomes []string |
| 53 | // PreviewCredential is the preview credential file, "" when previews |
| 54 | // are off. |
| 55 | PreviewCredential string |
| 56 | } |
| 57 | |
| 58 | func (p SecurityPaths) all() []string { |
| 59 | return append(p.Credentials(), p.ProviderHomes...) |
| 60 | } |
| 61 | |
| 62 | // Credentials are the protected single paths: never mounted into, or |
| 63 | // read from, a sandbox. The preview credential only when set. |
| 64 | func (p SecurityPaths) Credentials() []string { |
| 65 | out := []string{p.RunnerState, p.RunnerConfig, p.Journal, p.Bearer, p.Cleanup, p.ForgeCredential, p.LegacyHome, p.SSH} |
| 66 | if p.PreviewCredential != "" { |
| 67 | out = append(out, p.PreviewCredential) |
| 68 | } |
| 69 | return out |
| 70 | } |
| 71 | |
| 72 | type Config struct { |
| 73 | Protected SecurityPaths |
| 74 | PrivateRoot, WorkspaceRoot, GitPath string |
| 75 | Forge ForgeRead |
| 76 | Policy func(context.Context, provider.Selection) (provider.ReadPolicy, error) |
| 77 | Definitions func(context.Context, team.TargetBinding, string) (PreparedBug, error) |
| 78 | } |
| 79 | type Manager struct { |
| 80 | cfg Config |
| 81 | mu sync.Mutex |
| 82 | } |
| 83 | type Workspace struct { |
| 84 | ID, Path string |
| 85 | Record provider.Workspace |
| 86 | ArtifactHashes []string |
| 87 | Isolation team.IsolationSnapshot |
| 88 | key string |
| 89 | } |
| 90 | type attempt struct { |
| 91 | ReadOnly bool |
| 92 | ContentHash string |
| 93 | Local bool |
| 94 | ConfigHash string |
| 95 | AssignmentHash string |
| 96 | Hash string |
| 97 | Request provider.WorkspaceRequest |
| 98 | Workspace provider.Workspace |
| 99 | Target team.TargetBinding |
| 100 | ArtifactHashes []string |
| 101 | Isolation team.IsolationSnapshot |
| 102 | } |
| 103 | |
| 104 | var objectID = regexp.MustCompile(`^(?:[a-f0-9]{40}|[a-f0-9]{64})$`) |
| 105 | var packFile = regexp.MustCompile(`^pack-[a-f0-9]{40}(?:[a-f0-9]{24})?\.(pack|idx|rev)$`) |
| 106 | |
| 107 | func New(cfg Config) (*Manager, error) { |
| 108 | return newManager(cfg) |
| 109 | } |
| 110 | func newManager(cfg Config) (*Manager, error) { |
| 111 | if cfg.Forge == nil || cfg.Policy == nil || cfg.Definitions == nil || !filepath.IsAbs(cfg.GitPath) { |
| 112 | return nil, provider.ErrContract |
| 113 | } |
| 114 | for _, p := range []string{cfg.PrivateRoot, cfg.WorkspaceRoot} { |
| 115 | if !filepath.IsAbs(p) || filepath.Clean(p) != p { |
| 116 | return nil, provider.ErrPolicy |
| 117 | } |
| 118 | } |
| 119 | if contains(cfg.PrivateRoot, cfg.WorkspaceRoot) || contains(cfg.WorkspaceRoot, cfg.PrivateRoot) { |
| 120 | return nil, provider.ErrPolicy |
| 121 | } |
| 122 | if len(cfg.Protected.ProviderHomes) == 0 { |
| 123 | return nil, provider.ErrPolicy |
| 124 | } |
| 125 | cfg.Protected.ProviderHomes = append([]string(nil), cfg.Protected.ProviderHomes...) |
| 126 | for _, p := range cfg.Protected.all() { |
| 127 | if _, e := canonical(p); e != nil { |
| 128 | return nil, provider.ErrPolicy |
| 129 | } |
| 130 | } |
| 131 | for _, p := range []string{cfg.PrivateRoot, cfg.WorkspaceRoot} { |
| 132 | if resolved, e := canonical(p); e != nil || resolved != p { |
| 133 | return nil, provider.ErrPolicy |
| 134 | } |
| 135 | if err := os.MkdirAll(p, 0700); err != nil { |
| 136 | return nil, provider.ErrPolicy |
| 137 | } |
| 138 | info, err := os.Stat(p) |
| 139 | if err != nil || info.Mode().Perm()&0077 != 0 { |
| 140 | return nil, provider.ErrPolicy |
| 141 | } |
| 142 | resolved, err := filepath.EvalSymlinks(p) |
| 143 | if err != nil || resolved != p { |
| 144 | return nil, provider.ErrPolicy |
| 145 | } |
| 146 | } |
| 147 | return &Manager{cfg: cfg}, nil |
| 148 | } |
| 149 | func digest(v any) string { |
| 150 | b, _ := json.Marshal(v) |
| 151 | s := sha256.Sum256(b) |
| 152 | return hex.EncodeToString(s[:]) |
| 153 | } |
| 154 | func contains(root, p string) bool { |
| 155 | rel, e := filepath.Rel(root, p) |
| 156 | return e == nil && (rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))) |
| 157 | } |
| 158 | func canonical(p string) (string, error) { |
| 159 | if !filepath.IsAbs(p) || filepath.Clean(p) != p { |
| 160 | return "", provider.ErrPolicy |
| 161 | } |
| 162 | tail := "" |
| 163 | for ancestor := p; ; ancestor = filepath.Dir(ancestor) { |
| 164 | r, e := filepath.EvalSymlinks(ancestor) |
| 165 | if e == nil { |
| 166 | return filepath.Join(r, tail), nil |
| 167 | } |
| 168 | if !os.IsNotExist(e) || ancestor == filepath.Dir(ancestor) { |
| 169 | return "", provider.ErrPolicy |
| 170 | } |
| 171 | tail = filepath.Join(filepath.Base(ancestor), tail) |
| 172 | } |
| 173 | } |
| 174 | func allowed(p string, policy provider.ReadPolicy) bool { |
| 175 | r, e := canonical(p) |
| 176 | if e != nil || policy.ConfigHash == "" || len(policy.DeniedPaths) == 0 { |
| 177 | return false |
| 178 | } |
| 179 | for _, deny := range policy.DeniedPaths { |
| 180 | d, e := canonical(deny) |
| 181 | if e != nil || contains(d, r) { |
| 182 | return false |
| 183 | } |
| 184 | } |
| 185 | return true |
| 186 | } |
| 187 | func safeEnv() map[string]string { |
| 188 | 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"} |
| 189 | } |
| 190 | func GitEnvironment() map[string]string { return safeEnv() } |
| 191 | func (w Workspace) Environment() map[string]string { return GitEnvironment() } |
| 192 | func (m *Manager) git(ctx context.Context, dir string, input []byte, extra map[string]string, args ...string) ([]byte, error) { |
| 193 | cmd := exec.CommandContext(ctx, m.cfg.GitPath, args...) |
| 194 | cmd.Dir = dir |
| 195 | env := safeEnv() |
| 196 | env["HOME"] = "/nonexistent" |
| 197 | for k, v := range extra { |
| 198 | env[k] = v |
| 199 | } |
| 200 | for k, v := range env { |
| 201 | cmd.Env = append(cmd.Env, k+"="+v) |
| 202 | } |
| 203 | cmd.Stdin = bytes.NewReader(input) |
| 204 | cmd.Stderr = io.Discard |
| 205 | b, err := cmd.Output() |
| 206 | if err != nil { |
| 207 | return nil, provider.ErrContract |
| 208 | } |
| 209 | return b, nil |
| 210 | } |
| 211 | func (m *Manager) run(ctx context.Context, dir string, args ...string) (string, error) { |
| 212 | b, e := m.git(ctx, dir, nil, nil, args...) |
| 213 | return strings.TrimSpace(string(b)), e |
| 214 | } |
| 215 | func (m *Manager) validTarget(ctx context.Context, t team.TargetBinding, base bool) bool { |
| 216 | 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) { |
| 217 | return false |
| 218 | } |
| 219 | for _, r := range []string{t.Ref, t.DefaultRef} { |
| 220 | if r == "" || r == "HEAD" || r == "@" || strings.HasPrefix(r, "refs/") || strings.HasPrefix(r, "-") { |
| 221 | return false |
| 222 | } |
| 223 | if _, e := m.run(ctx, m.cfg.PrivateRoot, "check-ref-format", "refs/heads/"+r); e != nil { |
| 224 | return false |
| 225 | } |
| 226 | } |
| 227 | return true |
| 228 | } |
| 229 | func (m *Manager) init(ctx context.Context, dir, format string, bare bool) error { |
| 230 | args := []string{"init", "--template=", "--object-format=" + format} |
| 231 | if bare { |
| 232 | args = append(args, "--bare") |
| 233 | } |
| 234 | args = append(args, dir) |
| 235 | if _, e := m.run(ctx, m.cfg.PrivateRoot, args...); e != nil { |
| 236 | return e |
| 237 | } |
| 238 | for _, kv := range [][2]string{{"core.hooksPath", "/dev/null"}, {"credential.helper", ""}, {"core.fsmonitor", "false"}, {"core.attributesFile", "/dev/null"}, {"protocol.allow", "never"}, {"commit.gpgSign", "false"}} { |
| 239 | if _, e := m.run(ctx, dir, "config", "--local", kv[0], kv[1]); e != nil { |
| 240 | return e |
| 241 | } |
| 242 | } |
| 243 | return nil |
| 244 | } |
| 245 | func objectFormat(id string) string { |
| 246 | if len(id) == 64 { |
| 247 | return "sha256" |
| 248 | } |
| 249 | return "sha1" |
| 250 | } |
| 251 | func (m *Manager) fetch(ctx context.Context, t team.TargetBinding) (string, string, error) { |
| 252 | remote, err := m.cfg.Forge.Resolve(ctx, t.Repository) |
| 253 | if errors.Is(err, ErrGitPassword) { |
| 254 | return "", "", ErrGitPassword |
| 255 | } |
| 256 | if err != nil { |
| 257 | return "", "", provider.ErrContract |
| 258 | } |
| 259 | protocol := "" |
| 260 | if filepath.IsAbs(remote.URL) { |
| 261 | r, e := canonical(remote.URL) |
| 262 | if e != nil || r != remote.URL || remote.GitPassword != "" { |
| 263 | return "", "", provider.ErrPolicy |
| 264 | } |
| 265 | protocol = "file" |
| 266 | } else { |
| 267 | u, e := url.Parse(remote.URL) |
| 268 | if e != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || strings.ContainsAny(remote.URL+remote.GitPassword, "\r\n\x00") { |
| 269 | return "", "", provider.ErrPolicy |
| 270 | } |
| 271 | if remote.GitPassword == "" { |
| 272 | return "", "", ErrGitPassword |
| 273 | } |
| 274 | protocol = "https" |
| 275 | } |
| 276 | repo := filepath.Join(m.cfg.PrivateRoot, "project-"+digest(t.Repository)) |
| 277 | if _, err := os.Stat(repo); os.IsNotExist(err) { |
| 278 | if err = m.init(ctx, repo, objectFormat(t.BaseRevision), true); err != nil { |
| 279 | return "", "", err |
| 280 | } |
| 281 | } else if err != nil { |
| 282 | return "", "", provider.ErrContract |
| 283 | } |
| 284 | ref := t.BaseRevision |
| 285 | if ref == "" { |
| 286 | ref = "refs/heads/" + t.DefaultRef |
| 287 | } |
| 288 | env := map[string]string{} |
| 289 | if remote.GitPassword != "" { |
| 290 | env["GIT_CONFIG_COUNT"] = "10" |
| 291 | env["GIT_CONFIG_KEY_9"] = "http.extraHeader" |
| 292 | env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(remote.Username()+":"+remote.GitPassword)) |
| 293 | } |
| 294 | 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 { |
| 295 | return "", "", err |
| 296 | } |
| 297 | base, err := m.run(ctx, repo, "rev-parse", "--verify", "FETCH_HEAD^{commit}") |
| 298 | if err != nil || !objectID.MatchString(base) || t.BaseRevision != "" && base != t.BaseRevision { |
| 299 | return "", "", provider.ErrIdentity |
| 300 | } |
| 301 | return repo, base, nil |
| 302 | } |
| 303 | func (m *Manager) Prepare(ctx context.Context, target team.TargetBinding) (PreparedBug, error) { |
| 304 | m.mu.Lock() |
| 305 | defer m.mu.Unlock() |
| 306 | if !m.validTarget(ctx, target, target.BaseRevision != "") { |
| 307 | return PreparedBug{}, provider.ErrContract |
| 308 | } |
| 309 | repo, base, err := m.fetch(ctx, target) |
| 310 | if err != nil { |
| 311 | return PreparedBug{}, err |
| 312 | } |
| 313 | target.BaseRevision = base |
| 314 | p, err := m.cfg.Definitions(ctx, target, repo) |
| 315 | if err != nil { |
| 316 | return PreparedBug{}, fmt.Errorf("%w: preparation definition/baseline: %w", provider.ErrContract, err) |
| 317 | } |
| 318 | s := sha256.Sum256(p.CheckDefinition) |
| 319 | if len(p.CheckDefinition) == 0 || len(p.CheckDefinition) > team.MaxArtifactBytes || hex.EncodeToString(s[:]) != p.CheckDefinitionHash || len(p.BaselineTestSetHash) != 64 || !objectID.MatchString(p.BaselineTestSetHash) { |
| 320 | return PreparedBug{}, provider.ErrContract |
| 321 | } |
| 322 | p.Repository = target.Repository |
| 323 | p.DefaultBranch = target.DefaultRef |
| 324 | p.BaseCommit = base |
| 325 | p.CheckDefinition = bytes.Clone(p.CheckDefinition) |
| 326 | return p, nil |
| 327 | } |
| 328 | func selection(a runnerproto.Assignment) provider.Selection { |
| 329 | s := a.Selection |
| 330 | return provider.Selection{ConnectionID: s.ConnectionID, Provider: s.Provider, Family: s.Family, Model: s.Model, AccountID: s.AccountID} |
| 331 | } |
| 332 | func (m *Manager) preflight(ctx context.Context, a runnerproto.Assignment) (provider.ReadPolicy, error) { |
| 333 | s := selection(a) |
| 334 | p, e := m.cfg.Policy(ctx, s) |
| 335 | if e != nil { |
| 336 | return p, provider.ErrPolicy |
| 337 | } |
| 338 | p.DeniedPaths = append([]string(nil), p.DeniedPaths...) |
| 339 | for _, protected := range append(m.cfg.Protected.all(), m.cfg.PrivateRoot) { |
| 340 | resolved, e := canonical(protected) |
| 341 | if e != nil { |
| 342 | return p, provider.ErrPolicy |
| 343 | } |
| 344 | for _, path := range []string{protected, resolved} { |
| 345 | covered := false |
| 346 | for _, d := range p.DeniedPaths { |
| 347 | if !filepath.IsAbs(d) || filepath.Clean(d) != d { |
| 348 | return p, provider.ErrPolicy |
| 349 | } |
| 350 | if contains(d, path) { |
| 351 | covered = true |
| 352 | } |
| 353 | } |
| 354 | if !covered { |
| 355 | return p, provider.ErrPolicy |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | if !allowed(m.cfg.WorkspaceRoot, p) { |
| 360 | return p, provider.ErrPolicy |
| 361 | } |
| 362 | return p, nil |
| 363 | } |
| 364 | func save(path string, v any) error { |
| 365 | b, e := json.Marshal(v) |
| 366 | if e != nil { |
| 367 | return provider.ErrContract |
| 368 | } |
| 369 | f, e := os.CreateTemp(filepath.Dir(path), ".receipt-") |
| 370 | if e != nil { |
| 371 | return provider.ErrContract |
| 372 | } |
| 373 | name := f.Name() |
| 374 | defer os.Remove(name) |
| 375 | if _, e = f.Write(b); e == nil { |
| 376 | e = f.Sync() |
| 377 | } |
| 378 | closeErr := f.Close() |
| 379 | if e != nil || closeErr != nil { |
| 380 | return provider.ErrContract |
| 381 | } |
| 382 | if os.Rename(name, path) != nil { |
| 383 | return provider.ErrContract |
| 384 | } |
| 385 | d, e := os.Open(filepath.Dir(path)) |
| 386 | if e != nil { |
| 387 | return provider.ErrContract |
| 388 | } |
| 389 | defer d.Close() |
| 390 | if d.Sync() != nil { |
| 391 | return provider.ErrContract |
| 392 | } |
| 393 | return nil |
| 394 | } |
| 395 | func load(path string, v any) error { |
| 396 | b, e := os.ReadFile(path) |
| 397 | if e != nil { |
| 398 | return e |
| 399 | } |
| 400 | if json.Unmarshal(b, v) != nil { |
| 401 | return provider.ErrContract |
| 402 | } |
| 403 | return nil |
| 404 | } |
| 405 | func (m *Manager) Create(ctx context.Context, a runnerproto.Assignment, brief runnerproto.RunnerBrief) (Workspace, error) { |
| 406 | m.mu.Lock() |
| 407 | defer m.mu.Unlock() |
| 408 | var zero Workspace |
| 409 | if brief.Target.Kind == team.TargetProjectRead || brief.Step.Action == "scope" { |
| 410 | return m.createRead(ctx, a, brief) |
| 411 | } |
| 412 | if a.ID == "" || a.TaskID == "" || a.WorkspaceKey == "" || a.StepKey == "" || !reflect.DeepEqual(a.Selection, brief.Selection) || !m.validTarget(ctx, brief.Target, true) { |
| 413 | return zero, provider.ErrContract |
| 414 | } |
| 415 | if a.StepKey == "implement" && len(brief.ArtifactHashes) == 0 { |
| 416 | return zero, provider.ErrContract |
| 417 | } |
| 418 | for _, h := range brief.ArtifactHashes { |
| 419 | if len(h) != 64 || !objectID.MatchString(h) { |
| 420 | return zero, provider.ErrContract |
| 421 | } |
| 422 | } |
| 423 | policy, err := m.preflight(ctx, a) |
| 424 | if err != nil { |
| 425 | return zero, err |
| 426 | } |
| 427 | hash := digest(struct { |
| 428 | Assignment runnerproto.Assignment |
| 429 | Brief runnerproto.RunnerBrief |
| 430 | Policy provider.ReadPolicy |
| 431 | }{a, brief, policy}) |
| 432 | dir := filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(a.WorkspaceKey)) |
| 433 | record := filepath.Join(dir, "attempt.json") |
| 434 | var at attempt |
| 435 | err = load(record, &at) |
| 436 | if os.IsNotExist(err) { |
| 437 | if err = os.Mkdir(dir, 0700); err != nil { |
| 438 | return zero, provider.ErrUncertain |
| 439 | } |
| 440 | repo, _, e := m.fetch(ctx, brief.Target) |
| 441 | if e != nil { |
| 442 | return zero, e |
| 443 | } |
| 444 | source := filepath.Join(m.cfg.WorkspaceRoot, "source-"+digest(a.WorkspaceKey)) |
| 445 | if !allowed(source, policy) { |
| 446 | return zero, provider.ErrPolicy |
| 447 | } |
| 448 | if _, e := os.Lstat(source); !os.IsNotExist(e) { |
| 449 | return zero, provider.ErrUncertain |
| 450 | } |
| 451 | if e = m.init(ctx, source, objectFormat(brief.Target.BaseRevision), false); e != nil { |
| 452 | return zero, e |
| 453 | } |
| 454 | if e = copyObjects(filepath.Join(repo, "objects"), filepath.Join(source, ".git", "objects")); e != nil { |
| 455 | return zero, e |
| 456 | } |
| 457 | if _, e = m.run(ctx, source, "checkout", "--detach", brief.Target.BaseRevision); e != nil { |
| 458 | return zero, e |
| 459 | } |
| 460 | { |
| 461 | path := filepath.Join(m.cfg.WorkspaceRoot, "attempt-"+digest(a.WorkspaceKey)) |
| 462 | if _, e = m.run(ctx, source, "worktree", "add", "-b", brief.Target.Ref, path, brief.Target.BaseRevision); e != nil { |
| 463 | return zero, e |
| 464 | } |
| 465 | // Detach the worktree metadata from the source before exposing the checkout. |
| 466 | gitfile, e := regular(filepath.Join(path, ".git")) |
| 467 | if e != nil { |
| 468 | return zero, e |
| 469 | } |
| 470 | metadata := strings.TrimSpace(strings.TrimPrefix(string(gitfile), "gitdir: ")) |
| 471 | index, e := regular(filepath.Join(metadata, "index")) |
| 472 | if e != nil { |
| 473 | return zero, e |
| 474 | } |
| 475 | if e = os.Remove(filepath.Join(path, ".git")); e != nil { |
| 476 | return zero, e |
| 477 | } |
| 478 | if e = m.init(ctx, path, objectFormat(brief.Target.BaseRevision), false); e != nil { |
| 479 | return zero, e |
| 480 | } |
| 481 | if e = copyObjects(filepath.Join(source, ".git", "objects"), filepath.Join(path, ".git", "objects")); e != nil { |
| 482 | return zero, e |
| 483 | } |
| 484 | if _, e = m.run(ctx, path, "symbolic-ref", "HEAD", "refs/heads/"+brief.Target.Ref); e != nil { |
| 485 | return zero, e |
| 486 | } |
| 487 | if _, e = m.run(ctx, path, "update-ref", "refs/heads/"+brief.Target.Ref, brief.Target.BaseRevision); e != nil { |
| 488 | return zero, e |
| 489 | } |
| 490 | if e = os.WriteFile(filepath.Join(path, ".git", "index"), index, 0600); e != nil { |
| 491 | return zero, e |
| 492 | } |
| 493 | config, e := regular(filepath.Join(path, ".git", "config")) |
| 494 | if e != nil { |
| 495 | return zero, e |
| 496 | } |
| 497 | 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} |
| 498 | if e = m.validateWorkspace(at); e != nil { |
| 499 | return zero, e |
| 500 | } |
| 501 | if e = save(record, at); e != nil { |
| 502 | return zero, e |
| 503 | } |
| 504 | if e = os.RemoveAll(source); e != nil { |
| 505 | return zero, e |
| 506 | } |
| 507 | return localWorkspace(at, a.WorkspaceKey), nil |
| 508 | } |
| 509 | } else if err != nil { |
| 510 | return zero, provider.ErrUncertain |
| 511 | } |
| 512 | if at.Hash != hash { |
| 513 | return zero, provider.ErrIdentity |
| 514 | } |
| 515 | if !at.Local || at.Workspace.WorkspaceID == "" { |
| 516 | return zero, provider.ErrIdentity |
| 517 | } |
| 518 | if err = m.validateWorkspace(at); err != nil { |
| 519 | return zero, err |
| 520 | } |
| 521 | return localWorkspace(at, a.WorkspaceKey), nil |
| 522 | } |
| 523 | func regular(path string) ([]byte, error) { |
| 524 | s, e := os.Lstat(path) |
| 525 | if e != nil || !s.Mode().IsRegular() { |
| 526 | return nil, provider.ErrIdentity |
| 527 | } |
| 528 | b, e := os.ReadFile(path) |
| 529 | if e != nil { |
| 530 | return nil, provider.ErrIdentity |
| 531 | } |
| 532 | return b, nil |
| 533 | } |
| 534 | func localWorkspace(at attempt, key string) Workspace { |
| 535 | return Workspace{Record: at.Workspace, ID: at.Workspace.WorkspaceID, Path: at.Workspace.Path, ArtifactHashes: append([]string(nil), at.ArtifactHashes...), Isolation: at.Isolation, key: key} |
| 536 | } |
| 537 | func (m *Manager) gitdir(at attempt) (string, error) { |
| 538 | if !at.Local { |
| 539 | return "", provider.ErrIdentity |
| 540 | } |
| 541 | return m.localGitdir(at) |
| 542 | } |
| 543 | |
| 544 | func (m *Manager) validateWorkspace(at attempt) error { |
| 545 | if at.ReadOnly { |
| 546 | return validateRead(at) |
| 547 | } |
| 548 | for _, p := range []string{at.Workspace.Path, at.Request.Path, filepath.Join(at.Request.Path, ".git")} { |
| 549 | r, e := canonical(p) |
| 550 | if e != nil || r != p || !allowed(p, at.Request.ReadPolicy) { |
| 551 | return provider.ErrPolicy |
| 552 | } |
| 553 | } |
| 554 | _, e := m.gitdir(at) |
| 555 | return e |
| 556 | } |
| 557 | func (m *Manager) head(at attempt) (string, error) { |
| 558 | dir, e := m.gitdir(at) |
| 559 | if e != nil { |
| 560 | return "", e |
| 561 | } |
| 562 | b, e := regular(filepath.Join(dir, "HEAD")) |
| 563 | ref := "refs/heads/" + at.Target.Ref |
| 564 | if e != nil || strings.TrimSpace(string(b)) != "ref: "+ref { |
| 565 | return "", provider.ErrIdentity |
| 566 | } |
| 567 | common := filepath.Join(at.Request.Path, ".git") |
| 568 | p := filepath.Join(common, ref) |
| 569 | resolved, e := canonical(p) |
| 570 | if e != nil || resolved != p { |
| 571 | return "", provider.ErrIdentity |
| 572 | } |
| 573 | b, e = regular(p) |
| 574 | if e == nil { |
| 575 | id := strings.TrimSpace(string(b)) |
| 576 | if objectID.MatchString(id) { |
| 577 | return id, nil |
| 578 | } |
| 579 | return "", provider.ErrIdentity |
| 580 | } |
| 581 | b, e = regular(filepath.Join(common, "packed-refs")) |
| 582 | if e != nil { |
| 583 | return "", e |
| 584 | } |
| 585 | for _, line := range strings.Split(string(b), "\n") { |
| 586 | parts := strings.Split(line, " ") |
| 587 | if len(parts) == 2 && parts[1] == ref && objectID.MatchString(parts[0]) { |
| 588 | return parts[0], nil |
| 589 | } |
| 590 | } |
| 591 | return "", provider.ErrIdentity |
| 592 | } |
| 593 | func copyObjects(from, to string) error { |
| 594 | return filepath.WalkDir(from, func(p string, d os.DirEntry, err error) error { |
| 595 | if err != nil { |
| 596 | return provider.ErrIdentity |
| 597 | } |
| 598 | rel, e := filepath.Rel(from, p) |
| 599 | if e != nil || d.Type()&os.ModeSymlink != 0 { |
| 600 | return provider.ErrIdentity |
| 601 | } |
| 602 | if d.IsDir() { |
| 603 | if rel != "." && rel != "info" && rel != "pack" && !(len(rel) == 2 && strings.Trim(rel, "0123456789abcdef") == "") { |
| 604 | return provider.ErrIdentity |
| 605 | } |
| 606 | if os.MkdirAll(filepath.Join(to, rel), 0700) != nil { |
| 607 | return provider.ErrContract |
| 608 | } |
| 609 | return nil |
| 610 | } |
| 611 | if !d.Type().IsRegular() { |
| 612 | return provider.ErrIdentity |
| 613 | } |
| 614 | parts := strings.Split(rel, string(filepath.Separator)) |
| 615 | valid := len(parts) == 2 && ((len(parts[0]) == 2 && objectID.MatchString(parts[0]+parts[1])) || (parts[0] == "pack" && packFile.MatchString(parts[1]))) |
| 616 | if !valid { |
| 617 | return provider.ErrIdentity |
| 618 | } |
| 619 | in, e := os.Open(p) |
| 620 | if e != nil { |
| 621 | return provider.ErrIdentity |
| 622 | } |
| 623 | defer in.Close() |
| 624 | out, e := os.OpenFile(filepath.Join(to, rel), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| 625 | if e != nil { |
| 626 | return provider.ErrContract |
| 627 | } |
| 628 | _, e = io.Copy(out, in) |
| 629 | closeErr := out.Close() |
| 630 | if e != nil || closeErr != nil { |
| 631 | return provider.ErrContract |
| 632 | } |
| 633 | return nil |
| 634 | }) |
| 635 | } |
| 636 | func (m *Manager) clean(ctx context.Context, repo, path, commit string) error { |
| 637 | b, e := m.git(ctx, repo, nil, nil, "ls-tree", "-rz", "--full-tree", commit) |
| 638 | if e != nil { |
| 639 | return e |
| 640 | } |
| 641 | type entry struct{ mode, id string } |
| 642 | tracked := map[string]entry{} |
| 643 | dirs := map[string]bool{} |
| 644 | for _, item := range bytes.Split(b, []byte{0}) { |
| 645 | if len(item) == 0 { |
| 646 | continue |
| 647 | } |
| 648 | parts := bytes.SplitN(item, []byte{'\t'}, 2) |
| 649 | if len(parts) != 2 { |
| 650 | return provider.ErrIdentity |
| 651 | } |
| 652 | fields := strings.Fields(string(parts[0])) |
| 653 | name := string(parts[1]) |
| 654 | if len(fields) != 3 || fields[1] != "blob" || filepath.Clean(name) != name || filepath.IsAbs(name) || name == ".git" || strings.HasPrefix(name, "../") { |
| 655 | return provider.ErrIdentity |
| 656 | } |
| 657 | tracked[name] = entry{fields[0], fields[2]} |
| 658 | for d := filepath.Dir(name); d != "."; d = filepath.Dir(d) { |
| 659 | dirs[d] = true |
| 660 | } |
| 661 | } |
| 662 | seen := 0 |
| 663 | e = filepath.WalkDir(path, func(p string, d os.DirEntry, err error) error { |
| 664 | if err != nil { |
| 665 | return provider.ErrIdentity |
| 666 | } |
| 667 | rel, e := filepath.Rel(path, p) |
| 668 | if e != nil { |
| 669 | return provider.ErrIdentity |
| 670 | } |
| 671 | if rel == "." { |
| 672 | return nil |
| 673 | } |
| 674 | if rel == ".git" { |
| 675 | if d.IsDir() { |
| 676 | return filepath.SkipDir |
| 677 | } |
| 678 | return nil |
| 679 | } |
| 680 | if d.IsDir() { |
| 681 | if !dirs[rel] { |
| 682 | return provider.ErrIdentity |
| 683 | } |
| 684 | return nil |
| 685 | } |
| 686 | ent, ok := tracked[rel] |
| 687 | if !ok { |
| 688 | return provider.ErrIdentity |
| 689 | } |
| 690 | var data []byte |
| 691 | switch ent.mode { |
| 692 | case "120000": |
| 693 | if d.Type()&os.ModeSymlink == 0 { |
| 694 | return provider.ErrIdentity |
| 695 | } |
| 696 | link, e := os.Readlink(p) |
| 697 | if e != nil || filepath.IsAbs(link) { |
| 698 | return provider.ErrIdentity |
| 699 | } |
| 700 | resolved, e := canonical(filepath.Clean(filepath.Join(filepath.Dir(p), link))) |
| 701 | if e != nil || !contains(path, resolved) { |
| 702 | return provider.ErrIdentity |
| 703 | } |
| 704 | data = []byte(link) |
| 705 | case "100644", "100755": |
| 706 | if !d.Type().IsRegular() { |
| 707 | return provider.ErrIdentity |
| 708 | } |
| 709 | s, e := d.Info() |
| 710 | if e != nil || ((s.Mode()&0111) != 0) != (ent.mode == "100755") { |
| 711 | return provider.ErrIdentity |
| 712 | } |
| 713 | data, e = os.ReadFile(p) |
| 714 | if e != nil { |
| 715 | return provider.ErrIdentity |
| 716 | } |
| 717 | default: |
| 718 | return provider.ErrIdentity |
| 719 | } |
| 720 | framed := append([]byte(fmt.Sprintf("blob %d\x00", len(data))), data...) |
| 721 | id := "" |
| 722 | if len(ent.id) == 40 { |
| 723 | s := sha1.Sum(framed) |
| 724 | id = hex.EncodeToString(s[:]) |
| 725 | } else { |
| 726 | s := sha256.Sum256(framed) |
| 727 | id = hex.EncodeToString(s[:]) |
| 728 | } |
| 729 | if id != ent.id { |
| 730 | return provider.ErrIdentity |
| 731 | } |
| 732 | seen++ |
| 733 | return nil |
| 734 | }) |
| 735 | if e != nil || seen != len(tracked) { |
| 736 | return provider.ErrIdentity |
| 737 | } |
| 738 | return nil |
| 739 | } |
| 740 | func (m *Manager) CaptureCandidate(ctx context.Context, w Workspace, target team.TargetBinding) (GitCandidate, error) { |
| 741 | m.mu.Lock() |
| 742 | defer m.mu.Unlock() |
| 743 | var zero GitCandidate |
| 744 | var at attempt |
| 745 | 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 { |
| 746 | return zero, provider.ErrIdentity |
| 747 | } |
| 748 | if e := m.validateWorkspace(at); e != nil { |
| 749 | return zero, e |
| 750 | } |
| 751 | commit, e := m.head(at) |
| 752 | if e != nil { |
| 753 | return zero, e |
| 754 | } |
| 755 | staging, e := os.MkdirTemp(m.cfg.PrivateRoot, "capture-") |
| 756 | if e != nil { |
| 757 | return zero, provider.ErrContract |
| 758 | } |
| 759 | defer os.RemoveAll(staging) |
| 760 | if e = m.init(ctx, staging, objectFormat(target.BaseRevision), true); e != nil { |
| 761 | return zero, e |
| 762 | } |
| 763 | if e = copyObjects(filepath.Join(at.Request.Path, ".git", "objects"), filepath.Join(staging, "objects")); e != nil { |
| 764 | return zero, e |
| 765 | } |
| 766 | if _, e = m.run(ctx, staging, "merge-base", "--is-ancestor", target.BaseRevision, commit); e != nil { |
| 767 | return zero, provider.ErrIdentity |
| 768 | } |
| 769 | tree, e := m.run(ctx, staging, "rev-parse", "--verify", commit+"^{tree}") |
| 770 | if e != nil || !objectID.MatchString(tree) { |
| 771 | return zero, provider.ErrIdentity |
| 772 | } |
| 773 | gitdir, e := m.gitdir(at) |
| 774 | if e != nil { |
| 775 | return zero, e |
| 776 | } |
| 777 | index, e := regular(filepath.Join(gitdir, "index")) |
| 778 | if e != nil { |
| 779 | return zero, e |
| 780 | } |
| 781 | if os.WriteFile(filepath.Join(staging, "index"), index, 0600) != nil { |
| 782 | return zero, provider.ErrContract |
| 783 | } |
| 784 | if _, e = m.run(ctx, staging, "diff-index", "--cached", "--quiet", "--no-ext-diff", "--no-textconv", commit, "--"); e != nil { |
| 785 | return zero, provider.ErrIdentity |
| 786 | } |
| 787 | if e = m.clean(ctx, staging, w.Path, commit); e != nil { |
| 788 | return zero, e |
| 789 | } |
| 790 | again, e := m.head(at) |
| 791 | if e != nil || again != commit { |
| 792 | return zero, provider.ErrIdentity |
| 793 | } |
| 794 | c := GitCandidate{Repository: target.Repository, BaseCommit: target.BaseRevision, Commit: commit, Tree: tree} |
| 795 | if _, e = m.run(ctx, staging, "update-ref", "refs/heads/candidate", commit); e != nil { |
| 796 | return zero, e |
| 797 | } |
| 798 | if _, e = m.run(ctx, staging, "fsck", "--strict", "--no-reflogs"); e != nil { |
| 799 | return zero, provider.ErrIdentity |
| 800 | } |
| 801 | if _, e = m.run(ctx, staging, "-c", "core.fsync=all", "-c", "repack.writeBitmaps=false", "repack", "-adn"); e != nil { |
| 802 | return zero, e |
| 803 | } |
| 804 | entries, e := os.ReadDir(filepath.Join(staging, "objects")) |
| 805 | if e != nil { |
| 806 | return zero, provider.ErrContract |
| 807 | } |
| 808 | for _, entry := range entries { |
| 809 | if len(entry.Name()) == 2 && strings.Trim(entry.Name(), "0123456789abcdef") == "" { |
| 810 | if os.RemoveAll(filepath.Join(staging, "objects", entry.Name())) != nil { |
| 811 | return zero, provider.ErrContract |
| 812 | } |
| 813 | } |
| 814 | } |
| 815 | destination := filepath.Join(m.cfg.PrivateRoot, "candidate-"+digest(c)) |
| 816 | if _, e = os.Stat(destination); e == nil { |
| 817 | var saved GitCandidate |
| 818 | if load(filepath.Join(destination, "candidate.json"), &saved) != nil || saved != c { |
| 819 | return zero, provider.ErrIdentity |
| 820 | } |
| 821 | return c, nil |
| 822 | } |
| 823 | if e = save(filepath.Join(staging, "candidate.json"), c); e != nil { |
| 824 | return zero, e |
| 825 | } |
| 826 | if os.Rename(staging, destination) != nil { |
| 827 | return zero, provider.ErrContract |
| 828 | } |
| 829 | parent, e := os.Open(m.cfg.PrivateRoot) |
| 830 | if e != nil { |
| 831 | return zero, provider.ErrUncertain |
| 832 | } |
| 833 | defer parent.Close() |
| 834 | if parent.Sync() != nil { |
| 835 | return zero, provider.ErrUncertain |
| 836 | } |
| 837 | return c, nil |
| 838 | } |
| 839 | func (m *Manager) ExportCandidate(ctx context.Context, c GitCandidate, destination string) error { |
| 840 | m.mu.Lock() |
| 841 | defer m.mu.Unlock() |
| 842 | source := filepath.Join(m.cfg.PrivateRoot, "candidate-"+digest(c)) |
| 843 | var saved GitCandidate |
| 844 | if load(filepath.Join(source, "candidate.json"), &saved) != nil || saved != c { |
| 845 | return provider.ErrIdentity |
| 846 | } |
| 847 | r, e := canonical(destination) |
| 848 | if e != nil || r != destination || !allowed(destination, provider.ReadPolicy{ConfigHash: "export", DeniedPaths: append(m.cfg.Protected.all(), m.cfg.PrivateRoot)}) { |
| 849 | return provider.ErrPolicy |
| 850 | } |
| 851 | if _, e = os.Lstat(destination); !os.IsNotExist(e) { |
| 852 | return provider.ErrIdentity |
| 853 | } |
| 854 | if e = os.Mkdir(destination, 0700); e != nil { |
| 855 | return provider.ErrContract |
| 856 | } |
| 857 | ok := false |
| 858 | defer func() { |
| 859 | if !ok { |
| 860 | _ = os.RemoveAll(destination) |
| 861 | } |
| 862 | }() |
| 863 | if e = m.init(ctx, destination, objectFormat(c.Commit), false); e != nil { |
| 864 | return e |
| 865 | } |
| 866 | if e = copyObjects(filepath.Join(source, "objects"), filepath.Join(destination, ".git", "objects")); e != nil { |
| 867 | return e |
| 868 | } |
| 869 | tree, e := m.run(ctx, destination, "rev-parse", c.Commit+"^{tree}") |
| 870 | if e != nil || tree != c.Tree { |
| 871 | return provider.ErrIdentity |
| 872 | } |
| 873 | if _, e = m.run(ctx, destination, "checkout", "--detach", c.Commit); e != nil { |
| 874 | return e |
| 875 | } |
| 876 | if e = m.clean(ctx, destination, destination, c.Commit); e != nil { |
| 877 | return e |
| 878 | } |
| 879 | ok = true |
| 880 | return nil |
| 881 | } |
| 882 | |
| 883 | func (m *Manager) ValidateTurn(ctx context.Context, a runnerproto.Assignment, w Workspace) error { |
| 884 | m.mu.Lock() |
| 885 | defer m.mu.Unlock() |
| 886 | var at attempt |
| 887 | 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) { |
| 888 | return provider.ErrIdentity |
| 889 | } |
| 890 | policy, err := m.preflight(ctx, a) |
| 891 | if err != nil { |
| 892 | return err |
| 893 | } |
| 894 | if !reflect.DeepEqual(policy, at.Request.ReadPolicy) { |
| 895 | return provider.ErrPolicy |
| 896 | } |
| 897 | return m.validateWorkspace(at) |
| 898 | } |
| 899 | |
| 900 | // CheckoutCandidate installs only a previously captured immutable candidate in |
| 901 | // a fresh review workspace before any agent is created. |
| 902 | func (m *Manager) CheckoutCandidate(ctx context.Context, w Workspace, c GitCandidate) error { |
| 903 | return m.ContinueCandidate(ctx, w, c, false) |
| 904 | } |
| 905 | func (m *Manager) ContinueCandidate(ctx context.Context, w Workspace, c GitCandidate, build bool) error { |
| 906 | m.mu.Lock() |
| 907 | defer m.mu.Unlock() |
| 908 | var at attempt |
| 909 | 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 { |
| 910 | return provider.ErrIdentity |
| 911 | } |
| 912 | if err := m.validateWorkspace(at); err != nil { |
| 913 | return err |
| 914 | } |
| 915 | source := filepath.Join(m.cfg.PrivateRoot, "candidate-"+digest(c)) |
| 916 | var saved GitCandidate |
| 917 | if load(filepath.Join(source, "candidate.json"), &saved) != nil || saved != c { |
| 918 | return provider.ErrIdentity |
| 919 | } |
| 920 | if err := copyObjects(filepath.Join(source, "objects"), filepath.Join(at.Request.Path, ".git", "objects")); err != nil { |
| 921 | return err |
| 922 | } |
| 923 | args := []string{"checkout", "--detach", c.Commit} |
| 924 | if build { |
| 925 | args = []string{"checkout", "-B", at.Target.Ref, c.Commit} |
| 926 | } |
| 927 | if _, err := m.run(ctx, w.Path, args...); err != nil { |
| 928 | return err |
| 929 | } |
| 930 | tree, err := m.run(ctx, w.Path, "rev-parse", "HEAD^{tree}") |
| 931 | if err != nil || tree != c.Tree { |
| 932 | return provider.ErrIdentity |
| 933 | } |
| 934 | return m.clean(ctx, at.Request.Path, w.Path, c.Commit) |
| 935 | } |
| 936 | |
| 937 | func (m *Manager) PreparationDirectory() string { return m.cfg.PrivateRoot } |
| 938 | |