internal/control/adminhost.go

d775997ead04022093817ab513287b5886065247
gitbay/internal/control/adminhost.go history · blame · raw

327 lines · 11547 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"os"
  8
  9	"golang.org/x/crypto/ssh"
 10
 11	"gitbay.org/gitbay/internal/gitutil"
 12	"gitbay.org/gitbay/internal/lfs"
 13	"gitbay.org/gitbay/internal/mail"
 14	"gitbay.org/gitbay/internal/policy"
 15	"gitbay.org/gitbay/internal/protocol"
 16	"gitbay.org/gitbay/internal/store"
 17)
 18
 19// The account, email, invite and stats commands gitbayd admin used to
 20// implement on its own. They live here so the host binary and an admin
 21// session run the same code; gitbayd admin dispatches into these.
 22
 23func init() {
 24	register(Command{Path: []string{"admin", "user", "create"},
 25		Summary:    "create an account, optionally with a key and a verified address (instance admins)",
 26		Usage:      "admin user create <username> [--admin] [--email <address> [--verified]] [--key -] < key.pub",
 27		ReadsStdin: true, SSHOnly: true, Run: runAdminUserCreate})
 28	register(Command{Path: []string{"admin", "user", "disable"},
 29		Summary: "suspend an account: SSH, web sessions and API tokens refused until re-enabled",
 30		Usage:   "admin user disable <username>",
 31		SSHOnly: true, Run: runAdminUserDisable})
 32	register(Command{Path: []string{"admin", "user", "enable"},
 33		Summary: "restore a suspended account",
 34		Usage:   "admin user enable <username>",
 35		SSHOnly: true, Run: runAdminUserEnable})
 36	register(Command{Path: []string{"admin", "user", "delete"},
 37		Summary: "delete an account that anchors nothing (keys, emails and sessions go with it)",
 38		Usage:   "admin user delete <username> --yes",
 39		SSHOnly: true, Run: runAdminUserDelete})
 40	register(Command{Path: []string{"admin", "email", "verify"},
 41		Summary: "mark an address verified by admin assertion",
 42		Usage:   "admin email verify <username> <address>",
 43		SSHOnly: true, Run: runAdminEmailVerify})
 44	register(Command{Path: []string{"admin", "invite"},
 45		Summary: "issue a registration invite and mail its code",
 46		Usage:   "admin invite --email <address>",
 47		SSHOnly: true, Run: runAdminInvite})
 48	register(Command{Path: []string{"admin", "stats"},
 49		Summary:  "instance statistics: counts and per-repository disk usage",
 50		Usage:    "admin stats",
 51		ReadOnly: true, SSHOnly: true, Run: runAdminStats})
 52}
 53
 54func runAdminUserCreate(c *Ctx, args []string) int {
 55	if code := requireInstanceAdmin(c); code >= 0 {
 56		return code
 57	}
 58	const usage = "usage: admin user create <username> [--admin] [--email <address> [--verified]] [--key -] < key.pub"
 59	f, err := parseFlags(args, flagSpec{Values: []string{"--email", "--key"}, Bools: []string{"--admin", "--verified"}, MaxPos: 1, Usage: usage})
 60	if err != nil {
 61		return c.fail(protocol.ExitUsage, "%v", err)
 62	}
 63	username, email := f.pos(0), f.Value("--email")
 64	isAdmin, verified, withKey := f.Has("--admin"), f.Has("--verified"), f.Has("--key")
 65	if withKey && f.Value("--key") != "-" {
 66		return c.fail(protocol.ExitUsage, "--key only supports - (the public key on stdin)")
 67	}
 68	if username == "" || username[0] == '-' {
 69		return c.fail(protocol.ExitUsage, usage)
 70	}
 71	if username == "" || (verified && email == "") {
 72		return c.fail(protocol.ExitUsage, usage)
 73	}
 74	if err := policy.ValidateOwnerName(username); err != nil {
 75		return c.failErr(err)
 76	}
 77	// Parse the key before creating anything, so a bad key leaves no
 78	// half-made account behind.
 79	var pub ssh.PublicKey
 80	var comment string
 81	if withKey {
 82		raw, err := io.ReadAll(io.LimitReader(c.Stdin, 64<<10))
 83		if err != nil {
 84			return c.fail(protocol.ExitFailure, "reading key: %v", err)
 85		}
 86		if pub, comment, _, _, err = ssh.ParseAuthorizedKey(raw); err != nil {
 87			return c.fail(protocol.ExitUsage, "not a public key in authorized_keys format: %v", err)
 88		}
 89	}
 90	uid, err := c.Store.CreateUser(username, isAdmin)
 91	if err != nil {
 92		return c.failErr(err)
 93	}
 94	if email != "" {
 95		by := ""
 96		if verified {
 97			by = "admin"
 98		}
 99		if err := c.Store.AddEmail(uid, email, by, true); err != nil {
100			return c.failErr(err)
101		}
102	}
103	fp := ""
104	if pub != nil {
105		fp = ssh.FingerprintSHA256(pub)
106		label, _ := keyLabel(comment)
107		if err := c.Store.AddSSHKey(uid, fp, pub.Type(), pub.Marshal(), "full", label); err != nil {
108			return c.failErr(err)
109		}
110	}
111	c.Store.Audit(c.User.ID, "admin user.created", map[string]any{"user": username})
112	type out struct {
113		User        string `json:"user"`
114		Admin       bool   `json:"admin,omitempty"`
115		Fingerprint string `json:"fingerprint,omitempty"`
116	}
117	return c.emit(out{username, isAdmin, fp}, func(w io.Writer) {
118		if fp != "" {
119			fmt.Fprintln(w, "key", fp)
120		}
121		fmt.Fprintln(w, "created user", username)
122	})
123}
124
125// adminUserArg resolves the single username argument of an admin command.
126func adminUserArg(c *Ctx, args []string, usage string) (store.User, int) {
127	if code := requireInstanceAdmin(c); code >= 0 {
128		return store.User{}, code
129	}
130	if len(args) != 1 {
131		return store.User{}, c.fail(protocol.ExitUsage, "usage: %s", usage)
132	}
133	u, err := c.Store.UserByUsername(args[0])
134	if errors.Is(err, store.ErrNotFound) {
135		return u, c.fail(protocol.ExitNotFound, "no user %q", args[0])
136	} else if err != nil {
137		return u, c.fail(protocol.ExitFailure, "%v", err)
138	}
139	return u, -1
140}
141
142func runAdminUserDisable(c *Ctx, args []string) int {
143	u, code := adminUserArg(c, args, "admin user disable <username>")
144	if code >= 0 {
145		return code
146	}
147	if err := c.Store.SetUserDisabled(u.ID, true); err != nil {
148		return c.fail(protocol.ExitFailure, "%v", err)
149	}
150	c.Store.Audit(c.User.ID, "admin user.disabled", map[string]any{"user": u.Username})
151	return c.emit(map[string]any{"user": u.Username, "disabled": true}, func(w io.Writer) {
152		fmt.Fprintf(w, "disabled %s: SSH, web sessions, and API tokens are refused; nothing was deleted\n", u.Username)
153	})
154}
155
156func runAdminUserEnable(c *Ctx, args []string) int {
157	u, code := adminUserArg(c, args, "admin user enable <username>")
158	if code >= 0 {
159		return code
160	}
161	if err := c.Store.SetUserDisabled(u.ID, false); err != nil {
162		return c.fail(protocol.ExitFailure, "%v", err)
163	}
164	c.Store.Audit(c.User.ID, "admin user.enabled", map[string]any{"user": u.Username})
165	return c.emit(map[string]any{"user": u.Username, "disabled": false}, func(w io.Writer) {
166		fmt.Fprintf(w, "enabled %s\n", u.Username)
167	})
168}
169
170func runAdminUserDelete(c *Ctx, args []string) int {
171	var rest []string
172	var yes bool
173	for _, a := range args {
174		if a == "--yes" {
175			yes = true
176		} else {
177			rest = append(rest, a)
178		}
179	}
180	u, code := adminUserArg(c, rest, "admin user delete <username> --yes")
181	if code >= 0 {
182		return code
183	}
184	if !yes {
185		return c.fail(protocol.ExitUsage, "deletion is permanent; pass --yes")
186	}
187	if u.ID == c.User.ID {
188		return c.fail(protocol.ExitUsage, "that is your own account")
189	}
190	if err := c.Store.DeleteUser(u.ID); err != nil {
191		return c.failErr(err)
192	}
193	c.Store.Audit(c.User.ID, "admin user.deleted", map[string]any{"user": u.Username})
194	return c.emit(map[string]string{"deleted": u.Username}, func(w io.Writer) {
195		fmt.Fprintf(w, "deleted %s\n", u.Username)
196	})
197}
198
199func runAdminEmailVerify(c *Ctx, args []string) int {
200	if code := requireInstanceAdmin(c); code >= 0 {
201		return code
202	}
203	if len(args) != 2 {
204		return c.fail(protocol.ExitUsage, "usage: admin email verify <username> <address>")
205	}
206	u, err := c.Store.UserByUsername(args[0])
207	if errors.Is(err, store.ErrNotFound) {
208		return c.fail(protocol.ExitNotFound, "no user %q", args[0])
209	} else if err != nil {
210		return c.fail(protocol.ExitFailure, "%v", err)
211	}
212	if err := c.Store.VerifyEmail(u.ID, args[1], "admin"); err != nil {
213		c.Store.Audit(c.User.ID, "admin email.verify_failed", map[string]any{"user": args[0], "email": args[1]})
214		return c.fail(protocol.ExitNotFound, "no address %s on user %s", args[1], args[0])
215	}
216	c.Store.Audit(c.User.ID, "admin email.verified", map[string]any{"user": args[0], "email": args[1]})
217	return c.emit(map[string]string{"user": args[0], "verified": args[1]}, func(w io.Writer) {
218		fmt.Fprintln(w, "verified", args[1])
219	})
220}
221
222func runAdminInvite(c *Ctx, args []string) int {
223	if code := requireInstanceAdmin(c); code >= 0 {
224		return code
225	}
226	email := ""
227	if len(args) == 2 && args[0] == "--email" {
228		email = args[1]
229	}
230	if email == "" {
231		return c.fail(protocol.ExitUsage, "usage: admin invite --email <address>")
232	}
233	if used, err := c.Store.EmailInUse(email); err != nil {
234		return c.fail(protocol.ExitFailure, "%v", err)
235	} else if used {
236		return c.fail(protocol.ExitUsage, "%s already belongs to an account; invites are for new users", email)
237	}
238	code, hash, err := store.NewToken()
239	if err != nil {
240		return c.fail(protocol.ExitFailure, "%v", err)
241	}
242	if err := c.Store.CreateInvite(hash, email); err != nil {
243		return c.fail(protocol.ExitFailure, "%v", err)
244	}
245	host := siteHost(c.Cfg)
246	body := fmt.Sprintf(
247		"You have been invited to %s.\n\nCreate your account by running (with the SSH key you want to use):\n\n"+
248			"    ssh git@%s register --username <name> --invite %s\n\n"+
249			"The invite is single-use and tied to this address.\n", host, host, code)
250	type out struct {
251		Email  string `json:"email"`
252		Mailed bool   `json:"mailed"`
253		Code   string `json:"code,omitempty"` // only when it could not be mailed
254	}
255	if c.Cfg.Mail.SMTPHost != "" {
256		if err := mail.Send(c.Cfg, email, "your invite to "+host, body); err != nil {
257			return c.fail(protocol.ExitFailure, "invite stored but mail failed: %v (code: %s)", err, code)
258		}
259		c.Store.Audit(c.User.ID, "admin invite.issued", map[string]any{"email": email})
260		return c.emit(out{Email: email, Mailed: true}, func(w io.Writer) {
261			fmt.Fprintf(w, "invite emailed to %s\n", email)
262		})
263	}
264	return c.emit(out{Email: email, Code: code}, func(w io.Writer) {
265		fmt.Fprintf(w, "invite for %s (no SMTP configured; deliver it yourself):\n%s\n", email, code)
266	})
267}
268
269func runAdminStats(c *Ctx, args []string) int {
270	if code := requireInstanceAdmin(c); code >= 0 {
271		return code
272	}
273	if len(args) != 0 {
274		return c.fail(protocol.ExitUsage, "usage: admin stats")
275	}
276	counts, err := c.Store.InstanceCounts()
277	if err != nil {
278		return c.fail(protocol.ExitFailure, "%v", err)
279	}
280	repos, err := c.Store.ListAllRepos()
281	if err != nil {
282		return c.fail(protocol.ExitFailure, "%v", err)
283	}
284	type repoDisk struct {
285		Path  string `json:"path"`
286		Bytes int64  `json:"bytes"`
287	}
288	type out struct {
289		Counts    store.Counts `json:"counts"`
290		DBBytes   int64        `json:"db_bytes"`
291		RepoBytes int64        `json:"repo_bytes"`
292		LFSBytes  int64        `json:"lfs_bytes"`
293		Repos     []repoDisk   `json:"repos"`
294	}
295	d := out{Counts: counts, Repos: []repoDisk{}}
296	d.LFSBytes = lfs.LocalStore{Root: lfs.RootFor(c.Cfg.LFS.Root, c.Cfg.Server.Root)}.Size()
297	for _, r := range repos {
298		b := gitutil.DirSize(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
299		d.Repos = append(d.Repos, repoDisk{r.Path(), b})
300		d.RepoBytes += b
301	}
302	if fi, err := os.Stat(c.Cfg.Server.Root + "/gitbay.db"); err == nil {
303		d.DBBytes = fi.Size()
304	}
305	return c.emit(d, func(w io.Writer) {
306		fmt.Fprintf(w, "users %d · orgs %d · repos %d · issues %d (%d open) · MRs %d (%d open)\n",
307			counts.Users, counts.Orgs, counts.Repos,
308			counts.Issues, counts.OpenIssues, counts.MRs, counts.OpenMRs)
309		fmt.Fprintf(w, "database %s · repositories %s · lfs %s\n\n", humanBytes(d.DBBytes), humanBytes(d.RepoBytes), humanBytes(d.LFSBytes))
310		for _, r := range d.Repos {
311			fmt.Fprintf(w, "%s\t%s\n", r.Path, humanBytes(r.Bytes))
312		}
313	})
314}
315
316func humanBytes(b int64) string {
317	switch {
318	case b >= 1<<30:
319		return fmt.Sprintf("%.1f GiB", float64(b)/(1<<30))
320	case b >= 1<<20:
321		return fmt.Sprintf("%.1f MiB", float64(b)/(1<<20))
322	case b >= 1<<10:
323		return fmt.Sprintf("%.1f KiB", float64(b)/(1<<10))
324	default:
325		return fmt.Sprintf("%d B", b)
326	}
327}