internal/control/runnerrepo.go

210 lines · 7347 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"slices"
  8	"strings"
  9
 10	"golang.org/x/crypto/ssh"
 11
 12	"gitbay.org/gitbay/internal/ci"
 13	"gitbay.org/gitbay/internal/policy"
 14	"gitbay.org/gitbay/internal/protocol"
 15	"gitbay.org/gitbay/internal/store"
 16)
 17
 18// Runners attached to a repository (#184). A runner key claims builds only
 19// for the repositories it is attached to; a repository admin attaches it
 20// by pasting the runner's public key. The key lands on the admin's own
 21// account with scope runner, which confines it to the runner protocol and
 22// read-only git.
 23func init() {
 24	register(Command{Path: []string{"repo", "runner", "add"},
 25		Summary: "attach a runner's public key to a repository",
 26		Usage:   "repo runner add <owner/name> [--jobs <job,...>|all] < key.pub",
 27		Flags: []Flag{
 28			{"--jobs", "<job,...>", "claim only these jobs here; all restores every job", "every job, or as before on a re-add"},
 29		},
 30		Examples:        []string{"repo runner add krz/gitbay < key.pub", "repo runner add krz/app --jobs gitbay-security < key.pub"},
 31		ReadsStdin:      true,
 32		MintsCredential: true, NeedsRecentSignIn: true, Run: runRepoRunnerAdd})
 33	register(Command{Path: []string{"repo", "runner", "list"},
 34		Summary:  "list the runners attached to a repository",
 35		Usage:    "repo runner list <owner/name>",
 36		Examples: []string{"repo runner list krz/gitbay"},
 37		ReadOnly: true, Run: runRepoRunnerList})
 38	register(Command{Path: []string{"repo", "runner", "remove"},
 39		Summary:  "detach a runner from a repository",
 40		Usage:    "repo runner remove <owner/name> <fingerprint>",
 41		Examples: []string{"repo runner remove krz/gitbay SHA256:abcd1234"},
 42		Run:      runRepoRunnerRemove})
 43}
 44
 45func runRepoRunnerAdd(c *Ctx, args []string) int {
 46	f, err := c.parseArgs(args, flagSpec{Values: []string{"--jobs"}, MaxPos: 1, Usage: c.Cmd.Usage})
 47	if err != nil || len(f.Pos) != 1 {
 48		return c.usage()
 49	}
 50	var jobs []string
 51	if v := f.Value("--jobs"); v != "" && v != "all" {
 52		for _, j := range strings.Split(v, ",") {
 53			if !ci.ValidJobName(j) {
 54				return c.fail(protocol.ExitUsage, "bad job name %q", j)
 55			}
 56			if !slices.Contains(jobs, j) {
 57				jobs = append(jobs, j)
 58			}
 59		}
 60	}
 61	repo, code := resolveRepo(c, f.Pos[0], policy.CanAdmin)
 62	if code >= 0 {
 63		return code
 64	}
 65	raw, err := io.ReadAll(io.LimitReader(c.Stdin, 64<<10))
 66	if err != nil {
 67		return c.fail(protocol.ExitFailure, "reading key: %v", err)
 68	}
 69	pub, comment, _, _, err := ssh.ParseAuthorizedKey(raw)
 70	if err != nil {
 71		return c.fail(protocol.ExitUsage, "not a valid public key in authorized_keys format: %v", err)
 72	}
 73	fp := ssh.FingerprintSHA256(pub)
 74	key, err := c.Store.SSHKeyByFingerprint(fp)
 75	switch {
 76	case errors.Is(err, store.ErrNotFound):
 77		label, _ := keyLabel(comment)
 78		if err := c.Store.AddSSHKeyFrom(c.User.ID, fp, pub.Type(), pub.Marshal(), "runner", label, store.KeyOrigin{CreatedByToken: c.TokenID}); err != nil {
 79			return c.fail(protocol.ExitFailure, "adding key: %v", err)
 80		}
 81		if key, err = c.Store.SSHKeyByFingerprint(fp); err != nil {
 82			return c.fail(protocol.ExitFailure, "%v", err)
 83		}
 84	case err != nil:
 85		return c.fail(protocol.ExitFailure, "%v", err)
 86	case key.Scope != "runner":
 87		// A full key would let a build step administer the account; a
 88		// deploy key is bound elsewhere. A runner gets a key of its own.
 89		return c.fail(protocol.ExitDenied, "%s is a %s key, not a runner key; give the runner a key of its own", fp, key.Scope)
 90	case key.UserID != c.User.ID && !c.User.IsAdmin:
 91		return c.fail(protocol.ExitDenied, "%s belongs to another account", fp)
 92	}
 93	// The runner clones what it builds, so the key's account must be able
 94	// to read the repository. The caller's own key needs no check: they
 95	// hold admin on the repository to get here.
 96	if key.UserID != c.User.ID {
 97		owner, err := c.Store.UserByID(key.UserID)
 98		if err != nil {
 99			return c.fail(protocol.ExitFailure, "%v", err)
100		}
101		grant, err := c.Store.AccessRole(repo.ID, owner.ID)
102		if err != nil {
103			return c.fail(protocol.ExitFailure, "%v", err)
104		}
105		if !policy.CanRead(owner, repo, grant) {
106			return c.fail(protocol.ExitDenied, "%s belongs to %s, who cannot read %s", fp, owner.Username, repo.Path())
107		}
108	}
109	if err := c.Store.AttachRunner(key.ID, repo.ID); err != nil {
110		return c.fail(protocol.ExitFailure, "%v", err)
111	}
112	// Without --jobs a re-add leaves the attachment's jobs as they were.
113	if f.Has("--jobs") {
114		if err := c.Store.SetRunnerJobs(key.ID, repo.ID, jobs); err != nil {
115			return c.fail(protocol.ExitFailure, "%v", err)
116		}
117	}
118	audit := map[string]any{"repo": repo.Path(), "fingerprint": fp}
119	if f.Has("--jobs") {
120		audit["jobs"] = strings.Join(jobs, ",")
121	}
122	c.Store.Audit(c.User.ID, "repo.runner.add", audit)
123	d := map[string]any{"fingerprint": fp, "repo": repo.Path()}
124	if len(jobs) > 0 {
125		d["jobs"] = jobs
126	}
127	return c.emit(d, func(w io.Writer) {
128		if len(jobs) > 0 {
129			fmt.Fprintf(w, "runner %s attached to %s for %s\n", fp, repo.Path(), strings.Join(jobs, ", "))
130			return
131		}
132		fmt.Fprintf(w, "runner %s attached to %s\n", fp, repo.Path())
133	})
134}
135
136func runRepoRunnerList(c *Ctx, args []string) int {
137	if len(args) != 1 {
138		return c.usage()
139	}
140	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
141	if code >= 0 {
142		return code
143	}
144	runners, err := c.Store.ListRepoRunners(repo.ID)
145	if err != nil {
146		return c.fail(protocol.ExitFailure, "%v", err)
147	}
148	if runners == nil {
149		runners = []store.RepoRunner{}
150	}
151	return c.emitView(runners, func(w io.Writer) {
152		tb := c.table(w, "FINGERPRINT", "ALGO", "USER", "SEEN", "HELD", "JOBS")
153		for _, r := range runners {
154			seen := r.LastSeen
155			if seen == "" {
156				seen = "never"
157			}
158			held := "idle"
159			if r.BuildNumber != 0 {
160				held = fmt.Sprintf("%s #%d %s since %s", r.BuildRepo, r.BuildNumber, r.BuildJob, r.StartedAt)
161			}
162			jobs := "all"
163			if len(r.Jobs) > 0 {
164				jobs = strings.Join(r.Jobs, ",")
165			}
166			tb.row(cRef(r.Fingerprint), cText(r.Algo), cText(r.Username), cAge(seen), cText(held), cText(jobs))
167		}
168		tb.flush()
169	}, func() screen {
170		rows := make([]row, len(runners))
171		for i, r := range runners {
172			lead, held := cGlyph(""), ""
173			if r.BuildNumber != 0 {
174				lead, held = cGlyph("running"), fmt.Sprintf("building %s #%d %s", r.BuildRepo, r.BuildNumber, r.BuildJob)
175			}
176			seen := "never seen"
177			if r.LastSeen != "" {
178				seen = "seen " + relAge(r.LastSeen, termNow())
179			}
180			only := ""
181			if len(r.Jobs) > 0 {
182				only = "only " + strings.Join(r.Jobs, ",")
183			}
184			rows[i] = rowOf(cFlexRef(r.Fingerprint), lead, cText(r.Username), cMeta(r.Algo, seen, held, only))
185		}
186		return listScreen("Runners", rows,
187			action{"Runners", []string{"repo", "runner", "remove", repo.Path(), "<fingerprint>"}},
188		)
189	})
190}
191
192func runRepoRunnerRemove(c *Ctx, args []string) int {
193	if len(args) != 2 {
194		return c.usage()
195	}
196	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
197	if code >= 0 {
198		return code
199	}
200	if err := c.Store.DetachRunner(repo.ID, args[1]); err != nil {
201		if errors.Is(err, store.ErrNotFound) {
202			return c.fail(protocol.ExitNotFound, "no runner %s on %s", args[1], repo.Path())
203		}
204		return c.fail(protocol.ExitFailure, "%v", err)
205	}
206	c.Store.Audit(c.User.ID, "repo.runner.remove", map[string]any{"repo": repo.Path(), "fingerprint": args[1]})
207	return c.emit(map[string]string{"removed": args[1]}, func(w io.Writer) {
208		fmt.Fprintf(w, "runner %s detached from %s\n", args[1], repo.Path())
209	})
210}