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