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