internal/control/adminhost.go

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

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