oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "amadan.net/oficina/equipo/internal/wire/forgekey"
5 "bytes"
6 "context"
7 "crypto/sha256"
8 "encoding/base64"
9 "encoding/hex"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "io"
14 "log/slog"
15 "net/http"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "regexp"
20 "slices"
21 "strings"
22 "sync"
23 "syscall"
24 "time"
25
26 "amadan.net/oficina/equipo/internal/runner/forge"
27 "amadan.net/oficina/equipo/internal/runner/workspace"
28)
29
30// Forge is the runner's view of Amadan: which repositories it may work
31// on, how to reach them, and whether it may create one. Only the runner
32// holds the credential; no token leaves this package.
33type Forge interface {
34 Host() string
35 Propose(context.Context, Proposal) (ProposalRef, error)
36 // Repos is the allowlist the runner advertises in hello.
37 Repos() []string
38 // Remote resolves a repository for git: URL and git password.
39 Remote(ctx context.Context, repo string, use Use) (workspace.Remote, error)
40 // CreateIn lists namespaces the runner's agent may create repositories in.
41 CreateIn(ctx context.Context) []string
42 // Create makes a new private repository and adds it to Repos. One that
43 // exists already is added too, with ErrAdopted: it is not this runner's.
44 Create(ctx context.Context, repo string) error
45 // Reachable lists every repository the agent can reach, for the
46 // context index. It includes Repos.
47 Reachable(ctx context.Context) []string
48 // Agent is the agent account's name, without the operator.
49 Agent() string
50 // Exists asks the forge, without a cache, whether repo exists.
51 Exists(ctx context.Context, repo string) (bool, error)
52 // Recheck makes the next Reachable ask the hub afresh.
53 Recheck()
54 // Merge asks the hub to merge a task branch into the default branch
55 // (forge.MergeBranch decides when; this is the one request).
56 Merge(ctx context.Context, repo, branch string, req forge.MergeRequest) (forge.MergeResult, error)
57}
58
59// ErrNoCreate means repositories cannot be created in that namespace.
60var ErrNoCreate = errors.New("repository creation is not available here")
61
62// ErrAdopted means Create did not make the repository: it existed, or the
63// hub's answer was lost and it exists now. It is adopted, and is not this
64// runner's to start.
65var ErrAdopted = errors.New("the repository already exists; adopted")
66
67// ErrEmptyRepo means the forge serves the repository and it has no
68// commits yet: no branch, nothing to read. It is not an access failure.
69var ErrEmptyRepo = errors.New("the repository has no commits yet")
70
71const nsPrefix = forgekey.Hub + "/"
72
73// ValidNewRepo is the hub's rule for a new repository name, under the
74// forge host: amadan.net/<namespace>/<name>.
75func ValidNewRepo(repo string) bool { return forgekey.NewHubRepo(repo) }
76
77// fileForge reads the runner's forge credential file. Repositories the
78// runner created are kept in its own state directory, never written into
79// the credential file, and use the same agent credential.
80type fileForge struct {
81 accessTargets func(context.Context) ([]string, error)
82 accessAt time.Time
83 accessRepos []string
84 creds forge.FileCredentials
85 created string
86 hub string
87 client *http.Client
88 // Enabled turns repository creation on. Off, CreateIn is empty.
89 enabled bool
90
91 mu sync.Mutex
92 ns []string
93 nsAt time.Time
94 listed []string
95 // etag is the hub's validator for the last list, so a check that
96 // finds nothing new costs a 304.
97 etag string
98 // listKey is scopeKey of the credential the list was fetched with.
99 listKey string
100}
101
102// reachEvery is how long the hub's list of what the agent reaches is
103// trusted: a grant shows up within about a minute.
104const reachEvery = 55 * time.Second
105
106// NewFileForge serves the credential file at path; created repositories
107// are recorded in stateDir.
108func NewFileForge(path, stateDir string, create bool) Forge {
109 return &fileForge{creds: forge.FileCredentials{Path: path}, created: filepath.Join(stateDir, "created-repos.json"), hub: "https://amadan.net", client: &http.Client{Timeout: 30 * time.Second}, enabled: create}
110}
111
112func (f *fileForge) createdRepos() []string {
113 raw, err := os.ReadFile(f.created)
114 var out []string
115 if err != nil || json.Unmarshal(raw, &out) != nil {
116 return nil
117 }
118 return slices.DeleteFunc(out, func(r string) bool { return !forgekey.ValidHub(r) })
119}
120
121// Repos is every repository the agent may work in: the credential
122// file's entries, those it created, and what the hub last said it reaches
123// (the agent-wide credential covers them all).
124func (f *fileForge) Repos() []string {
125 names, err := f.creds.RepositoryNames()
126 if err != nil {
127 names = nil
128 }
129 f.mu.Lock()
130 listed := slices.Clone(f.listed)
131 f.mu.Unlock()
132 out := append(append(slices.Clone(names), f.createdRepos()...), listed...)
133 slices.Sort(out)
134 return slices.Compact(out)
135}
136
137// agent is the agent-wide credential: one agent account serves every
138// repository it reaches.
139func (f *fileForge) agent(ctx context.Context) (forge.Credential, error) {
140 c, err := f.creds.Agent(ctx)
141 if err != nil {
142 return forge.Credential{}, ErrNoCreate
143 }
144 return c, nil
145}
146
147// Recheck makes the next list ask the hub afresh.
148func (f *fileForge) Recheck() {
149 f.mu.Lock()
150 f.nsAt = time.Time{}
151 f.etag = ""
152 f.accessAt = time.Time{}
153 f.mu.Unlock()
154}
155
156func (f *fileForge) Remote(ctx context.Context, repo string, use Use) (workspace.Remote, error) {
157 if use != Read && use != Push {
158 return workspace.Remote{}, workspace.ErrGitPassword
159 }
160 if use == Read {
161 if !slices.Contains(f.Reachable(ctx), repo) {
162 return workspace.Remote{}, workspace.ErrGitPassword
163 }
164 return f.remoteCredential(ctx, repo)
165 }
166 // A push: the repository's own entry, or the fallback with the hub's
167 // current word (writeCredential).
168 if names, _ := f.creds.RepositoryNames(); slices.Contains(names, repo) {
169 return f.creds.Resolve(ctx, repo)
170 }
171 c, err := f.writeCredential(ctx, repo)
172 if errors.Is(err, workspace.ErrHubUnavailable) {
173 return workspace.Remote{}, workspace.ErrHubUnavailable
174 }
175 if err != nil || c.GitPassword == "" {
176 return workspace.Remote{}, workspace.ErrGitPassword
177 }
178 return workspace.Remote{URL: "https://" + repo, GitPassword: c.GitPassword}, nil
179}
180
181func (f *fileForge) remoteCredential(ctx context.Context, repo string) (workspace.Remote, error) {
182 if names, _ := f.creds.RepositoryNames(); slices.Contains(names, repo) {
183 return f.creds.Resolve(ctx, repo)
184 }
185 // Created or reachable through the agent's namespace grant: the
186 // agent-wide git password serves them.
187 c, err := f.credential(ctx, repo)
188 if err != nil || c.GitPassword == "" {
189 return workspace.Remote{}, workspace.ErrGitPassword
190 }
191 return workspace.Remote{URL: "https://" + repo, GitPassword: c.GitPassword}, nil
192}
193
194// credential is the forge credential for repo, which the caller has
195// already found in scope (Reachable for reads, Repos for CI reads): its own
196// entry in the credential file, or else the agent-wide credential. A
197// repository with its own entry never falls back: an unusable entry is
198// refused, not replaced. Writes go through writeCredential, which also
199// needs the hub's current word for a fallback.
200func (f *fileForge) credential(ctx context.Context, repo string) (forge.Credential, error) {
201 names, err := f.creds.RepositoryNames()
202 if err != nil {
203 return forge.Credential{}, err
204 }
205 if slices.Contains(names, repo) {
206 return f.creds.Credential(ctx, repo)
207 }
208 if !forgekey.ValidHub(repo) {
209 return forge.Credential{}, forge.ErrMergeNoCredential
210 }
211 c, err := f.creds.Agent(ctx)
212 if err != nil {
213 return forge.Credential{}, err
214 }
215 c.Remote = "https://" + repo
216 return c, nil
217}
218
219// writeCredential is the credential a merge or a push to repo uses, or a
220// forge.NotSentError: the repository's own entry, else the agent-wide
221// credential, but only for a repository the hub lists now as writable,
222// in a list fetched with that same credential (writable). A repository
223// the runner created is no exception: a revoked grant, a rename or a
224// replaced credential ends its fallback. No usable credential is
225// ErrMergeNoCredential; no current write scope is a policy refusal.
226func (f *fileForge) writeCredential(ctx context.Context, repo string) (forge.Credential, error) {
227 names, err := f.creds.RepositoryNames()
228 if err != nil {
229 return forge.Credential{}, forge.NotSent(repo, forge.ErrMergeNoCredential)
230 }
231 if slices.Contains(names, repo) {
232 c, err := f.creds.Credential(ctx, repo)
233 if err != nil {
234 return forge.Credential{}, forge.NotSent(repo, forge.ErrMergeNoCredential)
235 }
236 return c, nil
237 }
238 if !forgekey.ValidHub(repo) {
239 return forge.Credential{}, forge.NotSent(repo, errOutOfScope)
240 }
241 c, err := f.creds.Agent(ctx)
242 if err != nil {
243 return forge.Credential{}, forge.NotSent(repo, forge.ErrMergeNoCredential)
244 }
245 listed, confirmed := f.writable(ctx, repo, scopeKey(c))
246 if !confirmed {
247 return forge.Credential{}, forge.NotSent(repo, workspace.ErrHubUnavailable)
248 }
249 if !listed {
250 return forge.Credential{}, forge.NotSent(repo, errOutOfScope)
251 }
252 c.Remote = "https://" + repo
253 return c, nil
254}
255
256// scopeKey names a credential without holding it: what the hub's list
257// was fetched with.
258func scopeKey(c forge.Credential) string {
259 sum := sha256.Sum256([]byte(c.Agent + "\x00" + c.Bearer))
260 return hex.EncodeToString(sum[:])
261}
262
263// writable asks the hub now whether it lists repo as writable with the
264// credential key names: confirmed is whether it answered (a list fetched
265// just now with that credential), listed whether the repository is in it.
266// A write is rare, so it never trusts the cached list; the request is
267// conditional (a 304 when nothing changed). Unconfirmed, the write waits.
268func (f *fileForge) writable(ctx context.Context, repo, key string) (listed, confirmed bool) {
269 f.mu.Lock()
270 f.nsAt = time.Time{}
271 f.mu.Unlock()
272 f.list(ctx)
273 f.mu.Lock()
274 defer f.mu.Unlock()
275 confirmed = f.listKey == key && !f.nsAt.IsZero()
276 return confirmed && slices.Contains(f.listed, repo), confirmed
277}
278
279// MergePreflight refuses, before anything is read or sent, a merge this
280// runner has no credential or no current write scope for.
281func (f *fileForge) MergePreflight(ctx context.Context, repo string) error {
282 _, err := f.writeCredential(ctx, repo)
283 return err
284}
285
286// The start check's warnings: a repository the runner created that has no
287// usable credential (its merges are refused), and a legacy credential
288// file whose per-repository bearer serves as the agent's.
289const (
290 createdNoCredential = "created repository has no usable forge credential; merges there will be refused"
291 legacyAgentCredential = "forge credential file has no agent-wide entry; its shared per-repository credential serves as the agent's"
292)
293
294// checkCreated warns once if the credential file is a legacy one, and,
295// with repository creation on, once per repository this runner created
296// that has no usable credential. It reads the files, never the hub, and
297// logs repositories, never a credential.
298func (f *fileForge) checkCreated(ctx context.Context, log *slog.Logger) {
299 if log == nil {
300 return
301 }
302 if f.creds.Legacy() {
303 log.Warn(legacyAgentCredential)
304 }
305 if !f.enabled {
306 return
307 }
308 for _, repo := range f.createdRepos() {
309 if c, err := f.credential(ctx, repo); err != nil || c.Bearer == "" {
310 log.Warn(createdNoCredential, "repo", repo)
311 }
312 }
313}
314
315// list asks the hub which repositories the agent may write to, at most
316// about once a minute and conditionally (If-None-Match). Writer rank also
317// creates repositories.
318func (f *fileForge) list(ctx context.Context) ([]string, []string) {
319 f.mu.Lock()
320 defer f.mu.Unlock()
321 c, err := f.agent(ctx)
322 if err != nil {
323 f.listKey = ""
324 return []string{}, []string{}
325 }
326 if key := scopeKey(c); key != f.listKey {
327 // Another credential: what the hub said for the last one says
328 // nothing about this one.
329 f.ns, f.listed, f.nsAt, f.etag, f.listKey = nil, nil, time.Time{}, "", key
330 }
331 if time.Since(f.nsAt) < reachEvery && f.ns != nil {
332 return slices.Clone(f.ns), slices.Clone(f.listed)
333 }
334 req, _ := http.NewRequestWithContext(ctx, "GET", f.hub+"/api/v1/repos", nil)
335 req.Header.Set("Authorization", "Bearer "+c.Bearer)
336 if f.etag != "" && f.ns != nil {
337 req.Header.Set("If-None-Match", f.etag)
338 }
339 res, err := f.client.Do(req)
340 if err != nil {
341 return slices.Clone(f.ns), slices.Clone(f.listed)
342 }
343 defer res.Body.Close()
344 if res.StatusCode == http.StatusNotModified && f.ns != nil {
345 f.nsAt = time.Now()
346 return slices.Clone(f.ns), slices.Clone(f.listed)
347 }
348 if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
349 // The hub answered: this credential reaches nothing (revoked, or
350 // another's). A denial, not an outage.
351 f.ns, f.listed, f.nsAt, f.etag = []string{}, []string{}, time.Now(), ""
352 return []string{}, []string{}
353 }
354 var out struct {
355 Repos []struct {
356 NS string `json:"ns"`
357 Name string `json:"name"`
358 } `json:"repos"`
359 }
360 if res.StatusCode != 200 || json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&out) != nil {
361 return slices.Clone(f.ns), slices.Clone(f.listed)
362 }
363 ns, repos := []string{}, []string{}
364 for _, r := range out.Repos {
365 if r.NS != "" && !slices.Contains(ns, r.NS) {
366 ns = append(ns, r.NS)
367 }
368 if key := nsPrefix + r.NS + "/" + r.Name; forgekey.ValidHub(key) {
369 repos = append(repos, key)
370 }
371 }
372 slices.Sort(ns)
373 slices.Sort(repos)
374 f.ns, f.listed, f.nsAt, f.etag = ns, repos, time.Now(), res.Header.Get("ETag")
375 return slices.Clone(ns), slices.Clone(repos)
376}
377
378func (f *fileForge) CreateIn(ctx context.Context) []string {
379 if !f.enabled {
380 return []string{}
381 }
382 ns, _ := f.list(ctx)
383 return ns
384}
385
386func (f *fileForge) Reachable(ctx context.Context) []string {
387 _, listed := f.list(ctx)
388 out := append(append(f.Repos(), listed...), f.readGrants(ctx)...)
389 slices.Sort(out)
390 return slices.Compact(out)
391}
392
393func (f *fileForge) Agent() string {
394 c, err := f.agent(context.Background())
395 if err != nil {
396 return ""
397 }
398 name, _, _ := strings.Cut(c.Agent, "~")
399 return name
400}
401
402// Exists asks the hub afresh whether repo is among the agent's writable
403// repositories (the namespace the agent creates in, under that name).
404func (f *fileForge) Exists(ctx context.Context, repo string) (bool, error) {
405 f.mu.Lock()
406 f.nsAt = time.Time{}
407 f.mu.Unlock()
408 _, listed := f.list(ctx)
409 f.mu.Lock()
410 fresh := !f.nsAt.IsZero()
411 f.mu.Unlock()
412 if !fresh {
413 return false, ErrNoCreate
414 }
415 return slices.Contains(listed, repo), nil
416}
417
418// Create makes repo once: an existing one (an earlier answer was lost) is
419// adopted, and after any failure the hub is asked again before giving up.
420// Only the hub's own "created" answer makes it this runner's; an adopted
421// one returns ErrAdopted.
422func (f *fileForge) Create(ctx context.Context, repo string) error {
423 parts := strings.Split(strings.TrimPrefix(repo, nsPrefix), "/")
424 if !ValidNewRepo(repo) || !slices.Contains(f.CreateIn(ctx), parts[0]) {
425 return ErrNoCreate
426 }
427 if ok, err := f.Exists(ctx, repo); err != nil {
428 return err
429 } else if ok {
430 return f.adopt(repo)
431 }
432 c, err := f.agent(ctx)
433 if err != nil {
434 return err
435 }
436 body, _ := json.Marshal(map[string]string{"ns": parts[0], "name": parts[1], "tier": "private"})
437 req, _ := http.NewRequestWithContext(ctx, "POST", f.hub+"/api/v1/repos", bytes.NewReader(body))
438 req.Header.Set("Authorization", "Bearer "+c.Bearer)
439 req.Header.Set("Content-Type", "application/json")
440 res, err := f.client.Do(req)
441 if err == nil {
442 res.Body.Close()
443 if res.StatusCode == 200 || res.StatusCode == 201 {
444 return f.record(repo)
445 }
446 }
447 // "Already exists", or no answer: someone else's, or not known to be ours.
448 if ok, xerr := f.Exists(ctx, repo); xerr == nil && ok {
449 return f.adopt(repo)
450 }
451 return ErrNoCreate
452}
453
454func (f *fileForge) adopt(repo string) error {
455 if err := f.record(repo); err != nil {
456 return err
457 }
458 return ErrAdopted
459}
460
461// errOutOfScope: the repository has no entry of its own in the credential
462// file and the hub does not list it now as the agent's to write (a read
463// grant, a revoked grant, a rename). A policy refusal.
464var errOutOfScope = fmt.Errorf("%w: not a repository this runner's agent may write now", forge.ErrMergeRefused)
465
466// Merge sends the hub the merge request with writeCredential's credential.
467// Without one it refuses before contacting the hub (forge.NotSent).
468func (f *fileForge) Merge(ctx context.Context, repo, branch string, req forge.MergeRequest) (forge.MergeResult, error) {
469 c, err := f.writeCredential(ctx, repo)
470 if err != nil {
471 return forge.MergeResult{}, err
472 }
473 return forge.HubMerge(ctx, f.client, f.hub, c, repo, branch, req)
474}
475
476// CIHosted asks the hub whether it runs repo's CI on its own machines,
477// with the agent's credential for repo.
478func (f *fileForge) CIHosted(ctx context.Context, repo string) (bool, error) {
479 c, err := f.ciCredential(ctx, repo)
480 if err != nil {
481 return false, err
482 }
483 return forge.HubCIHosted(ctx, f.client, f.hub, c, repo)
484}
485
486// CIStatus reads the hub's CI verdict on branch's tip in repo.
487func (f *fileForge) CIStatus(ctx context.Context, repo, branch, logs string) (forge.CIStatus, error) {
488 c, err := f.ciCredential(ctx, repo)
489 if err != nil {
490 return forge.CIStatus{}, err
491 }
492 return forge.HubCIStatus(ctx, f.client, f.hub, c, repo, branch, logs)
493}
494
495func (f *fileForge) ciCredential(ctx context.Context, repo string) (forge.Credential, error) {
496 f.list(ctx)
497 if !slices.Contains(f.Repos(), repo) {
498 return forge.Credential{}, forge.ErrCIRead
499 }
500 c, err := f.credential(ctx, repo)
501 if err != nil {
502 return forge.Credential{}, forge.ErrCIRead
503 }
504 return c, nil
505}
506
507// hostedCIOf is the forge's hosted CI reads, when it has them.
508func hostedCIOf(f Forge) HostedCI {
509 if ci, ok := f.(HostedCI); ok {
510 return ci
511 }
512 return nil
513}
514
515func (f *fileForge) record(repo string) error {
516 f.mu.Lock()
517 defer f.mu.Unlock()
518 list := append(f.createdRepos(), repo)
519 slices.Sort(list)
520 raw, _ := json.Marshal(slices.Compact(list))
521 tmp := f.created + ".tmp"
522 if err := os.WriteFile(tmp, raw, 0600); err != nil {
523 return err
524 }
525 return os.Rename(tmp, f.created)
526}
527
528// Clones keeps one bare clone per project under the workspace root,
529// fetched on demand. Git runs with hooks, helpers and system config off;
530// the git password goes in an environment header, never argv or logs.
531type Clones struct {
532 Root string
533 Git string
534 Forge Forge
535
536 mu sync.Mutex
537}
538
539// Path is where repo's clone lives.
540func (c *Clones) Path(repo string) string {
541 sum := sha256.Sum256([]byte(repo))
542 return filepath.Join(c.Root, "repos", hex.EncodeToString(sum[:6])+"-"+filepath.Base(repo)+".git")
543}
544
545// Ensure clones repo if it is not here yet and fetches its branches.
546func (c *Clones) Ensure(ctx context.Context, repo string) error {
547 return c.fetch(ctx, repo, false, "")
548}
549
550// Shallow fetches only the tip of branch, for the context index.
551func (c *Clones) Shallow(ctx context.Context, repo, branch string) error {
552 return c.fetch(ctx, repo, true, branch)
553}
554
555func (c *Clones) fetch(ctx context.Context, repo string, shallow bool, branch string) error {
556 c.mu.Lock()
557 defer c.mu.Unlock()
558 if !forgekey.ValidHub(repo) {
559 return ErrNoCreate
560 }
561 remote, err := readRemote(ctx, c.Forge, repo)
562 if err != nil {
563 return err
564 }
565 env, protocol, err := remoteEnv(remote)
566 if err != nil {
567 return err
568 }
569 dir := c.Path(repo)
570 if err = os.MkdirAll(filepath.Dir(dir), 0700); err != nil {
571 return err
572 }
573 git := func(args ...string) error {
574 cmd := groupCommand(ctx, c.Git, args...)
575 cmd.Dir = filepath.Dir(dir)
576 for k, v := range env {
577 cmd.Env = append(cmd.Env, k+"="+v)
578 }
579 cmd.Stdout, cmd.Stderr = io.Discard, io.Discard
580 return cmd.Run()
581 }
582 if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
583 tmp := dir + ".new"
584 os.RemoveAll(tmp)
585 if err = git("init", "--bare", "--template=", "-q", tmp); err != nil {
586 return err
587 }
588 if err = os.Rename(tmp, dir); err != nil {
589 return err
590 }
591 }
592 args := []string{"-C", dir, "-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false", "fetch", "-q", "--no-tags", "--no-recurse-submodules"}
593 refspec := "+refs/heads/*:refs/heads/*"
594 if shallow {
595 if !validBranch(branch) {
596 return ErrNoCreate
597 }
598 args = append(args, "--depth=1")
599 refspec = "+refs/heads/" + branch + ":refs/heads/" + branch
600 } else {
601 args = append(args, "--prune")
602 }
603 if err := git(append(args, "--", remote.URL, refspec)...); err != nil {
604 return err
605 }
606 if branch != "" {
607 return git("-C", dir, "symbolic-ref", "HEAD", "refs/heads/"+branch)
608 }
609 return nil
610}
611
612var branchName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/-]{0,100}$`)
613
614func validBranch(b string) bool { return branchName.MatchString(b) && !strings.Contains(b, "..") }
615
616// groupCommand is a git command whose whole process group (git and its
617// remote helper) dies when ctx ends, and whose Wait does not hang on a
618// helper still holding its output.
619func groupCommand(ctx context.Context, name string, args ...string) *exec.Cmd {
620 cmd := exec.CommandContext(ctx, name, args...)
621 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
622 cmd.Cancel = func() error {
623 if cmd.Process == nil {
624 return nil
625 }
626 return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
627 }
628 cmd.WaitDelay = 5 * time.Second
629 return cmd
630}
631
632// remoteEnv is git's environment for a resolved remote: no home, and the
633// password only in a header. A local path takes no password; an https
634// remote needs one.
635func remoteEnv(remote workspace.Remote) (map[string]string, string, error) {
636 env := workspace.GitEnvironment()
637 env["HOME"] = "/nonexistent"
638 if filepath.IsAbs(remote.URL) {
639 if remote.GitPassword != "" {
640 return nil, "", ErrNoCreate
641 }
642 return env, "file", nil
643 }
644 if remote.GitPassword == "" || !strings.HasPrefix(remote.URL, "https://") {
645 return nil, "", workspace.ErrGitPassword
646 }
647 env["GIT_CONFIG_COUNT"] = "10"
648 env["GIT_CONFIG_KEY_9"] = "http.extraHeader"
649 env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(remote.Username()+":"+remote.GitPassword))
650 return env, "https", nil
651}
652
653// startDefaultGap runs between StartDefault's emptiness check and its
654// push; tests put another writer there.
655var startDefaultGap = func() {}
656
657// startDate makes the start commit the same bytes every time.
658const startDate = "2026-01-01T00:00:00+0000"
659
660// lsRefs reads ls-remote's lines: each ref once, without HEAD and without
661// the peeled lines of annotated tags (refs/tags/v1^{}), which are no refs
662// of their own.
663func lsRefs(out string) map[string]string {
664 got := map[string]string{}
665 for _, line := range strings.Split(out, "\n") {
666 if sha, ref, ok := strings.Cut(line, "\t"); ok && ref != "HEAD" && !strings.HasSuffix(ref, "^{}") {
667 got[ref] = sha
668 }
669 }
670 return got
671}
672
673// StartDefault gives a repository this runner just created its default
674// branch before any task branch exists: main, at an empty first commit
675// with no parent. Task branches then start from main, and every merge
676// targets it. Left unborn, the hub made the first task branch pushed the
677// default, and a later task's merge was asked to merge into that
678// unrelated branch. A repository with any ref at all is left alone.
679//
680// Another writer may push between the check and the push. The start
681// commit is deterministic (fixed dates), so main is recognisable as this
682// start, and it is pushed create-only (an empty lease): a main of theirs
683// is never replaced, and is the default. Any other ref that does not
684// start from this main fails the start, now and on every retry; main is
685// withdrawn when the forge allows (only while it is still the start), so
686// no main unrelated to their work is left behind quietly.
687func (c *Clones) StartDefault(ctx context.Context, repo string) error {
688 if !forgekey.ValidHub(repo) {
689 return ErrNoCreate
690 }
691 remote, err := c.Forge.Remote(ctx, repo, Push)
692 if err != nil {
693 return err
694 }
695 refs := func() (map[string]string, error) {
696 out, err := c.lsRemote(ctx, remote, "--", remote.URL)
697 if err != nil {
698 return nil, err
699 }
700 return lsRefs(string(out)), nil
701 }
702 env, protocol, err := remoteEnv(remote)
703 if err != nil {
704 return err
705 }
706 dir, err := os.MkdirTemp(c.Root, "start-")
707 if err != nil {
708 return err
709 }
710 defer os.RemoveAll(dir)
711 for k, v := range map[string]string{"GIT_DIR": dir, "GIT_AUTHOR_NAME": commitName, "GIT_AUTHOR_EMAIL": commitEmail, "GIT_COMMITTER_NAME": commitName, "GIT_COMMITTER_EMAIL": commitEmail, "GIT_AUTHOR_DATE": startDate, "GIT_COMMITTER_DATE": startDate} {
712 env[k] = v
713 }
714 git := func(stdin string, args ...string) (string, error) {
715 cmd := groupCommand(ctx, c.Git, append([]string{"-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false"}, args...)...)
716 cmd.Dir = dir
717 for k, v := range env {
718 cmd.Env = append(cmd.Env, k+"="+v)
719 }
720 cmd.Stdin, cmd.Stderr = strings.NewReader(stdin), io.Discard
721 out, err := cmd.Output()
722 return strings.TrimSpace(string(out)), err
723 }
724 if _, err := git("", "init", "-q", "--bare", "--template=", dir); err != nil {
725 return err
726 }
727 tree, err := git("", "hash-object", "-t", "tree", "-w", "--stdin")
728 if err != nil {
729 return err
730 }
731 sha, err := git("Start the repository\n", "commit-tree", tree)
732 if err != nil || !shaPattern.MatchString(sha) {
733 return fmt.Errorf("start %s: no first commit", repo)
734 }
735 main := "refs/heads/" + unbornDefault
736 have, err := refs()
737 if err != nil {
738 return err
739 }
740 if len(have) == 0 {
741 startDefaultGap()
742 _, perr := git("", "push", "-q", "--no-verify", "--force-with-lease="+main+":", "--", remote.URL, sha+":"+main)
743 if have, err = refs(); err != nil {
744 return err
745 }
746 if perr != nil && have[main] == "" {
747 return fmt.Errorf("start %s: push main: %w", repo, perr)
748 }
749 }
750 if have[main] != sha {
751 return nil // refs of their own, or their main: left as they are
752 }
753 delete(have, main)
754 if len(have) == 0 {
755 return nil
756 }
757 if _, err := git("", "fetch", "-q", "--no-tags", "--", remote.URL, "+refs/*:refs/check/*"); err == nil {
758 related := true
759 for ref := range have {
760 if _, err := git("", "merge-base", "--is-ancestor", sha, "refs/check/"+strings.TrimPrefix(ref, "refs/")); err != nil {
761 related = false
762 }
763 }
764 if related {
765 return nil
766 }
767 }
768 if _, err := git("", "push", "-q", "--no-verify", "--force-with-lease="+main+":"+sha, "--", remote.URL, ":"+main); err != nil {
769 return fmt.Errorf("start %s: another writer's branch does not start from main, and main could not be withdrawn: %w", repo, err)
770 }
771 return fmt.Errorf("start %s: another writer's branch does not start from main; main withdrawn", repo)
772}
773
774// DefaultBranch asks the remote which branch HEAD names.
775func (c *Clones) DefaultBranch(ctx context.Context, repo string) (string, error) {
776 remote, err := readRemote(ctx, c.Forge, repo)
777 if err != nil {
778 return "", err
779 }
780 out, err := c.lsRemote(ctx, remote, "--symref", "--", remote.URL, "HEAD")
781 if err != nil {
782 return "", err
783 }
784 for _, line := range strings.Split(string(out), "\n") {
785 if rest, ok := strings.CutPrefix(line, "ref: refs/heads/"); ok {
786 b, _, _ := strings.Cut(rest, "\t")
787 if validBranch(b) && !taskBranch(b) {
788 return b, nil
789 }
790 }
791 }
792 // No default branch at HEAD: none, or a task branch a hub rebuild
793 // pointed HEAD at (a task branch is never the default). A repository
794 // whose only refs are Equipo's task branches is empty: its default
795 // branch has no commits yet (the first task pushes its own branch,
796 // and only a merge makes the default branch). One with other refs but
797 // no default is not readable here.
798 if all, err := c.lsRemote(ctx, remote, "--", remote.URL); err == nil && onlyTaskBranches(string(all)) {
799 return "", ErrEmptyRepo
800 }
801 return "", ErrNoCreate
802}
803
804// taskBranch reports whether b is one of Equipo's task branches.
805func taskBranch(b string) bool { return strings.HasPrefix(b, "equipo/") }
806
807// onlyTaskBranches reports whether ls-remote's output names no ref but
808// Equipo's task branches (none at all included), HEAD aside.
809func onlyTaskBranches(out string) bool {
810 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
811 if line == "" {
812 continue
813 }
814 _, ref, ok := strings.Cut(line, "\t")
815 if ok && ref == "HEAD" {
816 // HEAD itself, resolved when a rebuild pointed it at a task
817 // branch: not a branch of its own.
818 continue
819 }
820 if !ok || !strings.HasPrefix(ref, "refs/heads/equipo/") {
821 return false
822 }
823 }
824 return true
825}
826
827// lsRemote runs git ls-remote against a resolved remote, its password in
828// a header and never in the URL or the environment's config files.
829func (c *Clones) lsRemote(ctx context.Context, remote workspace.Remote, args ...string) ([]byte, error) {
830 env := workspace.GitEnvironment()
831 env["HOME"] = "/nonexistent"
832 protocol := "https"
833 if filepath.IsAbs(remote.URL) {
834 protocol = "file"
835 } else if remote.GitPassword != "" {
836 env["GIT_CONFIG_COUNT"] = "10"
837 env["GIT_CONFIG_KEY_9"] = "http.extraHeader"
838 env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(remote.Username()+":"+remote.GitPassword))
839 }
840 cmd := groupCommand(ctx, c.Git, append([]string{"-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false", "ls-remote"}, args...)...)
841 cmd.Dir = c.Root
842 for k, v := range env {
843 cmd.Env = append(cmd.Env, k+"="+v)
844 }
845 // git's own words on a failure (logged redacted, never reported raw).
846 var stderr bytes.Buffer
847 cmd.Stderr = &limitWriter{w: &stderr, n: 2 << 10}
848 out, err := cmd.Output()
849 if err != nil {
850 return nil, fmt.Errorf("ls-remote: %w: %s", err, strings.TrimSpace(stderr.String()))
851 }
852 return out, nil
853}
854