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