oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package forge
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/base64"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "regexp"
16 "slices"
17 "strings"
18 "syscall"
19
20 "amadan.net/oficina/equipo/internal/runner/workspace"
21)
22
23// Branch publication errors. Only ErrPushRefused and ErrPushConflict are
24// final; ErrPushUncertain is settled by the next PushBranch for the key.
25var (
26 ErrPushRefused = errors.New("forge: push refused by validation")
27 ErrPushConflict = errors.New("forge: the branch moved")
28 ErrPushUncertain = errors.New("forge: push outcome unknown")
29)
30
31// BranchPush is one candidate commit for a task's own branch. Forge
32// validates the repository, the branch (equipo/..., never the default
33// branch), the candidate (a descendant of the base in the runner's
34// private repository) and the person, records its intent before any
35// network write, and reconciles a push cut off midway from the record.
36type BranchPush struct {
37 ExpectedHead string
38 // Root keeps the publication records (private, 0700).
39 Root string
40 Git string
41 // GitDir is the runner's private repository holding Commit; no
42 // namespace ever sees it.
43 GitDir string
44 Repo string
45 Branch string
46 // Default is the repository's default branch, never pushed. Base is
47 // the commit Commit was made on, or "" when the repository had none
48 // (Commit is then its initial commit).
49 Default string
50 Base string
51 Commit string
52 // Key names the attempt (task/step/attempt), one record each.
53 Key string
54 // Person is whose task this is; Owners are the persons this runner
55 // executes for.
56 Person string
57 Owners []string
58 // Remote resolves the URL and git password just in time.
59 Remote func(context.Context) (workspace.Remote, error)
60 // Confirm checks the execution lease with the instance; it runs right
61 // before the push and a failure stops it.
62 Confirm func(context.Context) error
63 // beforePush runs right before the push (tests move the branch).
64 beforePush func()
65}
66
67type pushRecord struct {
68 Key string `json:"key"`
69 Repo string `json:"repo"`
70 Branch string `json:"branch"`
71 Commit string `json:"commit"`
72 Phase string `json:"phase"`
73 // Expected is the head the push replaces ("" for no branch), fixed
74 // before the first push (Observed); only that head may be replaced.
75 Expected string `json:"expected"`
76 Observed bool `json:"observed"`
77}
78
79var taskRef = regexp.MustCompile(`^equipo/[a-z0-9]+(?:-[a-z0-9]+)*$`)
80
81func (b BranchPush) validate() error {
82 if b.ExpectedHead != "" && !object.MatchString(b.ExpectedHead) {
83 return ErrPushRefused
84 }
85 if !validRepository(b.Repo) || !validRef(b.Branch) || !taskRef.MatchString(b.Branch) || len(b.Branch) > 100 || b.Branch == b.Default || !validRef(b.Default) ||
86 !object.MatchString(b.Commit) || b.Base != "" && (!object.MatchString(b.Base) || len(b.Commit) != len(b.Base)) || b.Commit == b.Base ||
87 !filepath.IsAbs(b.GitDir) || !filepath.IsAbs(b.Root) || !filepath.IsAbs(b.Git) || b.Key == "" || b.Remote == nil || b.Confirm == nil ||
88 b.Person == "" || !slices.Contains(b.Owners, b.Person) {
89 return ErrPushRefused
90 }
91 return nil
92}
93
94// path is the attempt's record file.
95func (b BranchPush) path() string {
96 sum := sha256.Sum256([]byte(b.Key))
97 return filepath.Join(b.Root, "push-"+hex.EncodeToString(sum[:12])+".json")
98}
99
100// git runs git with hooks, helpers, system and global config off, the
101// password only in an environment header.
102func (b BranchPush) git(ctx context.Context, dir string, remote *workspace.Remote, args ...string) (string, error) {
103 protocol := "https"
104 if remote != nil && filepath.IsAbs(remote.URL) {
105 protocol = "file"
106 }
107 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...)
108 cmd := exec.CommandContext(ctx, b.Git, args...)
109 cmd.Dir = dir
110 env := workspace.GitEnvironment()
111 env["HOME"] = "/nonexistent"
112 env["GIT_DIR"] = b.GitDir
113 if remote != nil && remote.GitPassword != "" {
114 env["GIT_CONFIG_COUNT"] = "10"
115 env["GIT_CONFIG_KEY_9"] = "http.extraHeader"
116 env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(remote.Username()+":"+remote.GitPassword))
117 }
118 for k, v := range env {
119 cmd.Env = append(cmd.Env, k+"="+v)
120 }
121 var stderr bytes.Buffer
122 cmd.Stderr = &capWriter{w: &stderr, n: 8 << 10}
123 out, err := cmd.Output()
124 if err != nil {
125 return "", &gitAnswer{err: err, refusal: pushRefusalOf(string(out) + "\n" + stderr.String()), text: pushAnswer(string(out), stderr.String(), remote)}
126 }
127 return strings.TrimSpace(string(out)), nil
128}
129
130func (b BranchPush) save(r pushRecord) error {
131 raw, _ := json.Marshal(r)
132 tmp := b.path() + ".tmp"
133 f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0600)
134 if err != nil {
135 return err
136 }
137 if _, err = f.Write(raw); err == nil {
138 err = f.Sync()
139 }
140 if cerr := f.Close(); err == nil {
141 err = cerr
142 }
143 if err != nil {
144 return err
145 }
146 if err = os.Rename(tmp, b.path()); err != nil {
147 return err
148 }
149 dir, err := os.Open(b.Root)
150 if err != nil {
151 return err
152 }
153 defer dir.Close()
154 return dir.Sync()
155}
156
157// ours lists the commits Equipo itself pushed to this branch, from the
158// records of earlier attempts: a new attempt may replace only those.
159func (b BranchPush) ours() map[string]bool {
160 out := map[string]bool{}
161 paths, _ := filepath.Glob(filepath.Join(b.Root, "push-*.json"))
162 for _, p := range paths {
163 var r pushRecord
164 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") {
165 out[r.Commit] = true
166 }
167 }
168 return out
169}
170
171func (b BranchPush) load() (pushRecord, bool, error) {
172 var r pushRecord
173 raw, err := os.ReadFile(b.path())
174 if errors.Is(err, os.ErrNotExist) {
175 return r, false, nil
176 }
177 if err != nil || json.Unmarshal(raw, &r) != nil {
178 return r, false, ErrPushUncertain
179 }
180 return r, true, nil
181}
182
183// head reads the branch's tip on the remote; "" when it does not exist.
184func (b BranchPush) head(ctx context.Context, remote workspace.Remote) (string, error) {
185 ref := "refs/heads/" + b.Branch
186 out, err := b.git(ctx, b.Root, &remote, "ls-remote", "--refs", "--", remote.URL, ref)
187 if err != nil {
188 return "", pushError("ls-remote", err, ErrPushUncertain)
189 }
190 fields := strings.Fields(out)
191 if len(fields) == 0 {
192 return "", nil
193 }
194 if len(fields) != 2 || !object.MatchString(fields[0]) || fields[1] != ref {
195 return "", ErrPushUncertain
196 }
197 return fields[0], nil
198}
199
200// remote resolves the repository's remote and checks it is that one.
201func (b BranchPush) remote(ctx context.Context) (workspace.Remote, error) {
202 remote, err := b.Remote(ctx)
203 if errors.Is(err, workspace.ErrHubUnavailable) {
204 // Write access could not be confirmed: worth trying again.
205 return workspace.Remote{}, fmt.Errorf("resolving the remote: %w", err)
206 }
207 if err != nil {
208 return workspace.Remote{}, fmt.Errorf("%w: resolving the remote: %v", ErrPushRefused, err)
209 }
210 if remote.URL == "" || !filepath.IsAbs(remote.URL) && (remote.URL != "https://"+b.Repo || remote.GitPassword == "") || filepath.IsAbs(remote.URL) && remote.GitPassword != "" {
211 return workspace.Remote{}, ErrPushRefused
212 }
213 return remote, nil
214}
215
216// PushBranch publishes Commit to Branch once. A record is written before
217// any network write; a later call for the same key reconciles from the
218// remote (the branch already at Commit is success) instead of pushing
219// blind. The lease is confirmed right before the push.
220func PushBranch(ctx context.Context, b BranchPush) error {
221 if err := b.validate(); err != nil {
222 return err
223 }
224 if err := os.MkdirAll(b.Root, 0700); err != nil {
225 return ErrPushUncertain
226 }
227 lock, err := os.OpenFile(b.path()+".lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600)
228 if err != nil {
229 return ErrPushUncertain
230 }
231 defer lock.Close()
232 if syscall.Flock(int(lock.Fd()), syscall.LOCK_EX) != nil {
233 return ErrPushUncertain
234 }
235 rec, found, err := b.load()
236 if err != nil {
237 return err
238 }
239 if found && (rec.Key != b.Key || rec.Repo != b.Repo || rec.Branch != b.Branch || rec.Commit != b.Commit) {
240 return ErrPushRefused
241 }
242 // A push that may have landed reconciles from the remote first: it is
243 // done if the branch is at the candidate, even if the runner lost its
244 // local objects since.
245 if found && (rec.Phase == "push_started" || rec.Phase == "published") {
246 remote, err := b.remote(ctx)
247 if err != nil {
248 return err
249 }
250 head, err := b.head(ctx, remote)
251 if err != nil {
252 return err
253 }
254 if head == b.Commit {
255 rec.Phase = "published"
256 return b.save(rec)
257 }
258 }
259 // The candidate is what the runner committed: a commit descending from
260 // the base, complete and well formed in its private repository.
261 if id, err := b.git(ctx, b.Root, nil, "rev-parse", "--verify", "--end-of-options", b.Commit+"^{commit}"); err != nil || id != b.Commit {
262 return ErrPushRefused
263 }
264 if b.Base == "" {
265 // No base: the repository had no commits, so the candidate is its
266 // initial commit and has no parent.
267 if out, err := b.git(ctx, b.Root, nil, "rev-list", "--parents", "-n", "1", "--end-of-options", b.Commit); err != nil || out != b.Commit {
268 return ErrPushRefused
269 }
270 } else if _, err := b.git(ctx, b.Root, nil, "merge-base", "--is-ancestor", b.Base, b.Commit); err != nil {
271 return ErrPushRefused
272 }
273 if _, err := b.git(ctx, b.Root, nil, "fsck", "--no-reflogs", "--connectivity-only", b.Commit); err != nil {
274 return ErrPushRefused
275 }
276 if !found {
277 rec = pushRecord{Key: b.Key, Repo: b.Repo, Branch: b.Branch, Commit: b.Commit, Phase: "prepared"}
278 if err := b.save(rec); err != nil {
279 return ErrPushUncertain
280 }
281 }
282 remote, err := b.remote(ctx)
283 if err != nil {
284 return err
285 }
286 head, err := b.head(ctx, remote)
287 if err != nil {
288 return err
289 }
290 if head == b.Commit {
291 rec.Phase = "published"
292 return b.save(rec)
293 }
294 if b.ExpectedHead != "" && head != b.ExpectedHead {
295 return ErrPushConflict
296 }
297 if !rec.Observed {
298 // The predecessor is fixed once, before the first push: no branch
299 // yet, or a commit an earlier attempt of Equipo's pushed there.
300 if head != "" && !b.ours()[head] {
301 return ErrPushConflict
302 }
303 rec.Expected, rec.Observed = head, true
304 if err := b.save(rec); err != nil {
305 return ErrPushUncertain
306 }
307 }
308 if head != rec.Expected {
309 // Someone moved the branch since: never push over their work.
310 return ErrPushConflict
311 }
312 if err := b.Confirm(ctx); err != nil {
313 return fmt.Errorf("%w: confirming the lease: %v", ErrPushUncertain, err)
314 }
315 rec.Phase = "push_started"
316 if err := b.save(rec); err != nil {
317 return ErrPushUncertain
318 }
319 if b.beforePush != nil {
320 b.beforePush()
321 }
322 _, 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)
323 after, err := b.head(ctx, remote)
324 switch {
325 case err != nil && perr != nil:
326 // git's answer to the push says more than the read after it.
327 return pushError("push", perr, ErrPushUncertain)
328 case err != nil:
329 return err
330 case after == b.Commit:
331 rec.Phase = "published"
332 return b.save(rec)
333 case perr != nil && after != head:
334 return pushError("push", perr, ErrPushConflict)
335 case perr != nil:
336 return pushError("push", perr, ErrPushUncertain)
337 }
338 return fmt.Errorf("%w: git push succeeded but the branch is not at the commit", ErrPushUncertain)
339}
340