package forge import ( "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "os" "os/exec" "path/filepath" "regexp" "slices" "strings" "syscall" "amadan.net/oficina/equipo/internal/runner/workspace" ) // Branch publication errors. Only ErrPushRefused and ErrPushConflict are // final; ErrPushUncertain is settled by the next PushBranch for the key. var ( ErrPushRefused = errors.New("forge: push refused by validation") ErrPushConflict = errors.New("forge: the branch moved") ErrPushUncertain = errors.New("forge: push outcome unknown") ) // BranchPush is one candidate commit for a task's own branch. Forge // validates the repository, the branch (equipo/..., never the default // branch), the candidate (a descendant of the base in the runner's // private repository) and the person, records its intent before any // network write, and reconciles a push cut off midway from the record. type BranchPush struct { ExpectedHead string // Root keeps the publication records (private, 0700). Root string Git string // GitDir is the runner's private repository holding Commit; no // namespace ever sees it. GitDir string Repo string Branch string // Default is the repository's default branch, never pushed. Base is // the commit Commit was made on, or "" when the repository had none // (Commit is then its initial commit). Default string Base string Commit string // Key names the attempt (task/step/attempt), one record each. Key string // Person is whose task this is; Owners are the persons this runner // executes for. Person string Owners []string // Remote resolves the URL and git password just in time. Remote func(context.Context) (workspace.Remote, error) // Confirm checks the execution lease with the instance; it runs right // before the push and a failure stops it. Confirm func(context.Context) error // beforePush runs right before the push (tests move the branch). beforePush func() } type pushRecord struct { Key string `json:"key"` Repo string `json:"repo"` Branch string `json:"branch"` Commit string `json:"commit"` Phase string `json:"phase"` // Expected is the head the push replaces ("" for no branch), fixed // before the first push (Observed); only that head may be replaced. Expected string `json:"expected"` Observed bool `json:"observed"` } var taskRef = regexp.MustCompile(`^equipo/[a-z0-9]+(?:-[a-z0-9]+)*$`) func (b BranchPush) validate() error { if b.ExpectedHead != "" && !object.MatchString(b.ExpectedHead) { return ErrPushRefused } if !validRepository(b.Repo) || !validRef(b.Branch) || !taskRef.MatchString(b.Branch) || len(b.Branch) > 100 || b.Branch == b.Default || !validRef(b.Default) || !object.MatchString(b.Commit) || b.Base != "" && (!object.MatchString(b.Base) || len(b.Commit) != len(b.Base)) || b.Commit == b.Base || !filepath.IsAbs(b.GitDir) || !filepath.IsAbs(b.Root) || !filepath.IsAbs(b.Git) || b.Key == "" || b.Remote == nil || b.Confirm == nil || b.Person == "" || !slices.Contains(b.Owners, b.Person) { return ErrPushRefused } return nil } // path is the attempt's record file. func (b BranchPush) path() string { sum := sha256.Sum256([]byte(b.Key)) return filepath.Join(b.Root, "push-"+hex.EncodeToString(sum[:12])+".json") } // git runs git with hooks, helpers, system and global config off, the // password only in an environment header. func (b BranchPush) git(ctx context.Context, dir string, remote *workspace.Remote, args ...string) (string, error) { protocol := "https" if remote != nil && filepath.IsAbs(remote.URL) { protocol = "file" } args = append([]string{"-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false", "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "push.recurseSubmodules=no"}, args...) cmd := exec.CommandContext(ctx, b.Git, args...) cmd.Dir = dir env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" env["GIT_DIR"] = b.GitDir if remote != nil && 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)) } for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } var stderr bytes.Buffer cmd.Stderr = &capWriter{w: &stderr, n: 8 << 10} out, err := cmd.Output() if err != nil { return "", &gitAnswer{err: err, refusal: pushRefusalOf(string(out) + "\n" + stderr.String()), text: pushAnswer(string(out), stderr.String(), remote)} } return strings.TrimSpace(string(out)), nil } func (b BranchPush) save(r pushRecord) error { raw, _ := json.Marshal(r) tmp := b.path() + ".tmp" f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0600) if err != nil { return err } if _, err = f.Write(raw); err == nil { err = f.Sync() } if cerr := f.Close(); err == nil { err = cerr } if err != nil { return err } if err = os.Rename(tmp, b.path()); err != nil { return err } dir, err := os.Open(b.Root) if err != nil { return err } defer dir.Close() return dir.Sync() } // ours lists the commits Equipo itself pushed to this branch, from the // records of earlier attempts: a new attempt may replace only those. func (b BranchPush) ours() map[string]bool { out := map[string]bool{} paths, _ := filepath.Glob(filepath.Join(b.Root, "push-*.json")) for _, p := range paths { var r pushRecord if raw, err := os.ReadFile(p); err == nil && json.Unmarshal(raw, &r) == nil && r.Repo == b.Repo && r.Branch == b.Branch && (r.Phase == "published" || r.Phase == "push_started") { out[r.Commit] = true } } return out } func (b BranchPush) load() (pushRecord, bool, error) { var r pushRecord raw, err := os.ReadFile(b.path()) if errors.Is(err, os.ErrNotExist) { return r, false, nil } if err != nil || json.Unmarshal(raw, &r) != nil { return r, false, ErrPushUncertain } return r, true, nil } // head reads the branch's tip on the remote; "" when it does not exist. func (b BranchPush) head(ctx context.Context, remote workspace.Remote) (string, error) { ref := "refs/heads/" + b.Branch out, err := b.git(ctx, b.Root, &remote, "ls-remote", "--refs", "--", remote.URL, ref) if err != nil { return "", pushError("ls-remote", err, ErrPushUncertain) } fields := strings.Fields(out) if len(fields) == 0 { return "", nil } if len(fields) != 2 || !object.MatchString(fields[0]) || fields[1] != ref { return "", ErrPushUncertain } return fields[0], nil } // remote resolves the repository's remote and checks it is that one. func (b BranchPush) remote(ctx context.Context) (workspace.Remote, error) { remote, err := b.Remote(ctx) if errors.Is(err, workspace.ErrHubUnavailable) { // Write access could not be confirmed: worth trying again. return workspace.Remote{}, fmt.Errorf("resolving the remote: %w", err) } if err != nil { return workspace.Remote{}, fmt.Errorf("%w: resolving the remote: %v", ErrPushRefused, err) } if remote.URL == "" || !filepath.IsAbs(remote.URL) && (remote.URL != "https://"+b.Repo || remote.GitPassword == "") || filepath.IsAbs(remote.URL) && remote.GitPassword != "" { return workspace.Remote{}, ErrPushRefused } return remote, nil } // PushBranch publishes Commit to Branch once. A record is written before // any network write; a later call for the same key reconciles from the // remote (the branch already at Commit is success) instead of pushing // blind. The lease is confirmed right before the push. func PushBranch(ctx context.Context, b BranchPush) error { if err := b.validate(); err != nil { return err } if err := os.MkdirAll(b.Root, 0700); err != nil { return ErrPushUncertain } lock, err := os.OpenFile(b.path()+".lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600) if err != nil { return ErrPushUncertain } defer lock.Close() if syscall.Flock(int(lock.Fd()), syscall.LOCK_EX) != nil { return ErrPushUncertain } rec, found, err := b.load() if err != nil { return err } if found && (rec.Key != b.Key || rec.Repo != b.Repo || rec.Branch != b.Branch || rec.Commit != b.Commit) { return ErrPushRefused } // A push that may have landed reconciles from the remote first: it is // done if the branch is at the candidate, even if the runner lost its // local objects since. if found && (rec.Phase == "push_started" || rec.Phase == "published") { remote, err := b.remote(ctx) if err != nil { return err } head, err := b.head(ctx, remote) if err != nil { return err } if head == b.Commit { rec.Phase = "published" return b.save(rec) } } // The candidate is what the runner committed: a commit descending from // the base, complete and well formed in its private repository. if id, err := b.git(ctx, b.Root, nil, "rev-parse", "--verify", "--end-of-options", b.Commit+"^{commit}"); err != nil || id != b.Commit { return ErrPushRefused } if b.Base == "" { // No base: the repository had no commits, so the candidate is its // initial commit and has no parent. if out, err := b.git(ctx, b.Root, nil, "rev-list", "--parents", "-n", "1", "--end-of-options", b.Commit); err != nil || out != b.Commit { return ErrPushRefused } } else if _, err := b.git(ctx, b.Root, nil, "merge-base", "--is-ancestor", b.Base, b.Commit); err != nil { return ErrPushRefused } if _, err := b.git(ctx, b.Root, nil, "fsck", "--no-reflogs", "--connectivity-only", b.Commit); err != nil { return ErrPushRefused } if !found { rec = pushRecord{Key: b.Key, Repo: b.Repo, Branch: b.Branch, Commit: b.Commit, Phase: "prepared"} if err := b.save(rec); err != nil { return ErrPushUncertain } } remote, err := b.remote(ctx) if err != nil { return err } head, err := b.head(ctx, remote) if err != nil { return err } if head == b.Commit { rec.Phase = "published" return b.save(rec) } if b.ExpectedHead != "" && head != b.ExpectedHead { return ErrPushConflict } if !rec.Observed { // The predecessor is fixed once, before the first push: no branch // yet, or a commit an earlier attempt of Equipo's pushed there. if head != "" && !b.ours()[head] { return ErrPushConflict } rec.Expected, rec.Observed = head, true if err := b.save(rec); err != nil { return ErrPushUncertain } } if head != rec.Expected { // Someone moved the branch since: never push over their work. return ErrPushConflict } if err := b.Confirm(ctx); err != nil { return fmt.Errorf("%w: confirming the lease: %v", ErrPushUncertain, err) } rec.Phase = "push_started" if err := b.save(rec); err != nil { return ErrPushUncertain } if b.beforePush != nil { b.beforePush() } _, perr := b.git(ctx, b.Root, &remote, "push", "--porcelain", "--no-verify", "--no-recurse-submodules", "--force-with-lease=refs/heads/"+b.Branch+":"+rec.Expected, "--", remote.URL, b.Commit+":refs/heads/"+b.Branch) after, err := b.head(ctx, remote) switch { case err != nil && perr != nil: // git's answer to the push says more than the read after it. return pushError("push", perr, ErrPushUncertain) case err != nil: return err case after == b.Commit: rec.Phase = "published" return b.save(rec) case perr != nil && after != head: return pushError("push", perr, ErrPushConflict) case perr != nil: return pushError("push", perr, ErrPushUncertain) } return fmt.Errorf("%w: git push succeeded but the branch is not at the commit", ErrPushUncertain) }