internal/control/admin.go

fc755889baf27e51072434797bb4de2076d3f7eb
gitbay/internal/control/admin.go

700 lines · 23583 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"slices"
  8	"strconv"
  9	"strings"
 10	"time"
 11
 12	"gitbay.org/gitbay/internal/gitutil"
 13	"gitbay.org/gitbay/internal/protocol"
 14	"gitbay.org/gitbay/internal/store"
 15)
 16
 17func init() {
 18	register(Command{Path: []string{"admin", "user", "list"},
 19		Summary: "list accounts (instance admins)",
 20		Usage:   "admin user list [--state active|pending|disabled|admin] [--limit <n>] [--cursor <c>]",
 21		Flags: []Flag{
 22			{"--state", "active|pending|disabled|admin", "which accounts", ""},
 23			{"--limit", "<n>", "rows per page", ""},
 24			{"--cursor", "<c>", "continue from the previous page", ""},
 25		},
 26		Examples: []string{"admin user list --state pending"},
 27		ReadOnly: true, Run: runAdminUserList})
 28	register(Command{Path: []string{"admin", "user", "show"},
 29		Summary:  "show an account: keys, emails, orgs, tokens, sessions (instance admins)",
 30		Usage:    "admin user show <username>",
 31		Examples: []string{"admin user show alice"},
 32		ReadOnly: true, Run: runAdminUserShow})
 33	register(Command{Path: []string{"admin", "user", "promote"},
 34		NeedsRecentSignIn: true,
 35		Summary:           "make an account an instance admin",
 36		Usage:             "admin user promote <username>",
 37		Examples:          []string{"admin user promote alice"},
 38		Run:               runAdminUserPromote})
 39	register(Command{Path: []string{"admin", "user", "demote"},
 40		Summary:  "remove instance admin from an account (never the last one)",
 41		Usage:    "admin user demote <username>",
 42		Examples: []string{"admin user demote alice"},
 43		Run:      runAdminUserDemote})
 44	register(Command{Path: []string{"admin", "runners"},
 45		Summary:  "the build queue and runner accounts: last poll, scope, the build each holds (instance admins)",
 46		Usage:    "admin runners",
 47		Examples: []string{"admin runners"},
 48		ReadOnly: true, Run: runAdminRunners})
 49	register(Command{Path: []string{"admin", "runners", "remove"},
 50		Summary:  "drop a key's runner heartbeat row, e.g. one that polled once by mistake (instance admins)",
 51		Usage:    "admin runners remove <fingerprint>",
 52		Examples: []string{"admin runners remove SHA256:abcd1234"},
 53		Run:      runAdminRunnersForget})
 54	// forget is the name this shipped under in v1.18; remove is the verb
 55	// every other noun uses. Both stay for one release.
 56	register(Command{Path: []string{"admin", "runners", "forget"},
 57		Summary:  "alias of admin runners remove",
 58		Usage:    "admin runners forget <fingerprint>",
 59		Examples: []string{"admin runners forget SHA256:abcd1234"},
 60		Run:      runAdminRunnersForget})
 61	register(Command{Path: []string{"admin", "repo", "list"},
 62		Summary: "list every repository with size and last push (instance admins)",
 63		Usage:   "admin repo list [--owner <name>] [--visibility public|private] [--limit <n>] [--cursor <c>]",
 64		Flags: []Flag{
 65			{"--owner", "<name>", "only this owner's repositories", ""},
 66			{"--visibility", "public|private", "which repositories", ""},
 67			{"--limit", "<n>", "rows per page", ""},
 68			{"--cursor", "<c>", "continue from the previous page", ""},
 69		},
 70		Examples: []string{"admin repo list --owner alice"},
 71		ReadOnly: true, Run: runAdminRepoList})
 72	register(Command{Path: []string{"admin", "repo", "archive"},
 73		Summary:  "archive any repository (instance admins; audited)",
 74		Usage:    "admin repo archive <owner/name>",
 75		Examples: []string{"admin repo archive alice/old-project"},
 76		Run:      runAdminRepoArchive})
 77	register(Command{Path: []string{"admin", "repo", "unarchive"},
 78		Summary:  "unarchive any repository (instance admins; audited)",
 79		Usage:    "admin repo unarchive <owner/name>",
 80		Examples: []string{"admin repo unarchive alice/old-project"},
 81		Run:      runAdminRepoUnarchive})
 82	register(Command{Path: []string{"admin", "repo", "visibility"},
 83		Summary:  "set any repository's visibility (instance admins; audited)",
 84		Usage:    "admin repo visibility <owner/name> public|private",
 85		Examples: []string{"admin repo visibility alice/secret private"},
 86		Run:      runAdminRepoVisibility})
 87	register(Command{Path: []string{"admin", "repo", "delete"},
 88		Summary: "delete any repository (instance admins; audited)",
 89		Usage:   "admin repo delete <owner/name> --yes",
 90		Flags: []Flag{
 91			{"--yes", "", "confirm the permanent delete", ""},
 92		},
 93		Examples: []string{"admin repo delete alice/spam --yes"},
 94		Run:      runAdminRepoDelete})
 95	register(Command{Path: []string{"admin", "mr", "prune"},
 96		Summary: "drop merged or closed MRs' head refs and the objects only they kept, e.g. after a history rewrite (instance admins; audited)",
 97		Usage:   "admin mr prune <owner/name> <n> [<n>...] --yes",
 98		Flags: []Flag{
 99			{"--yes", "", "confirm the permanent prune", ""},
100		},
101		Examples: []string{"admin mr prune krz/gitbay 12 13 --yes"},
102		Run:      runAdminMRPrune})
103}
104
105// requireInstanceAdmin gates the admin noun. -1 means proceed.
106func requireInstanceAdmin(c *Ctx) int {
107	if !c.User.IsAdmin {
108		return c.fail(protocol.ExitDenied, "admin commands are for instance admins; ask one")
109	}
110	return -1
111}
112
113// adminUserOut is one account row, shared by list and show.
114type adminUserOut struct {
115	Username  string `json:"username"`
116	State     string `json:"state"` // active | pending | disabled
117	Admin     bool   `json:"admin"`
118	CreatedAt string `json:"created_at"`
119	LastSeen  string `json:"last_seen,omitempty"`
120}
121
122func adminUserRow(u store.AdminUser) adminUserOut {
123	state := "active"
124	switch {
125	case u.Disabled:
126		state = "disabled"
127	case u.Pending:
128		state = "pending"
129	}
130	return adminUserOut{u.Username, state, u.IsAdmin, u.CreatedAt, u.LastSeen}
131}
132
133func runAdminUserList(c *Ctx, args []string) int {
134	if code := requireInstanceAdmin(c); code >= 0 {
135		return code
136	}
137	args, p, code := parsePageFlags(c, args, "admin-user", false)
138	if code >= 0 {
139		return code
140	}
141	f, err := c.parseArgs(args, flagSpec{Values: []string{"--state"}, MaxPos: 0,
142		Usage: "admin user list [--state active|pending|disabled|admin] [--limit <n>] [--cursor <c>]"})
143	if err != nil {
144		return c.fail(protocol.ExitUsage, "%v", err)
145	}
146	state := f.Value("--state")
147	switch state {
148	case "", "active", "pending", "disabled", "admin":
149	default:
150		return c.fail(protocol.ExitUsage, "--state requires active|pending|disabled|admin")
151	}
152	users, err := c.Store.ListUsers(state, p.queryLimit(), p.key)
153	if err != nil {
154		return c.fail(protocol.ExitFailure, "%v", err)
155	}
156	users, next := trimPage(p, users, "admin-user", func(u store.AdminUser) string { return u.Username })
157	var ds []adminUserOut
158	for _, u := range users {
159		ds = append(ds, adminUserRow(u))
160	}
161	return c.emitPage(p, ds, next, func(w io.Writer) {
162		tb := c.table(w, "USERNAME", "STATE", "ADMIN", "CREATED", "LAST SEEN")
163		for _, d := range ds {
164			mark := ""
165			if d.Admin {
166				mark = "admin"
167			}
168			tb.row(cRef(d.Username), cState(d.State), cText(mark), cAge(d.CreatedAt), cAge(d.LastSeen))
169		}
170		tb.flush()
171	})
172}
173
174func runAdminUserShow(c *Ctx, args []string) int {
175	if code := requireInstanceAdmin(c); code >= 0 {
176		return code
177	}
178	if len(args) != 1 {
179		return c.usage()
180	}
181	name := args[0]
182	u, err := c.Store.UserByUsername(name)
183	if errors.Is(err, store.ErrNotFound) {
184		return c.fail(protocol.ExitNotFound, "no user %q", name)
185	} else if err != nil {
186		return c.fail(protocol.ExitFailure, "%v", err)
187	}
188	row, err := c.Store.AdminUserByName(name)
189	if err != nil {
190		return c.fail(protocol.ExitFailure, "%v", err)
191	}
192
193	type keyOut struct {
194		Fingerprint string `json:"fingerprint"`
195		Algo        string `json:"algo"`
196		Scope       string `json:"scope"`
197		Label       string `json:"label"`
198		CreatedAt   string `json:"created_at"`
199		LastUsedAt  string `json:"last_used_at,omitempty"`
200	}
201	type emailOut struct {
202		Address    string `json:"address"`
203		Verified   bool   `json:"verified"`
204		VerifiedBy string `json:"verified_by,omitempty"` // smtp | admin
205		Primary    bool   `json:"primary"`
206	}
207	type pgpOut struct {
208		Fingerprint string     `json:"fingerprint"`
209		ExpiresAt   *time.Time `json:"expires_at,omitempty"`
210		RevokedAt   *time.Time `json:"revoked_at,omitempty"`
211	}
212	type orgOut struct {
213		Org  string `json:"org"`
214		Role string `json:"role"`
215	}
216	type tokenOut struct {
217		Name       string     `json:"name"`
218		Scope      string     `json:"scope"`
219		CreatedAt  string     `json:"created_at"`
220		ExpiresAt  *time.Time `json:"expires_at,omitempty"`
221		LastUsedAt *time.Time `json:"last_used_at,omitempty"`
222	}
223	type out struct {
224		adminUserOut
225		Keys        []keyOut   `json:"keys"`
226		Emails      []emailOut `json:"emails"`
227		PGPKeys     []pgpOut   `json:"pgp_keys"`
228		Orgs        []orgOut   `json:"orgs"`
229		Repos       int64      `json:"repos"`
230		RepoLimit   int64      `json:"repo_limit"` // 0 unlimited
231		ByteLimit   int64      `json:"byte_limit"` // 0 unlimited
232		APITokens   []tokenOut `json:"api_tokens"`
233		WebSessions int64      `json:"web_sessions"`
234	}
235	d := out{adminUserOut: adminUserRow(row),
236		Keys: []keyOut{}, Emails: []emailOut{}, PGPKeys: []pgpOut{}, Orgs: []orgOut{}, APITokens: []tokenOut{}}
237
238	keys, err := c.Store.ListSSHKeys(u.ID)
239	if err != nil {
240		return c.fail(protocol.ExitFailure, "%v", err)
241	}
242	for _, k := range keys {
243		d.Keys = append(d.Keys, keyOut{k.Fingerprint, k.Algo, k.Scope, k.Label, k.CreatedAt, k.LastUsedAt})
244	}
245	emails, err := c.Store.ListEmails(u.ID)
246	if err != nil {
247		return c.fail(protocol.ExitFailure, "%v", err)
248	}
249	for _, e := range emails {
250		d.Emails = append(d.Emails, emailOut{e.Address, e.Verified, e.VerifiedBy, e.Primary})
251	}
252	pgp, err := c.Store.ListPGPKeys(u.ID)
253	if err != nil {
254		return c.fail(protocol.ExitFailure, "%v", err)
255	}
256	for _, k := range pgp {
257		d.PGPKeys = append(d.PGPKeys, pgpOut{k.Fingerprint, k.ExpiresAt, k.RevokedAt})
258	}
259	orgs, err := c.Store.ListOrgsForUser(u.ID)
260	if err != nil {
261		return c.fail(protocol.ExitFailure, "%v", err)
262	}
263	for _, m := range orgs {
264		d.Orgs = append(d.Orgs, orgOut{m.Username, m.Role})
265	}
266	if d.Repos, err = c.Store.OwnedRepoCount(u.ID); err != nil {
267		return c.fail(protocol.ExitFailure, "%v", err)
268	}
269	d.RepoLimit = RepoLimit(c.Store, limitsOf(c), u.ID)
270	d.ByteLimit = ByteLimit(c.Store, limitsOf(c), u.ID)
271	tokens, err := c.Store.ListAPITokens(u.ID)
272	if err != nil {
273		return c.fail(protocol.ExitFailure, "%v", err)
274	}
275	for _, t := range tokens {
276		d.APITokens = append(d.APITokens, tokenOut{t.Name, t.Scope, t.CreatedAt, t.ExpiresAt, t.LastUsedAt})
277	}
278	if d.WebSessions, err = c.Store.WebSessionCount(u.ID); err != nil {
279		return c.fail(protocol.ExitFailure, "%v", err)
280	}
281
282	return c.emit(d, func(w io.Writer) {
283		admin := ""
284		if d.Admin {
285			admin = "yes"
286		}
287		v := c.view(w)
288		v.title(d.Username, "", d.State)
289		v.fields(
290			"admin", admin,
291			"created", c.when(d.CreatedAt),
292			"last seen", c.when(d.LastSeen),
293			"repos", fmt.Sprintf("%d", d.Repos),
294			"web sessions", fmt.Sprintf("%d", d.WebSessions),
295		)
296		if len(d.Keys) > 0 {
297			v.section("keys")
298			tk := c.table(w, "FINGERPRINT", "ALGO", "SCOPE", "LAST USED")
299			for _, k := range d.Keys {
300				tk.row(cFlex(k.Fingerprint), cText(k.Algo), cState(k.Scope), cAge(k.LastUsedAt))
301			}
302			tk.flush()
303		}
304		if len(d.Emails) > 0 {
305			v.section("emails")
306			te := c.table(w, "ADDRESS", "STATE")
307			for _, e := range d.Emails {
308				state := "unverified"
309				if e.Verified {
310					state = "verified by " + e.VerifiedBy
311				}
312				cells := []cell{cRef(e.Address), cState(state)}
313				if e.Primary {
314					cells = append(cells, cText("primary"))
315				}
316				te.row(cells...)
317			}
318			te.flush()
319		}
320		if len(d.PGPKeys) > 0 {
321			v.section("pgp keys")
322			tp := c.table(w, "FINGERPRINT")
323			for _, k := range d.PGPKeys {
324				tp.row(cFlex(k.Fingerprint))
325			}
326			tp.flush()
327		}
328		if len(d.Orgs) > 0 {
329			v.section("orgs")
330			to := c.table(w, "ORG", "ROLE")
331			for _, o := range d.Orgs {
332				to.row(cRef(o.Org), cState(o.Role))
333			}
334			to.flush()
335		}
336		if len(d.APITokens) > 0 {
337			v.section("api tokens")
338			tt := c.table(w, "NAME", "SCOPE", "LAST USED")
339			for _, t := range d.APITokens {
340				used := ""
341				if t.LastUsedAt != nil {
342					used = t.LastUsedAt.UTC().Format(time.RFC3339Nano)
343				}
344				tt.row(cRef(t.Name), cState(t.Scope), cAge(used))
345			}
346			tt.flush()
347		}
348	})
349}
350
351func runAdminUserPromote(c *Ctx, args []string) int { return setAdmin(c, args, true) }
352func runAdminUserDemote(c *Ctx, args []string) int  { return setAdmin(c, args, false) }
353
354func setAdmin(c *Ctx, args []string, admin bool) int {
355	if code := requireInstanceAdmin(c); code >= 0 {
356		return code
357	}
358	verb := "demote"
359	if admin {
360		verb = "promote"
361	}
362	if len(args) != 1 {
363		return c.usage()
364	}
365	u, err := c.Store.UserByUsername(args[0])
366	if errors.Is(err, store.ErrNotFound) {
367		return c.fail(protocol.ExitNotFound, "no user %q", args[0])
368	} else if err != nil {
369		return c.fail(protocol.ExitFailure, "%v", err)
370	}
371	if u.IsAdmin == admin {
372		return c.fail(protocol.ExitUsage, "%s is already %s", u.Username, map[bool]string{true: "an admin", false: "not an admin"}[admin])
373	}
374	if admin && (u.Pending || u.Disabled) {
375		return c.fail(protocol.ExitUsage, "%s is %s; only an active account can be an admin", u.Username,
376			map[bool]string{true: "disabled", false: "pending"}[u.Disabled])
377	}
378	if err := c.Store.SetUserAdmin(u.ID, admin); err != nil {
379		if errors.Is(err, store.ErrLastAdmin) {
380			return c.failErr(err)
381		}
382		return c.fail(protocol.ExitFailure, "%v", err)
383	}
384	c.Store.Audit(c.User.ID, "admin user."+verb+"d", map[string]any{"user": u.Username})
385	return c.emit(map[string]any{"user": u.Username, "admin": admin}, func(w io.Writer) {
386		fmt.Fprintf(w, "%sd %s\n", verb, u.Username)
387	})
388}
389
390// adminRepo loads a repository for an admin override. Instance admin
391// carries no implicit read right, so policy is not consulted; the only
392// refusal is a path that does not exist. Every caller audits what it does.
393func adminRepo(c *Ctx, path string) (store.Repo, int) {
394	if code := requireInstanceAdmin(c); code >= 0 {
395		return store.Repo{}, code
396	}
397	repo, err := c.Store.RepoByPath(path)
398	if errors.Is(err, store.ErrNotFound) {
399		return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
400	} else if err != nil {
401		return repo, c.fail(protocol.ExitFailure, "loading repository: %v", err)
402	}
403	return repo, -1
404}
405
406func runAdminRepoList(c *Ctx, args []string) int {
407	if code := requireInstanceAdmin(c); code >= 0 {
408		return code
409	}
410	args, p, code := parsePageFlags(c, args, "admin-repo", false)
411	if code >= 0 {
412		return code
413	}
414	f, err := c.parseArgs(args, flagSpec{Values: []string{"--owner", "--visibility"}, MaxPos: 0,
415		Usage: "admin repo list [--owner <name>] [--visibility public|private] [--limit <n>] [--cursor <c>]"})
416	if err != nil {
417		return c.fail(protocol.ExitUsage, "%v", err)
418	}
419	owner, visibility := f.Value("--owner"), f.Value("--visibility")
420	if visibility != "" && visibility != "public" && visibility != "private" {
421		return c.fail(protocol.ExitUsage, "--visibility requires public|private")
422	}
423	repos, err := c.Store.ListReposAdmin(owner, visibility, p.queryLimit(), p.key)
424	if err != nil {
425		return c.fail(protocol.ExitFailure, "%v", err)
426	}
427	repos, next := trimPage(p, repos, "admin-repo", func(r store.AdminRepo) string { return r.Path })
428	type out struct {
429		Path       string `json:"path"`
430		Visibility string `json:"visibility"`
431		Archived   bool   `json:"archived,omitempty"`
432		CreatedAt  string `json:"created_at"`
433		LastPush   string `json:"last_push,omitempty"`
434		Bytes      int64  `json:"bytes"`
435	}
436	var ds []out
437	for _, r := range repos {
438		size := gitutil.DirSize(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
439		ds = append(ds, out{r.Path, r.Visibility, r.Archived, r.CreatedAt, r.LastPush, size})
440	}
441	return c.emitPage(p, ds, next, func(w io.Writer) {
442		tb := c.table(w, "PATH", "VISIBILITY", "BYTES", "CREATED", "LAST PUSH")
443		for _, d := range ds {
444			cells := []cell{cRef(d.Path), cState(d.Visibility), cNum(d.Bytes), cAge(d.CreatedAt), cAge(d.LastPush)}
445			if d.Archived {
446				cells = append(cells, cText("[archived]"))
447			}
448			tb.row(cells...)
449		}
450		tb.flush()
451	})
452}
453
454func runAdminRepoArchive(c *Ctx, args []string) int   { return adminArchive(c, args, true) }
455func runAdminRepoUnarchive(c *Ctx, args []string) int { return adminArchive(c, args, false) }
456
457func adminArchive(c *Ctx, args []string, archived bool) int {
458	verb := "archive"
459	if !archived {
460		verb = "unarchive"
461	}
462	if len(args) != 1 {
463		return c.usage()
464	}
465	repo, code := adminRepo(c, args[0])
466	if code >= 0 {
467		return code
468	}
469	if code := archiveRepo(c, repo, archived); code != protocol.ExitOK {
470		return code
471	}
472	c.Store.Audit(c.User.ID, "admin repo."+verb, map[string]any{"repo": repo.Path()})
473	return protocol.ExitOK
474}
475
476func runAdminRepoVisibility(c *Ctx, args []string) int {
477	if len(args) != 2 || (args[1] != "public" && args[1] != "private") {
478		return c.usage()
479	}
480	repo, code := adminRepo(c, args[0])
481	if code >= 0 {
482		return code
483	}
484	if code := setRepoVisibility(c, repo, args[1]); code != protocol.ExitOK {
485		return code
486	}
487	c.Store.Audit(c.User.ID, "admin repo.visibility", map[string]any{"repo": repo.Path(), "visibility": args[1]})
488	return protocol.ExitOK
489}
490
491func runAdminRepoDelete(c *Ctx, args []string) int {
492	var path string
493	var yes bool
494	for _, a := range args {
495		if a == "--yes" {
496			yes = true
497		} else if path == "" {
498			path = a
499		} else {
500			return c.usage()
501		}
502	}
503	if path == "" {
504		return c.usage()
505	}
506	repo, code := adminRepo(c, path)
507	if code >= 0 {
508		return code
509	}
510	if !yes {
511		return c.fail(protocol.ExitUsage, "admin repo delete is permanent; re-run with --yes")
512	}
513	if code := deleteRepo(c, repo); code != protocol.ExitOK {
514		return code
515	}
516	c.Store.Audit(c.User.ID, "admin repo.delete", map[string]any{"repo": repo.Path()})
517	return protocol.ExitOK
518}
519
520func runAdminRunnersForget(c *Ctx, args []string) int {
521	if code := requireInstanceAdmin(c); code >= 0 {
522		return code
523	}
524	if len(args) != 1 {
525		return c.usage()
526	}
527	if err := c.Store.ForgetRunner(args[0]); err != nil {
528		if errors.Is(err, store.ErrNotFound) {
529			return c.fail(protocol.ExitNotFound, "no runner has polled with %s", args[0])
530		}
531		return c.fail(protocol.ExitFailure, "%v", err)
532	}
533	c.Store.Audit(c.User.ID, "admin runners.forget", map[string]any{"fingerprint": args[0]})
534	return c.emit(map[string]string{"forgot": args[0]}, func(w io.Writer) {
535		fmt.Fprintf(w, "forgot runner %s\n", args[0])
536	})
537}
538
539func runAdminRunners(c *Ctx, args []string) int {
540	if code := requireInstanceAdmin(c); code >= 0 {
541		return code
542	}
543	if len(args) != 0 {
544		return c.usage()
545	}
546	runners, err := c.Store.ListRunners()
547	if err != nil {
548		return c.fail(protocol.ExitFailure, "%v", err)
549	}
550	queue, err := c.Store.QueueStats()
551	if err != nil {
552		return c.fail(protocol.ExitFailure, "%v", err)
553	}
554	if runners == nil {
555		runners = []store.Runner{}
556	}
557	// The scope column is what the key may claim, not what it asked for. A
558	// runner key is confined to its attachments, so they replace whatever
559	// -repos it polled with, and none of them means none. Any other key
560	// keeps the repositories it asked for, or the whole instance.
561	for i := range runners {
562		key, err := c.Store.SSHKeyByID(runners[i].KeyID)
563		if err != nil || key.Scope != "runner" {
564			continue
565		}
566		paths, err := c.Store.RunnerRepoPaths(runners[i].KeyID)
567		if err != nil {
568			return c.fail(protocol.ExitFailure, "%v", err)
569		}
570		runners[i].Scope = "none"
571		if len(paths) > 0 {
572			runners[i].Scope = strings.Join(paths, ",")
573		}
574	}
575	d := map[string]any{"queue": queue, "runners": runners}
576	return c.emit(d, func(w io.Writer) {
577		v := c.view(w)
578		v.fields(
579			"pending", fmt.Sprintf("%d", queue.Pending),
580			"claimed 24h", fmt.Sprintf("%d", queue.Claimed24h),
581			"wait avg", fmt.Sprintf("%ds", queue.ClaimWaitAvgS),
582			"wait max", fmt.Sprintf("%ds", queue.ClaimWaitMaxS),
583			"reaped 24h", fmt.Sprintf("%d", queue.Reaped24h),
584		)
585		if len(runners) > 0 {
586			v.section("runners")
587		}
588		tb := c.table(w, "USER", "FINGERPRINT", "LAST SEEN", "SCOPE", "HELD")
589		for _, r := range runners {
590			scope := r.Scope
591			if scope == "" {
592				scope = "any"
593			}
594			held := "idle"
595			if r.BuildNumber != 0 {
596				held = fmt.Sprintf("%s #%d %s since %s", r.BuildRepo, r.BuildNumber, r.BuildJob, r.StartedAt)
597			}
598			tb.row(cText(r.Username), cFlex(r.Fingerprint), cAge(r.LastSeen), cText(scope), cText(held))
599		}
600		tb.flush()
601	})
602}
603
604type mrPruneOut struct {
605	Number int64  `json:"number"`
606	Head   string `json:"head_sha"` // what the ref pointed at; empty if it was already gone
607}
608
609// runAdminMRPrune deletes refs/merge-requests/<n>/head for the named MRs
610// and prunes the repository at once, so commits a history rewrite left
611// reachable only through them stop being fetchable. Nothing drops a head
612// ref on its own: an open or source-gone MR is merged through it, and a
613// merged or closed one keeps its diff readable through it. Every check
614// runs before the first write.
615func runAdminMRPrune(c *Ctx, args []string) int {
616	var path string
617	var yes bool
618	var numbers []int64
619	for _, a := range args {
620		switch {
621		case a == "--yes":
622			yes = true
623		case path == "":
624			path = a
625		default:
626			n, err := strconv.ParseInt(a, 10, 64)
627			if err != nil || n <= 0 {
628				return c.usage()
629			}
630			if !slices.Contains(numbers, n) {
631				numbers = append(numbers, n)
632			}
633		}
634	}
635	if path == "" || len(numbers) == 0 {
636		return c.usage()
637	}
638	repo, code := adminRepo(c, path)
639	if code >= 0 {
640		return code
641	}
642	if !yes {
643		return c.fail(protocol.ExitUsage, "admin mr prune drops the commits for good; re-run with --yes")
644	}
645	mrs := make([]store.MR, 0, len(numbers))
646	for _, n := range numbers {
647		mr, err := c.Store.MRByNumber(repo.ID, n)
648		if errors.Is(err, store.ErrNotFound) {
649			return c.fail(protocol.ExitNotFound, "MR !%d not found in %s", n, repo.Path())
650		} else if err != nil {
651			return c.fail(protocol.ExitFailure, "%v", err)
652		}
653		if mr.State != "merged" && mr.State != "closed" {
654			return c.fail(protocol.ExitFailure, "!%d is still mergeable and its head is what makes it so; merge or close it first", n)
655		}
656		mrs = append(mrs, mr)
657	}
658
659	// The prune would remove objects a running full backup has listed
660	// and not yet read.
661	release, code := holdOffBackup(c)
662	if code >= 0 {
663		return code
664	}
665	defer release()
666
667	// The record is written as each ref goes, not after the gc: a failure
668	// past this point leaves refs deleted, and the audit log and the MR
669	// thread must say so. Re-running the same command finishes the job.
670	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
671	rows := make([]mrPruneOut, 0, len(mrs))
672	for _, mr := range mrs {
673		ref := mrHeadRef(mr.Number)
674		row := mrPruneOut{Number: mr.Number}
675		if gitutil.RefExists(dir, ref) {
676			row.Head, _ = gitutil.ResolveRef(dir, ref)
677			if err := gitutil.DeleteRef(dir, ref); err != nil {
678				c.Store.Audit(c.User.ID, "admin mr.prune", map[string]any{"repo": repo.Path(), "numbers": numbers, "failed": err.Error()})
679				return c.fail(protocol.ExitFailure, "%v; the refs before !%d are deleted and not yet pruned; re-run the same command", err, mr.Number)
680			}
681		}
682		c.Store.AddMRSystemComment(mr.ID, c.User.ID, fmt.Sprintf("head ref pruned by %s; the diff is no longer available", c.User.Username))
683		rows = append(rows, row)
684	}
685	c.Store.Audit(c.User.ID, "admin mr.prune", map[string]any{"repo": repo.Path(), "numbers": numbers})
686	if err := gitutil.PruneNow(dir); err != nil {
687		return c.fail(protocol.ExitFailure, "%v; the head refs are deleted but the objects are not yet pruned; re-run the same command", err)
688	}
689	return c.emit(rows, func(w io.Writer) {
690		tb := c.table(w, "!", "HEAD")
691		for _, r := range rows {
692			if r.Head == "" {
693				tb.row(cRef(fmt.Sprintf("!%d", r.Number)), cText("already gone"))
694				continue
695			}
696			tb.row(cRef(fmt.Sprintf("!%d", r.Number)), cRef(r.Head))
697		}
698		tb.flush()
699	})
700}