internal/control/admin.go

838 lines · 28268 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		NeedsRecentSignIn: true,
 84		Summary:           "set any repository's visibility (instance admins; audited)",
 85		Usage:             "admin repo visibility <owner/name> public|private",
 86		Examples:          []string{"admin repo visibility alice/secret private"},
 87		Run:               runAdminRepoVisibility})
 88	register(Command{Path: []string{"admin", "repo", "delete"},
 89		Summary: "delete any repository (instance admins; audited)",
 90		Usage:   "admin repo delete <owner/name> --yes",
 91		Flags: []Flag{
 92			{"--yes", "", "confirm the permanent delete", ""},
 93		},
 94		Examples: []string{"admin repo delete alice/spam --yes"},
 95		Run:      runAdminRepoDelete})
 96	register(Command{Path: []string{"admin", "mr", "prune"},
 97		Summary: "drop merged or closed MRs' head refs and the objects only they kept, e.g. after a history rewrite (instance admins; audited)",
 98		Usage:   "admin mr prune <owner/name> <n> [<n>...] --yes",
 99		Flags: []Flag{
100			{"--yes", "", "confirm the permanent prune", ""},
101		},
102		Examples: []string{"admin mr prune krz/gitbay 12 13 --yes"},
103		Run:      runAdminMRPrune})
104}
105
106// requireInstanceAdmin gates the admin noun. -1 means proceed.
107func requireInstanceAdmin(c *Ctx) int {
108	if !c.User.IsAdmin {
109		return c.fail(protocol.ExitDenied, "admin commands are for instance admins; ask one")
110	}
111	return -1
112}
113
114// adminUserOut is one account row, shared by list and show.
115type adminUserOut struct {
116	Username  string `json:"username"`
117	State     string `json:"state"` // active | pending | disabled
118	Admin     bool   `json:"admin"`
119	CreatedAt string `json:"created_at"`
120	LastSeen  string `json:"last_seen,omitempty"`
121}
122
123func adminUserRow(u store.AdminUser) adminUserOut {
124	state := "active"
125	switch {
126	case u.Disabled:
127		state = "disabled"
128	case u.Pending:
129		state = "pending"
130	}
131	return adminUserOut{u.Username, state, u.IsAdmin, u.CreatedAt, u.LastSeen}
132}
133
134func runAdminUserList(c *Ctx, args []string) int {
135	if code := requireInstanceAdmin(c); code >= 0 {
136		return code
137	}
138	args, p, code := parsePageFlags(c, args, "admin-user", false)
139	if code >= 0 {
140		return code
141	}
142	f, err := c.parseArgs(args, flagSpec{Values: []string{"--state"}, MaxPos: 0,
143		Usage: "admin user list [--state active|pending|disabled|admin] [--limit <n>] [--cursor <c>]"})
144	if err != nil {
145		return c.fail(protocol.ExitUsage, "%v", err)
146	}
147	state := f.Value("--state")
148	switch state {
149	case "", "active", "pending", "disabled", "admin":
150	default:
151		return c.fail(protocol.ExitUsage, "--state requires active|pending|disabled|admin")
152	}
153	users, err := c.Store.ListUsers(state, p.queryLimit(), p.key)
154	if err != nil {
155		return c.fail(protocol.ExitFailure, "%v", err)
156	}
157	users, next := trimPage(p, users, "admin-user", func(u store.AdminUser) string { return u.Username })
158	var ds []adminUserOut
159	for _, u := range users {
160		ds = append(ds, adminUserRow(u))
161	}
162	return c.emitPageView(p, ds, next, func(w io.Writer) {
163		tb := c.table(w, "USERNAME", "STATE", "ADMIN", "CREATED", "LAST SEEN")
164		for _, d := range ds {
165			mark := ""
166			if d.Admin {
167				mark = "admin"
168			}
169			tb.row(cRef(d.Username), cState(d.State), cText(mark), cAge(d.CreatedAt), cAge(d.LastSeen))
170		}
171		tb.flush()
172	}, func() screen {
173		rows := make([]row, len(ds))
174		for i, d := range ds {
175			lead := cGlyph("")
176			if d.State == "pending" {
177				lead = cYou()
178			}
179			admin, seen := "", ""
180			if d.Admin {
181				admin = "admin"
182			}
183			if d.LastSeen != "" {
184				seen = "seen " + relAge(d.LastSeen, termNow())
185			}
186			rows[i] = rowOf(cRef(d.Username), lead, cState(d.State), cMeta(admin, seen))
187		}
188		return listScreen("Accounts", rows,
189			action{"Filter", []string{"admin", "user", "list", "--state", "pending"}},
190		)
191	})
192}
193
194func runAdminUserShow(c *Ctx, args []string) int {
195	if code := requireInstanceAdmin(c); code >= 0 {
196		return code
197	}
198	if len(args) != 1 {
199		return c.usage()
200	}
201	name := args[0]
202	u, err := c.Store.UserByUsername(name)
203	if errors.Is(err, store.ErrNotFound) {
204		return c.fail(protocol.ExitNotFound, "no user %q", name)
205	} else if err != nil {
206		return c.fail(protocol.ExitFailure, "%v", err)
207	}
208	row, err := c.Store.AdminUserByName(name)
209	if err != nil {
210		return c.fail(protocol.ExitFailure, "%v", err)
211	}
212
213	type keyOut struct {
214		Fingerprint string `json:"fingerprint"`
215		Algo        string `json:"algo"`
216		Scope       string `json:"scope"`
217		Label       string `json:"label"`
218		CreatedAt   string `json:"created_at"`
219		LastUsedAt  string `json:"last_used_at,omitempty"`
220	}
221	type emailOut struct {
222		Address    string `json:"address"`
223		Verified   bool   `json:"verified"`
224		VerifiedBy string `json:"verified_by,omitempty"` // smtp | admin
225		Primary    bool   `json:"primary"`
226	}
227	type pgpOut struct {
228		Fingerprint string     `json:"fingerprint"`
229		ExpiresAt   *time.Time `json:"expires_at,omitempty"`
230		RevokedAt   *time.Time `json:"revoked_at,omitempty"`
231	}
232	type orgOut struct {
233		Org  string `json:"org"`
234		Role string `json:"role"`
235	}
236	type tokenOut struct {
237		Name       string     `json:"name"`
238		Scope      string     `json:"scope"`
239		CreatedAt  string     `json:"created_at"`
240		ExpiresAt  *time.Time `json:"expires_at,omitempty"`
241		LastUsedAt *time.Time `json:"last_used_at,omitempty"`
242	}
243	type out struct {
244		adminUserOut
245		Keys        []keyOut   `json:"keys"`
246		Emails      []emailOut `json:"emails"`
247		PGPKeys     []pgpOut   `json:"pgp_keys"`
248		Orgs        []orgOut   `json:"orgs"`
249		Repos       int64      `json:"repos"`
250		RepoLimit   int64      `json:"repo_limit"` // 0 unlimited
251		ByteLimit   int64      `json:"byte_limit"` // 0 unlimited
252		APITokens   []tokenOut `json:"api_tokens"`
253		WebSessions int64      `json:"web_sessions"`
254	}
255	d := out{adminUserOut: adminUserRow(row),
256		Keys: []keyOut{}, Emails: []emailOut{}, PGPKeys: []pgpOut{}, Orgs: []orgOut{}, APITokens: []tokenOut{}}
257
258	keys, err := c.Store.ListSSHKeys(u.ID)
259	if err != nil {
260		return c.fail(protocol.ExitFailure, "%v", err)
261	}
262	for _, k := range keys {
263		d.Keys = append(d.Keys, keyOut{k.Fingerprint, k.Algo, k.Scope, k.Label, k.CreatedAt, k.LastUsedAt})
264	}
265	emails, err := c.Store.ListEmails(u.ID)
266	if err != nil {
267		return c.fail(protocol.ExitFailure, "%v", err)
268	}
269	for _, e := range emails {
270		d.Emails = append(d.Emails, emailOut{e.Address, e.Verified, e.VerifiedBy, e.Primary})
271	}
272	pgp, err := c.Store.ListPGPKeys(u.ID)
273	if err != nil {
274		return c.fail(protocol.ExitFailure, "%v", err)
275	}
276	for _, k := range pgp {
277		d.PGPKeys = append(d.PGPKeys, pgpOut{k.Fingerprint, k.ExpiresAt, k.RevokedAt})
278	}
279	orgs, err := c.Store.ListOrgsForUser(u.ID)
280	if err != nil {
281		return c.fail(protocol.ExitFailure, "%v", err)
282	}
283	for _, m := range orgs {
284		d.Orgs = append(d.Orgs, orgOut{m.Username, m.Role})
285	}
286	if d.Repos, err = c.Store.OwnedRepoCount(u.ID); err != nil {
287		return c.fail(protocol.ExitFailure, "%v", err)
288	}
289	d.RepoLimit = RepoLimit(c.Store, limitsOf(c), u.ID)
290	d.ByteLimit = ByteLimit(c.Store, limitsOf(c), u.ID)
291	tokens, err := c.Store.ListAPITokens(u.ID)
292	if err != nil {
293		return c.fail(protocol.ExitFailure, "%v", err)
294	}
295	for _, t := range tokens {
296		d.APITokens = append(d.APITokens, tokenOut{t.Name, t.Scope, t.CreatedAt, t.ExpiresAt, t.LastUsedAt})
297	}
298	if d.WebSessions, err = c.Store.WebSessionCount(u.ID); err != nil {
299		return c.fail(protocol.ExitFailure, "%v", err)
300	}
301
302	return c.emitView(d, func(w io.Writer) {
303		admin := ""
304		if d.Admin {
305			admin = "yes"
306		}
307		v := c.view(w)
308		v.title(d.Username, "", d.State)
309		v.fields(
310			"admin", admin,
311			"created", c.when(d.CreatedAt),
312			"last seen", c.when(d.LastSeen),
313			"repos", fmt.Sprintf("%d", d.Repos),
314			"web sessions", fmt.Sprintf("%d", d.WebSessions),
315		)
316		if len(d.Keys) > 0 {
317			v.section("keys")
318			tk := c.table(w, "FINGERPRINT", "ALGO", "SCOPE", "LAST USED")
319			for _, k := range d.Keys {
320				tk.row(cFlex(k.Fingerprint), cText(k.Algo), cState(k.Scope), cAge(k.LastUsedAt))
321			}
322			tk.flush()
323		}
324		if len(d.Emails) > 0 {
325			v.section("emails")
326			te := c.table(w, "ADDRESS", "STATE")
327			for _, e := range d.Emails {
328				state := "unverified"
329				if e.Verified {
330					state = "verified by " + e.VerifiedBy
331				}
332				cells := []cell{cRef(e.Address), cState(state)}
333				if e.Primary {
334					cells = c.note(cells, 1, "primary", "primary")
335				}
336				te.row(cells...)
337			}
338			te.flush()
339		}
340		if len(d.PGPKeys) > 0 {
341			v.section("pgp keys")
342			tp := c.table(w, "FINGERPRINT")
343			for _, k := range d.PGPKeys {
344				tp.row(cFlex(k.Fingerprint))
345			}
346			tp.flush()
347		}
348		if len(d.Orgs) > 0 {
349			v.section("orgs")
350			to := c.table(w, "ORG", "ROLE")
351			for _, o := range d.Orgs {
352				to.row(cRef(o.Org), cState(o.Role))
353			}
354			to.flush()
355		}
356		if len(d.APITokens) > 0 {
357			v.section("api tokens")
358			tt := c.table(w, "NAME", "SCOPE", "LAST USED")
359			for _, t := range d.APITokens {
360				used := ""
361				if t.LastUsedAt != nil {
362					used = t.LastUsedAt.UTC().Format(time.RFC3339Nano)
363				}
364				tt.row(cRef(t.Name), cState(t.Scope), cAge(used))
365			}
366			tt.flush()
367		}
368	}, func() screen {
369		s := screen{}
370		user := []cell{cRef(d.Username), cState(d.State)}
371		if d.Admin {
372			user = append(user, cMeta("admin"))
373		}
374		seen := "never seen"
375		if d.LastSeen != "" {
376			seen = "seen " + relAge(d.LastSeen, termNow())
377		}
378		s.fields = []field{
379			{"User", user},
380			{"Seen", []cell{cText(seen), cMeta("created " + relAge(d.CreatedAt, termNow()))}},
381			{"Repos", []cell{cText(strconv.FormatInt(d.Repos, 10))}},
382			{"Sessions", []cell{cText(strconv.FormatInt(d.WebSessions, 10))}},
383		}
384		keys := section{title: "Keys", n: len(d.Keys)}
385		for _, k := range d.Keys {
386			keys.rows = append(keys.rows, rowOf(cFlexRef(k.Fingerprint), cState(k.Scope), cMeta(k.Algo, "used "+relAge(k.LastUsedAt, termNow()))))
387		}
388		emails := section{title: "Emails", n: len(d.Emails)}
389		for _, e := range d.Emails {
390			state, primary := "unverified", ""
391			if e.Verified {
392				state = "verified"
393			}
394			if e.Primary {
395				primary = "primary"
396			}
397			emails.rows = append(emails.rows, rowOf(cRef(e.Address), cState(state), cMeta(primary, e.VerifiedBy)))
398		}
399		pgp := section{title: "PGP keys", n: len(d.PGPKeys)}
400		for _, k := range d.PGPKeys {
401			pgp.rows = append(pgp.rows, rowOf(cFlexRef(k.Fingerprint)))
402		}
403		orgs := section{title: "Orgs", n: len(d.Orgs)}
404		for _, o := range d.Orgs {
405			orgs.rows = append(orgs.rows, rowOf(cLink(o.Org, c.siteURL(o.Org)), cState(o.Role)))
406		}
407		tokens := section{title: "API tokens", n: len(d.APITokens)}
408		for _, tk := range d.APITokens {
409			used := ""
410			if tk.LastUsedAt != nil {
411				used = "used " + relAge(tk.LastUsedAt.UTC().Format(time.RFC3339Nano), termNow())
412			}
413			tokens.rows = append(tokens.rows, rowOf(cRef(tk.Name), cState(tk.Scope), cMeta(used)))
414		}
415		s.sections = []section{keys, emails, pgp, orgs, tokens}
416		role, state := "promote", "disable"
417		if d.Admin {
418			role = "demote"
419		}
420		if d.State == "disabled" {
421			state = "enable"
422		}
423		s.actions = []action{
424			{"Manage", []string{"admin", "user", role, d.Username}},
425			{"Manage", []string{"admin", "user", state, d.Username}},
426		}
427		return s
428	})
429}
430
431func runAdminUserPromote(c *Ctx, args []string) int { return setAdmin(c, args, true) }
432func runAdminUserDemote(c *Ctx, args []string) int  { return setAdmin(c, args, false) }
433
434func setAdmin(c *Ctx, args []string, admin bool) int {
435	if code := requireInstanceAdmin(c); code >= 0 {
436		return code
437	}
438	verb := "demote"
439	if admin {
440		verb = "promote"
441	}
442	if len(args) != 1 {
443		return c.usage()
444	}
445	u, err := c.Store.UserByUsername(args[0])
446	if errors.Is(err, store.ErrNotFound) {
447		return c.fail(protocol.ExitNotFound, "no user %q", args[0])
448	} else if err != nil {
449		return c.fail(protocol.ExitFailure, "%v", err)
450	}
451	if u.IsAdmin == admin {
452		return c.fail(protocol.ExitUsage, "%s is already %s", u.Username, map[bool]string{true: "an admin", false: "not an admin"}[admin])
453	}
454	if admin && (u.Pending || u.Disabled) {
455		return c.fail(protocol.ExitUsage, "%s is %s; only an active account can be an admin", u.Username,
456			map[bool]string{true: "disabled", false: "pending"}[u.Disabled])
457	}
458	if err := c.Store.SetUserAdmin(u.ID, admin); err != nil {
459		if errors.Is(err, store.ErrLastAdmin) {
460			return c.failErr(err)
461		}
462		return c.fail(protocol.ExitFailure, "%v", err)
463	}
464	c.Store.Audit(c.User.ID, "admin user."+verb+"d", map[string]any{"user": u.Username})
465	return c.emit(map[string]any{"user": u.Username, "admin": admin}, func(w io.Writer) {
466		fmt.Fprintf(w, "%sd %s\n", verb, u.Username)
467	})
468}
469
470// adminRepo loads a repository for an admin override. Instance admin
471// carries no implicit read right, so policy is not consulted; the only
472// refusal is a path that does not exist. Every caller audits what it does.
473func adminRepo(c *Ctx, path string) (store.Repo, int) {
474	if code := requireInstanceAdmin(c); code >= 0 {
475		return store.Repo{}, code
476	}
477	repo, err := c.Store.RepoByPath(path)
478	if errors.Is(err, store.ErrNotFound) {
479		return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
480	} else if err != nil {
481		return repo, c.fail(protocol.ExitFailure, "loading repository: %v", err)
482	}
483	return repo, -1
484}
485
486func runAdminRepoList(c *Ctx, args []string) int {
487	if code := requireInstanceAdmin(c); code >= 0 {
488		return code
489	}
490	args, p, code := parsePageFlags(c, args, "admin-repo", false)
491	if code >= 0 {
492		return code
493	}
494	f, err := c.parseArgs(args, flagSpec{Values: []string{"--owner", "--visibility"}, MaxPos: 0,
495		Usage: "admin repo list [--owner <name>] [--visibility public|private] [--limit <n>] [--cursor <c>]"})
496	if err != nil {
497		return c.fail(protocol.ExitUsage, "%v", err)
498	}
499	owner, visibility := f.Value("--owner"), f.Value("--visibility")
500	if visibility != "" && visibility != "public" && visibility != "private" {
501		return c.fail(protocol.ExitUsage, "--visibility requires public|private")
502	}
503	repos, err := c.Store.ListReposAdmin(owner, visibility, p.queryLimit(), p.key)
504	if err != nil {
505		return c.fail(protocol.ExitFailure, "%v", err)
506	}
507	repos, next := trimPage(p, repos, "admin-repo", func(r store.AdminRepo) string { return r.Path })
508	type out struct {
509		Path       string `json:"path"`
510		Visibility string `json:"visibility"`
511		Archived   bool   `json:"archived,omitempty"`
512		CreatedAt  string `json:"created_at"`
513		LastPush   string `json:"last_push,omitempty"`
514		Bytes      int64  `json:"bytes"`
515	}
516	var ds []out
517	for _, r := range repos {
518		size := gitutil.DirSize(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
519		ds = append(ds, out{r.Path, r.Visibility, r.Archived, r.CreatedAt, r.LastPush, size})
520	}
521	return c.emitPageView(p, ds, next, func(w io.Writer) {
522		tb := c.table(w, "PATH", "VISIBILITY", "BYTES", "CREATED", "LAST PUSH")
523		for _, d := range ds {
524			cells := []cell{cLink(d.Path, c.siteURL(d.Path)), cState(d.Visibility), cSize(d.Bytes), cAge(d.CreatedAt), cAge(d.LastPush)}
525			if d.Archived {
526				cells = c.note(cells, 1, "[archived]", "archived")
527			}
528			tb.row(cells...)
529		}
530		tb.flush()
531	}, func() screen {
532		rows := make([]row, len(ds))
533		for i, d := range ds {
534			state := d.Visibility
535			if d.Archived {
536				state += ", archived"
537			}
538			pushed := ""
539			if d.LastPush != "" {
540				pushed = "pushed " + relAge(d.LastPush, termNow())
541			}
542			rows[i] = rowOf(cLink(d.Path, c.siteURL(d.Path)), cState(state), cSize(d.Bytes), cMeta(pushed))
543		}
544		return listScreen("Repositories", rows,
545			action{"Filter", []string{"admin", "repo", "list", "--visibility", "private"}},
546		)
547	})
548}
549
550func runAdminRepoArchive(c *Ctx, args []string) int   { return adminArchive(c, args, true) }
551func runAdminRepoUnarchive(c *Ctx, args []string) int { return adminArchive(c, args, false) }
552
553func adminArchive(c *Ctx, args []string, archived bool) int {
554	verb := "archive"
555	if !archived {
556		verb = "unarchive"
557	}
558	if len(args) != 1 {
559		return c.usage()
560	}
561	repo, code := adminRepo(c, args[0])
562	if code >= 0 {
563		return code
564	}
565	if code := archiveRepo(c, repo, archived); code != protocol.ExitOK {
566		return code
567	}
568	c.Store.Audit(c.User.ID, "admin repo."+verb, map[string]any{"repo": repo.Path()})
569	return protocol.ExitOK
570}
571
572func runAdminRepoVisibility(c *Ctx, args []string) int {
573	if len(args) != 2 || (args[1] != "public" && args[1] != "private") {
574		return c.usage()
575	}
576	repo, code := adminRepo(c, args[0])
577	if code >= 0 {
578		return code
579	}
580	if code := setRepoVisibility(c, repo, args[1]); code != protocol.ExitOK {
581		return code
582	}
583	c.Store.Audit(c.User.ID, "admin repo.visibility", map[string]any{"repo": repo.Path(), "visibility": args[1]})
584	return protocol.ExitOK
585}
586
587func runAdminRepoDelete(c *Ctx, args []string) int {
588	var path string
589	var yes bool
590	for _, a := range args {
591		if a == "--yes" {
592			yes = true
593		} else if path == "" {
594			path = a
595		} else {
596			return c.usage()
597		}
598	}
599	if path == "" {
600		return c.usage()
601	}
602	repo, code := adminRepo(c, path)
603	if code >= 0 {
604		return code
605	}
606	if !yes {
607		return c.fail(protocol.ExitUsage, "admin repo delete is permanent; re-run with --yes")
608	}
609	if code := deleteRepo(c, repo); code != protocol.ExitOK {
610		return code
611	}
612	c.Store.Audit(c.User.ID, "admin repo.delete", map[string]any{"repo": repo.Path()})
613	return protocol.ExitOK
614}
615
616func runAdminRunnersForget(c *Ctx, args []string) int {
617	if code := requireInstanceAdmin(c); code >= 0 {
618		return code
619	}
620	if len(args) != 1 {
621		return c.usage()
622	}
623	if err := c.Store.ForgetRunner(args[0]); err != nil {
624		if errors.Is(err, store.ErrNotFound) {
625			return c.fail(protocol.ExitNotFound, "no runner has polled with %s", args[0])
626		}
627		return c.fail(protocol.ExitFailure, "%v", err)
628	}
629	c.Store.Audit(c.User.ID, "admin runners.forget", map[string]any{"fingerprint": args[0]})
630	return c.emit(map[string]string{"forgot": args[0]}, func(w io.Writer) {
631		fmt.Fprintf(w, "forgot runner %s\n", args[0])
632	})
633}
634
635func runAdminRunners(c *Ctx, args []string) int {
636	if code := requireInstanceAdmin(c); code >= 0 {
637		return code
638	}
639	if len(args) != 0 {
640		return c.usage()
641	}
642	runners, err := c.Store.ListRunners()
643	if err != nil {
644		return c.fail(protocol.ExitFailure, "%v", err)
645	}
646	queue, err := c.Store.QueueStats()
647	if err != nil {
648		return c.fail(protocol.ExitFailure, "%v", err)
649	}
650	if runners == nil {
651		runners = []store.Runner{}
652	}
653	// The scope column is what the key may claim, not what it asked for. A
654	// runner key is confined to its attachments, so they replace whatever
655	// -repos it polled with, and none of them means none. Any other key
656	// keeps the repositories it asked for, or the whole instance.
657	for i := range runners {
658		key, err := c.Store.SSHKeyByID(runners[i].KeyID)
659		if err != nil || key.Scope != "runner" {
660			continue
661		}
662		paths, err := c.Store.RunnerRepoPaths(runners[i].KeyID)
663		if err != nil {
664			return c.fail(protocol.ExitFailure, "%v", err)
665		}
666		runners[i].Scope = "none"
667		if len(paths) > 0 {
668			runners[i].Scope = strings.Join(paths, ",")
669		}
670	}
671	d := map[string]any{"queue": queue, "runners": runners}
672	return c.emitView(d, func(w io.Writer) {
673		v := c.view(w)
674		v.fields(
675			"pending", fmt.Sprintf("%d", queue.Pending),
676			"claimed 24h", fmt.Sprintf("%d", queue.Claimed24h),
677			"wait avg", c.Term.dur(queue.ClaimWaitAvgS),
678			"wait max", c.Term.dur(queue.ClaimWaitMaxS),
679			"reaped 24h", fmt.Sprintf("%d", queue.Reaped24h),
680		)
681		if len(runners) > 0 {
682			v.section("runners")
683		}
684		tb := c.table(w, "USER", "FINGERPRINT", "LAST SEEN", "SCOPE", "HELD")
685		for _, r := range runners {
686			scope := r.Scope
687			if scope == "" {
688				scope = "any"
689			}
690			held := "idle"
691			if r.BuildNumber != 0 {
692				held = fmt.Sprintf("%s #%d %s since %s", r.BuildRepo, r.BuildNumber, r.BuildJob, r.StartedAt)
693			}
694			tb.row(cText(r.Username), cText(r.Fingerprint), cAge(r.LastSeen), cFlex(scope), cText(held))
695		}
696		tb.flush()
697	}, func() screen {
698		s := screen{fields: []field{{"Queue", []cell{
699			cText(fmt.Sprintf("%d pending", queue.Pending)),
700			cMeta(fmt.Sprintf("%d claimed in 24h", queue.Claimed24h), "wait avg "+c.Term.dur(queue.ClaimWaitAvgS),
701				"max "+c.Term.dur(queue.ClaimWaitMaxS), fmt.Sprintf("%d reaped", queue.Reaped24h)),
702		}}}}
703		runnersSec := section{title: "Runners", n: len(runners)}
704		idle := ""
705		for _, r := range runners {
706			scope := r.Scope
707			if scope == "" {
708				scope = "any"
709			}
710			lead, held := cGlyph(""), "idle"
711			if r.BuildNumber != 0 {
712				lead, held = cGlyph("running"), fmt.Sprintf("building %s #%d %s", r.BuildRepo, r.BuildNumber, r.BuildJob)
713			} else if idle == "" {
714				idle = r.Fingerprint
715			}
716			runnersSec.rows = append(runnersSec.rows, rowOf(cRef(r.Username), lead, cFlex(scope), cMeta("seen "+relAge(r.LastSeen, termNow()), held)))
717		}
718		s.sections = []section{runnersSec}
719		if idle != "" {
720			s.actions = []action{{"Prune", []string{"admin", "runners", "remove", idle}}}
721		}
722		return s
723	})
724}
725
726type mrPruneOut struct {
727	Number int64  `json:"number"`
728	Head   string `json:"head_sha"` // what the ref pointed at; empty if it was already gone
729}
730
731// runAdminMRPrune deletes refs/merge-requests/<n>/head for the named MRs
732// and prunes the repository at once, so commits a history rewrite left
733// reachable only through them stop being fetchable. Nothing drops a head
734// ref on its own: an open or source-gone MR is merged through it, and a
735// merged or closed one keeps its diff readable through it. Every check
736// runs before the first write.
737func runAdminMRPrune(c *Ctx, args []string) int {
738	var path string
739	var yes bool
740	var numbers []int64
741	for _, a := range args {
742		switch {
743		case a == "--yes":
744			yes = true
745		case path == "":
746			path = a
747		default:
748			n, err := strconv.ParseInt(a, 10, 64)
749			if err != nil || n <= 0 {
750				return c.usage()
751			}
752			if !slices.Contains(numbers, n) {
753				numbers = append(numbers, n)
754			}
755		}
756	}
757	if path == "" || len(numbers) == 0 {
758		return c.usage()
759	}
760	repo, code := adminRepo(c, path)
761	if code >= 0 {
762		return code
763	}
764	if !yes {
765		return c.fail(protocol.ExitUsage, "admin mr prune drops the commits for good; re-run with --yes")
766	}
767	mrs := make([]store.MR, 0, len(numbers))
768	for _, n := range numbers {
769		mr, err := c.Store.MRByNumber(repo.ID, n)
770		if errors.Is(err, store.ErrNotFound) {
771			return c.fail(protocol.ExitNotFound, "MR !%d not found in %s", n, repo.Path())
772		} else if err != nil {
773			return c.fail(protocol.ExitFailure, "%v", err)
774		}
775		if mr.State != "merged" && mr.State != "closed" {
776			return c.fail(protocol.ExitFailure, "!%d is still mergeable and its head is what makes it so; merge or close it first", n)
777		}
778		mrs = append(mrs, mr)
779	}
780
781	// The prune would remove objects a running full backup has listed
782	// and not yet read.
783	release, code := holdOffBackup(c)
784	if code >= 0 {
785		return code
786	}
787	defer release()
788
789	// The record is written as each ref goes, not after the gc: a failure
790	// past this point leaves refs deleted, and the audit log and the MR
791	// thread must say so. Re-running the same command finishes the job.
792	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
793	rows := make([]mrPruneOut, 0, len(mrs))
794	for _, mr := range mrs {
795		ref := mrHeadRef(mr.Number)
796		row := mrPruneOut{Number: mr.Number}
797		if gitutil.RefExists(dir, ref) {
798			row.Head, _ = gitutil.ResolveRef(dir, ref)
799			if err := gitutil.DeleteRef(dir, ref); err != nil {
800				c.Store.Audit(c.User.ID, "admin mr.prune", map[string]any{"repo": repo.Path(), "numbers": numbers, "failed": err.Error()})
801				return c.fail(protocol.ExitFailure, "%v; the refs before !%d are deleted and not yet pruned; re-run the same command", err, mr.Number)
802			}
803		}
804		c.Store.AddMRSystemComment(mr.ID, c.User.ID, fmt.Sprintf("head ref pruned by %s; the diff is no longer available", c.User.Username))
805		rows = append(rows, row)
806	}
807	c.Store.Audit(c.User.ID, "admin mr.prune", map[string]any{"repo": repo.Path(), "numbers": numbers})
808	if err := gitutil.PruneNow(dir); err != nil {
809		return c.fail(protocol.ExitFailure, "%v; the head refs are deleted but the objects are not yet pruned; re-run the same command", err)
810	}
811	return c.emitView(rows, func(w io.Writer) {
812		tb := c.table(w, "!", "HEAD")
813		for _, r := range rows {
814			if r.Head == "" {
815				tb.row(cRef(fmt.Sprintf("!%d", r.Number)), cText("already gone"))
816				continue
817			}
818			tb.row(cRef(fmt.Sprintf("!%d", r.Number)), cRef(r.Head))
819		}
820		tb.flush()
821	}, func() screen {
822		rs := make([]row, len(rows))
823		for i, r := range rows {
824			n := strconv.FormatInt(r.Number, 10)
825			ref := cLink("!"+n, c.siteURL(repo.Path(), "mrs", n))
826			if r.Head == "" {
827				rs[i] = rowOf(ref, cGlyph("skipped"), cMeta("already gone"))
828				continue
829			}
830			rs[i] = rowOf(ref, cGlyph("ok"), cRef(fmt.Sprintf("%.10s", r.Head)))
831		}
832		s := listScreen("Pruned", rs)
833		if len(rows) > 0 {
834			s.actions = []action{{"Read", []string{"mr", "show", repo.Path(), strconv.FormatInt(rows[0].Number, 10)}}}
835		}
836		return s
837	})
838}