package thin import ( "amadan.net/oficina/equipo/internal/wire/forgekey" "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" "os" "os/exec" "path/filepath" "regexp" "slices" "strings" "sync" "syscall" "time" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/runner/workspace" ) // Forge is the runner's view of Amadan: which repositories it may work // on, how to reach them, and whether it may create one. Only the runner // holds the credential; no token leaves this package. type Forge interface { Host() string Propose(context.Context, Proposal) (ProposalRef, error) // Repos is the allowlist the runner advertises in hello. Repos() []string // Remote resolves a repository for git: URL and git password. Remote(ctx context.Context, repo string, use Use) (workspace.Remote, error) // CreateIn lists namespaces the runner's agent may create repositories in. CreateIn(ctx context.Context) []string // Create makes a new private repository and adds it to Repos. One that // exists already is added too, with ErrAdopted: it is not this runner's. Create(ctx context.Context, repo string) error // Reachable lists every repository the agent can reach, for the // context index. It includes Repos. Reachable(ctx context.Context) []string // Agent is the agent account's name, without the operator. Agent() string // Exists asks the forge, without a cache, whether repo exists. Exists(ctx context.Context, repo string) (bool, error) // Recheck makes the next Reachable ask the hub afresh. Recheck() // Merge asks the hub to merge a task branch into the default branch // (forge.MergeBranch decides when; this is the one request). Merge(ctx context.Context, repo, branch string, req forge.MergeRequest) (forge.MergeResult, error) } // ErrNoCreate means repositories cannot be created in that namespace. var ErrNoCreate = errors.New("repository creation is not available here") // ErrAdopted means Create did not make the repository: it existed, or the // hub's answer was lost and it exists now. It is adopted, and is not this // runner's to start. var ErrAdopted = errors.New("the repository already exists; adopted") // ErrEmptyRepo means the forge serves the repository and it has no // commits yet: no branch, nothing to read. It is not an access failure. var ErrEmptyRepo = errors.New("the repository has no commits yet") const nsPrefix = forgekey.Hub + "/" // ValidNewRepo is the hub's rule for a new repository name, under the // forge host: amadan.net//. func ValidNewRepo(repo string) bool { return forgekey.NewHubRepo(repo) } // fileForge reads the runner's forge credential file. Repositories the // runner created are kept in its own state directory, never written into // the credential file, and use the same agent credential. type fileForge struct { accessTargets func(context.Context) ([]string, error) accessAt time.Time accessRepos []string creds forge.FileCredentials created string hub string client *http.Client // Enabled turns repository creation on. Off, CreateIn is empty. enabled bool mu sync.Mutex ns []string nsAt time.Time listed []string // etag is the hub's validator for the last list, so a check that // finds nothing new costs a 304. etag string // listKey is scopeKey of the credential the list was fetched with. listKey string } // reachEvery is how long the hub's list of what the agent reaches is // trusted: a grant shows up within about a minute. const reachEvery = 55 * time.Second // NewFileForge serves the credential file at path; created repositories // are recorded in stateDir. func NewFileForge(path, stateDir string, create bool) Forge { 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} } func (f *fileForge) createdRepos() []string { raw, err := os.ReadFile(f.created) var out []string if err != nil || json.Unmarshal(raw, &out) != nil { return nil } return slices.DeleteFunc(out, func(r string) bool { return !forgekey.ValidHub(r) }) } // Repos is every repository the agent may work in: the credential // file's entries, those it created, and what the hub last said it reaches // (the agent-wide credential covers them all). func (f *fileForge) Repos() []string { names, err := f.creds.RepositoryNames() if err != nil { names = nil } f.mu.Lock() listed := slices.Clone(f.listed) f.mu.Unlock() out := append(append(slices.Clone(names), f.createdRepos()...), listed...) slices.Sort(out) return slices.Compact(out) } // agent is the agent-wide credential: one agent account serves every // repository it reaches. func (f *fileForge) agent(ctx context.Context) (forge.Credential, error) { c, err := f.creds.Agent(ctx) if err != nil { return forge.Credential{}, ErrNoCreate } return c, nil } // Recheck makes the next list ask the hub afresh. func (f *fileForge) Recheck() { f.mu.Lock() f.nsAt = time.Time{} f.etag = "" f.accessAt = time.Time{} f.mu.Unlock() } func (f *fileForge) Remote(ctx context.Context, repo string, use Use) (workspace.Remote, error) { if use != Read && use != Push { return workspace.Remote{}, workspace.ErrGitPassword } if use == Read { if !slices.Contains(f.Reachable(ctx), repo) { return workspace.Remote{}, workspace.ErrGitPassword } return f.remoteCredential(ctx, repo) } // A push: the repository's own entry, or the fallback with the hub's // current word (writeCredential). if names, _ := f.creds.RepositoryNames(); slices.Contains(names, repo) { return f.creds.Resolve(ctx, repo) } c, err := f.writeCredential(ctx, repo) if errors.Is(err, workspace.ErrHubUnavailable) { return workspace.Remote{}, workspace.ErrHubUnavailable } if err != nil || c.GitPassword == "" { return workspace.Remote{}, workspace.ErrGitPassword } return workspace.Remote{URL: "https://" + repo, GitPassword: c.GitPassword}, nil } func (f *fileForge) remoteCredential(ctx context.Context, repo string) (workspace.Remote, error) { if names, _ := f.creds.RepositoryNames(); slices.Contains(names, repo) { return f.creds.Resolve(ctx, repo) } // Created or reachable through the agent's namespace grant: the // agent-wide git password serves them. c, err := f.credential(ctx, repo) if err != nil || c.GitPassword == "" { return workspace.Remote{}, workspace.ErrGitPassword } return workspace.Remote{URL: "https://" + repo, GitPassword: c.GitPassword}, nil } // credential is the forge credential for repo, which the caller has // already found in scope (Reachable for reads, Repos for CI reads): its own // entry in the credential file, or else the agent-wide credential. A // repository with its own entry never falls back: an unusable entry is // refused, not replaced. Writes go through writeCredential, which also // needs the hub's current word for a fallback. func (f *fileForge) credential(ctx context.Context, repo string) (forge.Credential, error) { names, err := f.creds.RepositoryNames() if err != nil { return forge.Credential{}, err } if slices.Contains(names, repo) { return f.creds.Credential(ctx, repo) } if !forgekey.ValidHub(repo) { return forge.Credential{}, forge.ErrMergeNoCredential } c, err := f.creds.Agent(ctx) if err != nil { return forge.Credential{}, err } c.Remote = "https://" + repo return c, nil } // writeCredential is the credential a merge or a push to repo uses, or a // forge.NotSentError: the repository's own entry, else the agent-wide // credential, but only for a repository the hub lists now as writable, // in a list fetched with that same credential (writable). A repository // the runner created is no exception: a revoked grant, a rename or a // replaced credential ends its fallback. No usable credential is // ErrMergeNoCredential; no current write scope is a policy refusal. func (f *fileForge) writeCredential(ctx context.Context, repo string) (forge.Credential, error) { names, err := f.creds.RepositoryNames() if err != nil { return forge.Credential{}, forge.NotSent(repo, forge.ErrMergeNoCredential) } if slices.Contains(names, repo) { c, err := f.creds.Credential(ctx, repo) if err != nil { return forge.Credential{}, forge.NotSent(repo, forge.ErrMergeNoCredential) } return c, nil } if !forgekey.ValidHub(repo) { return forge.Credential{}, forge.NotSent(repo, errOutOfScope) } c, err := f.creds.Agent(ctx) if err != nil { return forge.Credential{}, forge.NotSent(repo, forge.ErrMergeNoCredential) } listed, confirmed := f.writable(ctx, repo, scopeKey(c)) if !confirmed { return forge.Credential{}, forge.NotSent(repo, workspace.ErrHubUnavailable) } if !listed { return forge.Credential{}, forge.NotSent(repo, errOutOfScope) } c.Remote = "https://" + repo return c, nil } // scopeKey names a credential without holding it: what the hub's list // was fetched with. func scopeKey(c forge.Credential) string { sum := sha256.Sum256([]byte(c.Agent + "\x00" + c.Bearer)) return hex.EncodeToString(sum[:]) } // writable asks the hub now whether it lists repo as writable with the // credential key names: confirmed is whether it answered (a list fetched // just now with that credential), listed whether the repository is in it. // A write is rare, so it never trusts the cached list; the request is // conditional (a 304 when nothing changed). Unconfirmed, the write waits. func (f *fileForge) writable(ctx context.Context, repo, key string) (listed, confirmed bool) { f.mu.Lock() f.nsAt = time.Time{} f.mu.Unlock() f.list(ctx) f.mu.Lock() defer f.mu.Unlock() confirmed = f.listKey == key && !f.nsAt.IsZero() return confirmed && slices.Contains(f.listed, repo), confirmed } // MergePreflight refuses, before anything is read or sent, a merge this // runner has no credential or no current write scope for. func (f *fileForge) MergePreflight(ctx context.Context, repo string) error { _, err := f.writeCredential(ctx, repo) return err } // The start check's warnings: a repository the runner created that has no // usable credential (its merges are refused), and a legacy credential // file whose per-repository bearer serves as the agent's. const ( createdNoCredential = "created repository has no usable forge credential; merges there will be refused" legacyAgentCredential = "forge credential file has no agent-wide entry; its shared per-repository credential serves as the agent's" ) // checkCreated warns once if the credential file is a legacy one, and, // with repository creation on, once per repository this runner created // that has no usable credential. It reads the files, never the hub, and // logs repositories, never a credential. func (f *fileForge) checkCreated(ctx context.Context, log *slog.Logger) { if log == nil { return } if f.creds.Legacy() { log.Warn(legacyAgentCredential) } if !f.enabled { return } for _, repo := range f.createdRepos() { if c, err := f.credential(ctx, repo); err != nil || c.Bearer == "" { log.Warn(createdNoCredential, "repo", repo) } } } // list asks the hub which repositories the agent may write to, at most // about once a minute and conditionally (If-None-Match). Writer rank also // creates repositories. func (f *fileForge) list(ctx context.Context) ([]string, []string) { f.mu.Lock() defer f.mu.Unlock() c, err := f.agent(ctx) if err != nil { f.listKey = "" return []string{}, []string{} } if key := scopeKey(c); key != f.listKey { // Another credential: what the hub said for the last one says // nothing about this one. f.ns, f.listed, f.nsAt, f.etag, f.listKey = nil, nil, time.Time{}, "", key } if time.Since(f.nsAt) < reachEvery && f.ns != nil { return slices.Clone(f.ns), slices.Clone(f.listed) } req, _ := http.NewRequestWithContext(ctx, "GET", f.hub+"/api/v1/repos", nil) req.Header.Set("Authorization", "Bearer "+c.Bearer) if f.etag != "" && f.ns != nil { req.Header.Set("If-None-Match", f.etag) } res, err := f.client.Do(req) if err != nil { return slices.Clone(f.ns), slices.Clone(f.listed) } defer res.Body.Close() if res.StatusCode == http.StatusNotModified && f.ns != nil { f.nsAt = time.Now() return slices.Clone(f.ns), slices.Clone(f.listed) } if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { // The hub answered: this credential reaches nothing (revoked, or // another's). A denial, not an outage. f.ns, f.listed, f.nsAt, f.etag = []string{}, []string{}, time.Now(), "" return []string{}, []string{} } var out struct { Repos []struct { NS string `json:"ns"` Name string `json:"name"` } `json:"repos"` } if res.StatusCode != 200 || json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&out) != nil { return slices.Clone(f.ns), slices.Clone(f.listed) } ns, repos := []string{}, []string{} for _, r := range out.Repos { if r.NS != "" && !slices.Contains(ns, r.NS) { ns = append(ns, r.NS) } if key := nsPrefix + r.NS + "/" + r.Name; forgekey.ValidHub(key) { repos = append(repos, key) } } slices.Sort(ns) slices.Sort(repos) f.ns, f.listed, f.nsAt, f.etag = ns, repos, time.Now(), res.Header.Get("ETag") return slices.Clone(ns), slices.Clone(repos) } func (f *fileForge) CreateIn(ctx context.Context) []string { if !f.enabled { return []string{} } ns, _ := f.list(ctx) return ns } func (f *fileForge) Reachable(ctx context.Context) []string { _, listed := f.list(ctx) out := append(append(f.Repos(), listed...), f.readGrants(ctx)...) slices.Sort(out) return slices.Compact(out) } func (f *fileForge) Agent() string { c, err := f.agent(context.Background()) if err != nil { return "" } name, _, _ := strings.Cut(c.Agent, "~") return name } // Exists asks the hub afresh whether repo is among the agent's writable // repositories (the namespace the agent creates in, under that name). func (f *fileForge) Exists(ctx context.Context, repo string) (bool, error) { f.mu.Lock() f.nsAt = time.Time{} f.mu.Unlock() _, listed := f.list(ctx) f.mu.Lock() fresh := !f.nsAt.IsZero() f.mu.Unlock() if !fresh { return false, ErrNoCreate } return slices.Contains(listed, repo), nil } // Create makes repo once: an existing one (an earlier answer was lost) is // adopted, and after any failure the hub is asked again before giving up. // Only the hub's own "created" answer makes it this runner's; an adopted // one returns ErrAdopted. func (f *fileForge) Create(ctx context.Context, repo string) error { parts := strings.Split(strings.TrimPrefix(repo, nsPrefix), "/") if !ValidNewRepo(repo) || !slices.Contains(f.CreateIn(ctx), parts[0]) { return ErrNoCreate } if ok, err := f.Exists(ctx, repo); err != nil { return err } else if ok { return f.adopt(repo) } c, err := f.agent(ctx) if err != nil { return err } body, _ := json.Marshal(map[string]string{"ns": parts[0], "name": parts[1], "tier": "private"}) req, _ := http.NewRequestWithContext(ctx, "POST", f.hub+"/api/v1/repos", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+c.Bearer) req.Header.Set("Content-Type", "application/json") res, err := f.client.Do(req) if err == nil { res.Body.Close() if res.StatusCode == 200 || res.StatusCode == 201 { return f.record(repo) } } // "Already exists", or no answer: someone else's, or not known to be ours. if ok, xerr := f.Exists(ctx, repo); xerr == nil && ok { return f.adopt(repo) } return ErrNoCreate } func (f *fileForge) adopt(repo string) error { if err := f.record(repo); err != nil { return err } return ErrAdopted } // errOutOfScope: the repository has no entry of its own in the credential // file and the hub does not list it now as the agent's to write (a read // grant, a revoked grant, a rename). A policy refusal. var errOutOfScope = fmt.Errorf("%w: not a repository this runner's agent may write now", forge.ErrMergeRefused) // Merge sends the hub the merge request with writeCredential's credential. // Without one it refuses before contacting the hub (forge.NotSent). func (f *fileForge) Merge(ctx context.Context, repo, branch string, req forge.MergeRequest) (forge.MergeResult, error) { c, err := f.writeCredential(ctx, repo) if err != nil { return forge.MergeResult{}, err } return forge.HubMerge(ctx, f.client, f.hub, c, repo, branch, req) } // CIHosted asks the hub whether it runs repo's CI on its own machines, // with the agent's credential for repo. func (f *fileForge) CIHosted(ctx context.Context, repo string) (bool, error) { c, err := f.ciCredential(ctx, repo) if err != nil { return false, err } return forge.HubCIHosted(ctx, f.client, f.hub, c, repo) } // CIStatus reads the hub's CI verdict on branch's tip in repo. func (f *fileForge) CIStatus(ctx context.Context, repo, branch, logs string) (forge.CIStatus, error) { c, err := f.ciCredential(ctx, repo) if err != nil { return forge.CIStatus{}, err } return forge.HubCIStatus(ctx, f.client, f.hub, c, repo, branch, logs) } func (f *fileForge) ciCredential(ctx context.Context, repo string) (forge.Credential, error) { f.list(ctx) if !slices.Contains(f.Repos(), repo) { return forge.Credential{}, forge.ErrCIRead } c, err := f.credential(ctx, repo) if err != nil { return forge.Credential{}, forge.ErrCIRead } return c, nil } // hostedCIOf is the forge's hosted CI reads, when it has them. func hostedCIOf(f Forge) HostedCI { if ci, ok := f.(HostedCI); ok { return ci } return nil } func (f *fileForge) record(repo string) error { f.mu.Lock() defer f.mu.Unlock() list := append(f.createdRepos(), repo) slices.Sort(list) raw, _ := json.Marshal(slices.Compact(list)) tmp := f.created + ".tmp" if err := os.WriteFile(tmp, raw, 0600); err != nil { return err } return os.Rename(tmp, f.created) } // Clones keeps one bare clone per project under the workspace root, // fetched on demand. Git runs with hooks, helpers and system config off; // the git password goes in an environment header, never argv or logs. type Clones struct { Root string Git string Forge Forge mu sync.Mutex } // Path is where repo's clone lives. func (c *Clones) Path(repo string) string { sum := sha256.Sum256([]byte(repo)) return filepath.Join(c.Root, "repos", hex.EncodeToString(sum[:6])+"-"+filepath.Base(repo)+".git") } // Ensure clones repo if it is not here yet and fetches its branches. func (c *Clones) Ensure(ctx context.Context, repo string) error { return c.fetch(ctx, repo, false, "") } // Shallow fetches only the tip of branch, for the context index. func (c *Clones) Shallow(ctx context.Context, repo, branch string) error { return c.fetch(ctx, repo, true, branch) } func (c *Clones) fetch(ctx context.Context, repo string, shallow bool, branch string) error { c.mu.Lock() defer c.mu.Unlock() if !forgekey.ValidHub(repo) { return ErrNoCreate } remote, err := readRemote(ctx, c.Forge, repo) if err != nil { return err } env, protocol, err := remoteEnv(remote) if err != nil { return err } dir := c.Path(repo) if err = os.MkdirAll(filepath.Dir(dir), 0700); err != nil { return err } git := func(args ...string) error { cmd := groupCommand(ctx, c.Git, args...) cmd.Dir = filepath.Dir(dir) for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } cmd.Stdout, cmd.Stderr = io.Discard, io.Discard return cmd.Run() } if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) { tmp := dir + ".new" os.RemoveAll(tmp) if err = git("init", "--bare", "--template=", "-q", tmp); err != nil { return err } if err = os.Rename(tmp, dir); err != nil { return err } } args := []string{"-C", dir, "-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false", "fetch", "-q", "--no-tags", "--no-recurse-submodules"} refspec := "+refs/heads/*:refs/heads/*" if shallow { if !validBranch(branch) { return ErrNoCreate } args = append(args, "--depth=1") refspec = "+refs/heads/" + branch + ":refs/heads/" + branch } else { args = append(args, "--prune") } if err := git(append(args, "--", remote.URL, refspec)...); err != nil { return err } if branch != "" { return git("-C", dir, "symbolic-ref", "HEAD", "refs/heads/"+branch) } return nil } var branchName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/-]{0,100}$`) func validBranch(b string) bool { return branchName.MatchString(b) && !strings.Contains(b, "..") } // groupCommand is a git command whose whole process group (git and its // remote helper) dies when ctx ends, and whose Wait does not hang on a // helper still holding its output. func groupCommand(ctx context.Context, name string, args ...string) *exec.Cmd { cmd := exec.CommandContext(ctx, name, args...) cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { if cmd.Process == nil { return nil } return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } cmd.WaitDelay = 5 * time.Second return cmd } // remoteEnv is git's environment for a resolved remote: no home, and the // password only in a header. A local path takes no password; an https // remote needs one. func remoteEnv(remote workspace.Remote) (map[string]string, string, error) { env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" if filepath.IsAbs(remote.URL) { if remote.GitPassword != "" { return nil, "", ErrNoCreate } return env, "file", nil } if remote.GitPassword == "" || !strings.HasPrefix(remote.URL, "https://") { return nil, "", workspace.ErrGitPassword } 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)) return env, "https", nil } // startDefaultGap runs between StartDefault's emptiness check and its // push; tests put another writer there. var startDefaultGap = func() {} // startDate makes the start commit the same bytes every time. const startDate = "2026-01-01T00:00:00+0000" // lsRefs reads ls-remote's lines: each ref once, without HEAD and without // the peeled lines of annotated tags (refs/tags/v1^{}), which are no refs // of their own. func lsRefs(out string) map[string]string { got := map[string]string{} for _, line := range strings.Split(out, "\n") { if sha, ref, ok := strings.Cut(line, "\t"); ok && ref != "HEAD" && !strings.HasSuffix(ref, "^{}") { got[ref] = sha } } return got } // StartDefault gives a repository this runner just created its default // branch before any task branch exists: main, at an empty first commit // with no parent. Task branches then start from main, and every merge // targets it. Left unborn, the hub made the first task branch pushed the // default, and a later task's merge was asked to merge into that // unrelated branch. A repository with any ref at all is left alone. // // Another writer may push between the check and the push. The start // commit is deterministic (fixed dates), so main is recognisable as this // start, and it is pushed create-only (an empty lease): a main of theirs // is never replaced, and is the default. Any other ref that does not // start from this main fails the start, now and on every retry; main is // withdrawn when the forge allows (only while it is still the start), so // no main unrelated to their work is left behind quietly. func (c *Clones) StartDefault(ctx context.Context, repo string) error { if !forgekey.ValidHub(repo) { return ErrNoCreate } remote, err := c.Forge.Remote(ctx, repo, Push) if err != nil { return err } refs := func() (map[string]string, error) { out, err := c.lsRemote(ctx, remote, "--", remote.URL) if err != nil { return nil, err } return lsRefs(string(out)), nil } env, protocol, err := remoteEnv(remote) if err != nil { return err } dir, err := os.MkdirTemp(c.Root, "start-") if err != nil { return err } defer os.RemoveAll(dir) 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} { env[k] = v } git := func(stdin string, args ...string) (string, error) { cmd := groupCommand(ctx, c.Git, append([]string{"-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false"}, args...)...) cmd.Dir = dir for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } cmd.Stdin, cmd.Stderr = strings.NewReader(stdin), io.Discard out, err := cmd.Output() return strings.TrimSpace(string(out)), err } if _, err := git("", "init", "-q", "--bare", "--template=", dir); err != nil { return err } tree, err := git("", "hash-object", "-t", "tree", "-w", "--stdin") if err != nil { return err } sha, err := git("Start the repository\n", "commit-tree", tree) if err != nil || !shaPattern.MatchString(sha) { return fmt.Errorf("start %s: no first commit", repo) } main := "refs/heads/" + unbornDefault have, err := refs() if err != nil { return err } if len(have) == 0 { startDefaultGap() _, perr := git("", "push", "-q", "--no-verify", "--force-with-lease="+main+":", "--", remote.URL, sha+":"+main) if have, err = refs(); err != nil { return err } if perr != nil && have[main] == "" { return fmt.Errorf("start %s: push main: %w", repo, perr) } } if have[main] != sha { return nil // refs of their own, or their main: left as they are } delete(have, main) if len(have) == 0 { return nil } if _, err := git("", "fetch", "-q", "--no-tags", "--", remote.URL, "+refs/*:refs/check/*"); err == nil { related := true for ref := range have { if _, err := git("", "merge-base", "--is-ancestor", sha, "refs/check/"+strings.TrimPrefix(ref, "refs/")); err != nil { related = false } } if related { return nil } } if _, err := git("", "push", "-q", "--no-verify", "--force-with-lease="+main+":"+sha, "--", remote.URL, ":"+main); err != nil { return fmt.Errorf("start %s: another writer's branch does not start from main, and main could not be withdrawn: %w", repo, err) } return fmt.Errorf("start %s: another writer's branch does not start from main; main withdrawn", repo) } // DefaultBranch asks the remote which branch HEAD names. func (c *Clones) DefaultBranch(ctx context.Context, repo string) (string, error) { remote, err := readRemote(ctx, c.Forge, repo) if err != nil { return "", err } out, err := c.lsRemote(ctx, remote, "--symref", "--", remote.URL, "HEAD") if err != nil { return "", err } for _, line := range strings.Split(string(out), "\n") { if rest, ok := strings.CutPrefix(line, "ref: refs/heads/"); ok { b, _, _ := strings.Cut(rest, "\t") if validBranch(b) && !taskBranch(b) { return b, nil } } } // No default branch at HEAD: none, or a task branch a hub rebuild // pointed HEAD at (a task branch is never the default). A repository // whose only refs are Equipo's task branches is empty: its default // branch has no commits yet (the first task pushes its own branch, // and only a merge makes the default branch). One with other refs but // no default is not readable here. if all, err := c.lsRemote(ctx, remote, "--", remote.URL); err == nil && onlyTaskBranches(string(all)) { return "", ErrEmptyRepo } return "", ErrNoCreate } // taskBranch reports whether b is one of Equipo's task branches. func taskBranch(b string) bool { return strings.HasPrefix(b, "equipo/") } // onlyTaskBranches reports whether ls-remote's output names no ref but // Equipo's task branches (none at all included), HEAD aside. func onlyTaskBranches(out string) bool { for _, line := range strings.Split(strings.TrimSpace(out), "\n") { if line == "" { continue } _, ref, ok := strings.Cut(line, "\t") if ok && ref == "HEAD" { // HEAD itself, resolved when a rebuild pointed it at a task // branch: not a branch of its own. continue } if !ok || !strings.HasPrefix(ref, "refs/heads/equipo/") { return false } } return true } // lsRemote runs git ls-remote against a resolved remote, its password in // a header and never in the URL or the environment's config files. func (c *Clones) lsRemote(ctx context.Context, remote workspace.Remote, args ...string) ([]byte, error) { env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" protocol := "https" if filepath.IsAbs(remote.URL) { protocol = "file" } else if 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)) } cmd := groupCommand(ctx, c.Git, append([]string{"-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false", "ls-remote"}, args...)...) cmd.Dir = c.Root for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } // git's own words on a failure (logged redacted, never reported raw). var stderr bytes.Buffer cmd.Stderr = &limitWriter{w: &stderr, n: 2 << 10} out, err := cmd.Output() if err != nil { return nil, fmt.Errorf("ls-remote: %w: %s", err, strings.TrimSpace(stderr.String())) } return out, nil }