package forge import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "html" "io" "net/http" "net/url" "os" "path/filepath" "regexp" "slices" "strconv" "strings" "syscall" "time" "amadan.net/oficina/equipo/internal/runnerproto" ) // Merge errors. ErrMergeUncertain is settled by the next MergeBranch for // the same task and commit: it reads the default branch first. var ( ErrMergeRefused = errors.New("forge: merge refused by validation") ErrMergeMoved = errors.New("forge: the task branch is not at the judged commit") ErrMergeConflict = errors.New("forge: the branch conflicts with the default branch") ErrMergeCIPending = errors.New("forge: the hub's own CI on the commit has not finished") ErrMergeCIFailed = errors.New("forge: the hub's own CI on the commit is not green") ErrMergeForbidden = errors.New("forge: the agent may not merge in this repository") ErrMergeFailed = errors.New("forge: the hub refused the merge") ErrMergeUncertain = errors.New("forge: merge outcome unknown") // ErrMergeUnbornDefault: the default branch has no commits yet and // the hub refused to make the first merge (unborn_default, or // is_default once a rebuild pointed its HEAD at the task branch). ErrMergeUnbornDefault = errors.New("forge: the hub cannot make the first merge into an empty repository") // ErrMergeNoCredential: the runner has no usable forge credential for // the repository (none in the credential file, and it is not one the // agent-wide credential serves), so it refused the merge itself. ErrMergeNoCredential = errors.New("forge: no usable forge credential for the repository") ) // NotSentError is a merge Equipo refused itself before any merge request // left for the hub: a definite refusal, never "outcome unknown", since the // hub cannot have acted on it. Only code that has sent no merge request // returns one. type NotSentError struct { // Repo is the repository refused, "" when it is not a valid hub key. Repo string Err error } func (e *NotSentError) Error() string { repo := e.Repo if repo == "" { repo = "this repository" } return fmt.Sprintf("%v (%s; refused by the runner, no merge request was sent)", e.Err, repo) } func (e *NotSentError) Unwrap() error { return e.Err } // NotSent is err as a refusal made before the merge request, naming repo // only when it is a valid hub repository. func NotSent(repo string, err error) error { if !validRepository(repo) { repo = "" } return &NotSentError{Repo: repo, Err: err} } // HubError is the hub's answer to a merge it did not make: its HTTP // status, its machine-readable reason (the JSON "reason") and its // sentence (the JSON "error", or a page's text), both redacted and // bounded. It wraps the outcome the answer means (ErrMergeConflict, // ErrMergeFailed, ErrMergeUncertain, ...), which still decides the // step's reason. type HubError struct { Status int Code, Message string Err error } func (e *HubError) Error() string { return fmt.Sprintf("%v (hub %s: %s)", e.Err, strings.TrimSpace(strconv.Itoa(e.Status)+" "+e.Code), e.Message) } func (e *HubError) Unwrap() error { return e.Err } func hubError(res MergeResult, err error) error { return &HubError{Status: res.Status, Code: runnerproto.RedactDetail(res.Reason, 64), Message: runnerproto.RedactDetail(res.Message, runnerproto.DetailLimit), Err: err} } // uncertain is ErrMergeUncertain with what is known of why: the hub's // answer when it gave one, else the cause's words. Only the words: a // cause's own identity never decides the outcome (MergeBranch settles a // NotSentError, the one refusal known to have sent nothing, before this). func uncertain(res MergeResult, cause error) error { switch { case res.Status != 0: return hubError(res, ErrMergeUncertain) case cause == nil: return ErrMergeUncertain case errors.Is(cause, ErrMergeUncertain): return cause } return fmt.Errorf("%w: %v", ErrMergeUncertain, cause) } // MergeDetail is a failed merge for the step report, a few lines: the // hub's status, code and message when it answered, else the error's own // words; redacted and bounded either way. func MergeDetail(err error) string { var h *HubError switch { case err == nil: return "" case !errors.As(err, &h): return "error: " + runnerproto.RedactDetail(err.Error(), runnerproto.DetailLimit) } out := "status: " + strconv.Itoa(h.Status) if code := runnerproto.RedactDetail(h.Code, 64); code != "" { out += "\ncode: " + code } if msg := runnerproto.RedactDetail(h.Message, runnerproto.DetailLimit); msg != "" { out += "\nmessage: " + msg } return out } // pageTag is markup in an answer that is not JSON (a proxy's error page). var pageTag = regexp.MustCompile(`(?s)<(?:script|style)\b.*?|<[^>]*>`) // MergeRequest is the hub's merge API body (POST /api/v1/repos/{ns}/ // {repo}/branches/{name}/merge). ExpectSHA is the commit that was judged: // the hub's instance compares it with the branch under its git lock, so a // branch that moved is refused, never merged. type MergeRequest struct { ExpectSHA string `json:"expect_sha"` Message string `json:"message"` KeepBranch bool `json:"keep_branch"` Strategy string `json:"strategy"` Agent AgentMeta `json:"agent"` } // AgentMeta names the agent session making the request, as the hub // requires of agent accounts. type AgentMeta struct { Session string `json:"session"` Harness string `json:"harness"` Host string `json:"host"` } // MergeResult is the hub's answer: merged with the new commit on Into, // or a refusal with its machine-readable reason (conflicts, moved, // ci_not_green with CIState, up_to_date, no_such_branch, ...) and its // sentence (Message, redacted and bounded). type MergeResult struct { Status int Merged bool SHA string Into string BranchClosed bool Reason string CIState string Message string } type hubMergeBody struct { Merged bool `json:"merged"` SHA string `json:"sha"` Into string `json:"into"` BranchClosed bool `json:"branch_closed"` Reason string `json:"reason"` CIState string `json:"ci_state"` Error string `json:"error"` } // HubMerge sends one merge request to the hub with the agent's bearer. // A transport failure or an unreadable answer is an error: the caller // cannot know whether the merge happened. What it refuses before sending // is a NotSentError. func HubMerge(ctx context.Context, client *http.Client, hub string, cred Credential, repo, branch string, req MergeRequest) (MergeResult, error) { if !validRepository(repo) || !validRef(branch) { return MergeResult{}, NotSent(repo, ErrMergeRefused) } if cred.Bearer == "" || strings.ContainsAny(cred.Bearer, "\r\n") { return MergeResult{}, NotSent(repo, ErrMergeNoCredential) } parts := strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/") body, _ := json.Marshal(req) hr, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(hub, "/")+"/api/v1/repos/"+url.PathEscape(parts[0])+"/"+url.PathEscape(parts[1])+"/branches/"+url.PathEscape(branch)+"/merge", bytes.NewReader(body)) if err != nil { return MergeResult{}, NotSent(repo, ErrMergeRefused) } hr.Header.Set("Authorization", "Bearer "+cred.Bearer) hr.Header.Set("Content-Type", "application/json") hr.Header.Set("Accept", "application/json") res, err := client.Do(hr) if err != nil { return MergeResult{}, fmt.Errorf("%w: %v", ErrMergeUncertain, err) } defer res.Body.Close() var out hubMergeBody raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<10)) if err != nil || json.Unmarshal(raw, &out) != nil { // Not JSON (a proxy's page, say): its text is the sentence. out = hubMergeBody{Error: html.UnescapeString(pageTag.ReplaceAllString(string(raw), " "))} if res.StatusCode == http.StatusOK || res.StatusCode >= 500 { return MergeResult{Status: res.StatusCode, Message: runnerproto.RedactDetail(out.Error, runnerproto.DetailLimit)}, ErrMergeUncertain } } // Merged only on a 200 that says so with a commit: anything else is a // refusal, never a success. merged := res.StatusCode == http.StatusOK && out.Merged && object.MatchString(out.SHA) return MergeResult{Status: res.StatusCode, Merged: merged, SHA: out.SHA, Into: out.Into, BranchClosed: out.BranchClosed, Reason: out.Reason, CIState: out.CIState, Message: runnerproto.RedactDetail(out.Error, runnerproto.DetailLimit)}, nil } // RemoteState is the repository as the runner reads it: the task // branch's head ("" when gone), the default branch and its tip, and // whether the commit is on the default branch, with the commit there that // brought it in (its merge, or the commit itself). type RemoteState struct { Head string Default string Tip string Landed bool MergeSHA string // Unborn: the default branch has no commits yet (an empty // repository): no Tip, no advertised Default, nothing landed. Unborn bool } // BranchMerge is one judged commit of a task's branch to merge into the // default branch through the hub. Forge validates the repository, the // branch (equipo/..., never the default), the commit and the person, // reads the remote, records its intent, confirms the lease and only then // asks the hub; a later call for the same task and commit reconciles from // the default branch instead of asking again blind. type BranchMerge struct { // Root keeps the merge records (private, 0700). Root string Repo string Branch string Commit string Task string Message string Strategy string Agent AgentMeta // Person is whose task this is; Owners are the persons this runner // executes for. Person string Owners []string // Inspect reads the remote (ls-remote and, when needed, a fetch). Inspect func(context.Context) (RemoteState, error) // Request sends the merge to the hub. Request func(context.Context, MergeRequest) (MergeResult, error) // Confirm checks the execution lease right before the request. Confirm func(context.Context) error // Preflight, if set, makes the runner's own checks that need no // remote (the credential the inspection and the request use) before // the remote is read. It returns a NotSentError to refuse. Preflight func(context.Context) error // beforeRequest runs right before the request (tests move the branch). beforeRequest func() } // MergeOutcome is a confirmed merge: the commit on Into, how, and whether // it was found on the default branch rather than in the hub's answer. type MergeOutcome struct { SHA, Into, Strategy string Reconciled bool // Source is where SHA came from: SourceHub, this request's own answer // from the hub; SourceReconciled, the default branch read after the // fact (its tip when the landing commit was not found); SourceCached, // this runner's earlier record. Only SourceHub is the hub's word. Source string } // Merge outcome sources. const ( SourceHub = "hub" SourceReconciled = "reconciled" SourceCached = "cached" ) type mergeRecord struct { Task string `json:"task"` Repo string `json:"repo"` Branch string `json:"branch"` Commit string `json:"commit"` Phase string `json:"phase"` Strategy string `json:"strategy"` SHA string `json:"sha"` Into string `json:"into"` Reason string `json:"reason"` At string `json:"at"` } // Merge record phases: prepared (nothing sent), requested (a request may // have reached the hub), merged (the hub confirmed it, or the default // branch shows it), refused (the hub answered no; a new request may go). const ( mergePrepared = "prepared" mergeRequested = "requested" mergeMerged = "merged" mergeRefusedPh = "refused" ) var mergeTaskRef = taskRef func (m BranchMerge) validate() error { if !validRepository(m.Repo) || !validRef(m.Branch) || !mergeTaskRef.MatchString(m.Branch) || len(m.Branch) > 100 || !object.MatchString(m.Commit) || m.Task == "" || strings.ContainsAny(m.Task, "/\\\x00") || !filepath.IsAbs(m.Root) || m.Inspect == nil || m.Request == nil || m.Confirm == nil || m.Strategy != "merge" && m.Strategy != "squash" || m.Agent.Session == "" || m.Person == "" || !slices.Contains(m.Owners, m.Person) || len(m.Message) > 4000 { return ErrMergeRefused } return nil } // path is the record for this task and commit: a new attempt to merge the // same judged commit reads the same record. func (m BranchMerge) path() string { sum := sha256.Sum256([]byte(m.Task + "\x00" + m.Repo + "\x00" + m.Branch + "\x00" + m.Commit)) return filepath.Join(m.Root, "merge-"+hex.EncodeToString(sum[:12])+".json") } func (m BranchMerge) load() (mergeRecord, bool, error) { var r mergeRecord raw, err := os.ReadFile(m.path()) if errors.Is(err, os.ErrNotExist) { return r, false, nil } if err != nil || json.Unmarshal(raw, &r) != nil { return r, false, ErrMergeUncertain } return r, true, nil } func (m BranchMerge) save(r mergeRecord) error { r.At = time.Now().UTC().Format(time.RFC3339Nano) raw, _ := json.Marshal(r) tmp := m.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, m.path()); err != nil { return err } dir, err := os.Open(m.Root) if err != nil { return err } defer dir.Close() return dir.Sync() } // landed records a merge the default branch shows and returns it. func (m BranchMerge) landed(rec mergeRecord, st RemoteState, reconciled bool) (MergeOutcome, error) { rec.Phase, rec.SHA, rec.Into = mergeMerged, firstOf(st.MergeSHA, st.Tip), st.Default if err := m.save(rec); err != nil { return MergeOutcome{}, ErrMergeUncertain } return MergeOutcome{SHA: rec.SHA, Into: rec.Into, Strategy: rec.Strategy, Reconciled: reconciled, Source: SourceReconciled}, nil } func firstOf(a, b string) string { if a != "" { return a } return b } // MergeBranch merges Commit into the default branch once. The remote is // read first: a commit already on the default branch is done (a lost // answer, a crash after the request, or a person who merged it), and a // branch no longer at Commit is never merged. The record is written // before the request; the lease is confirmed right before it. func MergeBranch(ctx context.Context, m BranchMerge) (MergeOutcome, error) { if err := m.validate(); err != nil { return MergeOutcome{}, err } if err := os.MkdirAll(m.Root, 0700); err != nil { return MergeOutcome{}, ErrMergeUncertain } lock, err := os.OpenFile(m.path()+".lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600) if err != nil { return MergeOutcome{}, ErrMergeUncertain } defer lock.Close() if syscall.Flock(int(lock.Fd()), syscall.LOCK_EX) != nil { return MergeOutcome{}, ErrMergeUncertain } rec, found, err := m.load() if err != nil { return MergeOutcome{}, err } if found && (rec.Task != m.Task || rec.Repo != m.Repo || rec.Branch != m.Branch || rec.Commit != m.Commit) { return MergeOutcome{}, ErrMergeRefused } if found && rec.Phase == mergeMerged { return MergeOutcome{SHA: rec.SHA, Into: rec.Into, Strategy: rec.Strategy, Source: SourceCached}, nil } // An earlier request may still land: reconcile from the default branch // (a read) before the runner's write check, which then gates only a // new request. unresolved := found && rec.Phase == mergeRequested if m.Preflight != nil && !unresolved { // The runner's own refusals come before the remote is read (that // read needs the same credential): definite, as no request was // ever sent. if err := m.Preflight(ctx); err != nil { var ns *NotSentError if !errors.As(err, &ns) { return MergeOutcome{}, uncertain(MergeResult{}, err) } return MergeOutcome{}, err } } if !found { rec = mergeRecord{Task: m.Task, Repo: m.Repo, Branch: m.Branch, Commit: m.Commit, Phase: mergePrepared, Strategy: m.Strategy} } st, err := m.Inspect(ctx) if err != nil { return MergeOutcome{}, fmt.Errorf("%w: reading the repository: %v", ErrMergeUncertain, err) } if st.Landed { // Already on the default branch: a request that reached the hub // before its answer was lost, or a person merged it. Never again. return m.landed(rec, st, true) } if st.Head != m.Commit { // The branch moved (or is gone) since it was judged: what is there // now was not checked or reviewed. return MergeOutcome{}, ErrMergeMoved } if !st.Unborn && (st.Default == "" || st.Default == m.Branch || !validRef(st.Default)) { return MergeOutcome{}, ErrMergeRefused } if !found || rec.Phase != mergeRequested { rec.Phase = mergePrepared if err := m.save(rec); err != nil { return MergeOutcome{}, ErrMergeUncertain } } before := rec.Phase if m.Preflight != nil && unresolved { // Not landed, and the earlier request is unresolved: a new one only // with write access confirmed; without it, still unknown. if err := m.Preflight(ctx); err != nil { return MergeOutcome{}, uncertain(MergeResult{}, err) } } if err := m.Confirm(ctx); err != nil { return MergeOutcome{}, fmt.Errorf("%w: confirming the lease: %v", ErrMergeUncertain, err) } rec.Phase = mergeRequested if err := m.save(rec); err != nil { return MergeOutcome{}, ErrMergeUncertain } if m.beforeRequest != nil { m.beforeRequest() } res, rerr := m.Request(ctx, MergeRequest{ExpectSHA: m.Commit, Message: m.Message, Strategy: m.Strategy, Agent: m.Agent}) var notSent *NotSentError if errors.As(rerr, ¬Sent) && before != mergeRequested { // Refused here before anything left for the hub, and no earlier // request is unresolved: definite, nothing to reconcile. The // record goes back to prepared, so a later Merge asks as usual. // After an unresolved request it is no answer at all: the default // branch decides below, and the record stays requested. rec.Phase = before if err := m.save(rec); err != nil { return MergeOutcome{}, ErrMergeUncertain } return MergeOutcome{}, rerr } if rerr == nil && res.Merged { rec.Phase, rec.SHA, rec.Into = mergeMerged, res.SHA, firstOf(res.Into, st.Default) if err := m.save(rec); err != nil { return MergeOutcome{}, ErrMergeUncertain } return MergeOutcome{SHA: rec.SHA, Into: rec.Into, Strategy: rec.Strategy, Source: SourceHub}, nil } if rerr == nil && st.Unborn && (res.Reason == "unborn_default" || res.Reason == "is_default") { // The hub cannot make the first merge yet: final for this request, // never sent again blind. return MergeOutcome{}, m.refused(rec, res, ErrMergeUnbornDefault) } if rerr != nil || res.Reason == "up_to_date" || res.Reason == "moved" || res.Reason == "no_such_branch" || res.Status >= 500 { // No answer, or one that may mean it landed after all: the default // branch decides. Not landed stays requested; the next call reads // the remote again before any new request. again, err := m.Inspect(ctx) if err == nil && again.Landed { return m.landed(rec, again, true) } if rerr != nil || res.Status >= 500 || err != nil { return MergeOutcome{}, uncertain(res, rerr) } if again.Head != m.Commit { return MergeOutcome{}, m.refused(rec, res, ErrMergeMoved) } if st.Unborn && again.Unborn { // Still no default branch, the branch where it was: the hub // could not create it. return MergeOutcome{}, m.refused(rec, res, ErrMergeUnbornDefault) } return MergeOutcome{}, m.refused(rec, res, ErrMergeFailed) } switch { case res.Reason == "conflicts": return MergeOutcome{}, m.refused(rec, res, ErrMergeConflict) case res.Reason == "ci_not_green" && (res.CIState == "pending" || res.CIState == "running" || res.CIState == "queued" || res.CIState == "unknown" || res.CIState == ""): return MergeOutcome{}, m.refused(rec, res, ErrMergeCIPending) case res.Reason == "ci_not_green": return MergeOutcome{}, m.refused(rec, res, ErrMergeCIFailed) case res.Status == http.StatusForbidden || res.Status == http.StatusNotFound || res.Status == http.StatusUnauthorized: return MergeOutcome{}, m.refused(rec, res, ErrMergeForbidden) } return MergeOutcome{}, m.refused(rec, res, ErrMergeFailed) } // refused records the hub's refusal (a new request may go later) and // returns err. func (m BranchMerge) refused(rec mergeRecord, res MergeResult, err error) error { rec.Phase, rec.Reason = mergeRefusedPh, res.Reason if serr := m.save(rec); serr != nil { return uncertain(res, nil) } if res.Status == 0 { return err } return hubError(res, err) } // SweepMerges removes merge records older than keep. func SweepMerges(root string, keep time.Duration) { paths, _ := filepath.Glob(filepath.Join(root, "merge-*.json")) for _, p := range paths { if info, err := os.Lstat(p); err == nil && info.Mode().IsRegular() && time.Since(info.ModTime()) > keep { os.Remove(p) os.Remove(p + ".lock") } } }