internal/control/register.go

da232bfde4952959944a074ccec455f38eab3b66
gitbay/internal/control/register.go history · blame · raw

273 lines · 10552 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"strings"
  8	"time"
  9
 10	"golang.org/x/crypto/ssh"
 11
 12	"gitbay.org/gitbay/internal/config"
 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
 19func init() {
 20	register(Command{Path: []string{"register"},
 21		Summary: "create an account (only meaningful for unregistered keys)",
 22		Usage:   "register --username <name> [--email <address> | --invite <code>]",
 23		Run: func(c *Ctx, args []string) int {
 24			return c.fail(protocol.ExitUsage,
 25				"this SSH key already belongs to %s. To register a new account, connect with the key it should use:\n  ssh -F /dev/null -i <newkey> git@<host> register ...",
 26				c.User.Username)
 27		}})
 28	register(Command{Path: []string{"email", "add"},
 29		Summary: "add an address and mail a verification code",
 30		Usage:   "email add <address>", Run: runEmailAdd})
 31	register(Command{Path: []string{"email", "verify"},
 32		Summary: "confirm a verification code",
 33		Usage:   "email verify <code>", Run: runEmailVerify})
 34	register(Command{Path: []string{"email", "list"},
 35		Summary:  "list the addresses on your account",
 36		Usage:    "email list",
 37		ReadOnly: true, Run: runEmailList})
 38	register(Command{Path: []string{"email", "remove"},
 39		Summary: "remove an address; not the primary, nor the last verified one",
 40		Usage:   "email remove <address>", Run: runEmailRemove})
 41	register(Command{Path: []string{"email", "primary"},
 42		Summary: "make a verified address the primary",
 43		Usage:   "email primary <address>", Run: runEmailPrimary})
 44}
 45
 46func runEmailList(c *Ctx, args []string) int {
 47	if len(args) != 0 {
 48		return c.usage()
 49	}
 50	emails, err := c.Store.ListEmails(c.User.ID)
 51	if err != nil {
 52		return c.fail(protocol.ExitFailure, "listing addresses: %v", err)
 53	}
 54	type out struct {
 55		Address    string `json:"address"`
 56		Verified   bool   `json:"verified"`
 57		VerifiedBy string `json:"verified_by,omitempty"`
 58		Primary    bool   `json:"primary"`
 59	}
 60	ds := make([]out, 0, len(emails))
 61	for _, e := range emails {
 62		ds = append(ds, out{e.Address, e.Verified, e.VerifiedBy, e.Primary})
 63	}
 64	return c.emit(ds, func(w io.Writer) {
 65		for _, d := range ds {
 66			state := "unverified"
 67			if d.Verified {
 68				state = "verified"
 69			}
 70			if d.Primary {
 71				state += "\tprimary"
 72			}
 73			fmt.Fprintf(w, "%s\t%s\n", d.Address, state)
 74		}
 75	})
 76}
 77
 78// emailErr maps the store's refusals onto exit codes: a missing address is
 79// not found, a rule is denied, anything else is a failure.
 80func emailErr(c *Ctx, verb string, err error) int {
 81	switch {
 82	case errors.Is(err, store.ErrNotFound):
 83		return c.fail(protocol.ExitNotFound, "no such address on your account")
 84	case errors.Is(err, store.ErrPrimaryEmail), errors.Is(err, store.ErrLastVerifiedEmail), errors.Is(err, store.ErrUnverifiedEmail):
 85		return c.fail(protocol.ExitDenied, "%v", err)
 86	}
 87	return c.fail(protocol.ExitFailure, "%s: %v", verb, err)
 88}
 89
 90func runEmailRemove(c *Ctx, args []string) int {
 91	if len(args) != 1 {
 92		return c.usage()
 93	}
 94	if err := c.Store.RemoveEmail(c.User.ID, args[0]); err != nil {
 95		return emailErr(c, "removing address", err)
 96	}
 97	return c.emit(map[string]string{"address": args[0], "status": "removed"}, func(w io.Writer) {
 98		fmt.Fprintf(w, "%s removed\n", args[0])
 99	})
100}
101
102func runEmailPrimary(c *Ctx, args []string) int {
103	if len(args) != 1 {
104		return c.usage()
105	}
106	if err := c.Store.SetPrimaryEmail(c.User.ID, args[0]); err != nil {
107		return emailErr(c, "setting primary", err)
108	}
109	return c.emit(map[string]string{"address": args[0], "status": "primary"}, func(w io.Writer) {
110		fmt.Fprintf(w, "%s is now the primary address\n", args[0])
111	})
112}
113
114func siteHost(cfg config.Config) string {
115	h := strings.TrimPrefix(strings.TrimPrefix(cfg.Server.SiteURL, "https://"), "http://")
116	return strings.TrimSuffix(h, "/")
117}
118
119func sendVerification(cfg config.Config, st *store.Store, userID int64, address string) error {
120	code, hash, err := store.NewToken()
121	if err != nil {
122		return err
123	}
124	if err := st.CreateEmailToken(userID, address, hash, 24*time.Hour); err != nil {
125		return err
126	}
127	body := fmt.Sprintf(
128		"Someone (hopefully you) added this address to an account on %s.\n\n"+
129			"To verify it, run:\n\n    ssh git@%s email verify %s\n\n"+
130			"Or sign in at https://%s/login with this address and paste the code under Settings.\n\n"+
131			"The code expires in 24 hours. If this wasn't you, ignore this mail.\n",
132		siteHost(cfg), siteHost(cfg), code, siteHost(cfg))
133	return mail.Send(cfg, address, "verify your email on "+siteHost(cfg), body)
134}
135
136const maxEmailAddsPerHour = 5
137
138func runEmailAdd(c *Ctx, args []string) int {
139	if len(args) != 1 || !strings.Contains(args[0], "@") {
140		return c.usage()
141	}
142	if c.Cfg.Mail.SMTPHost == "" {
143		return c.fail(protocol.ExitFailure, "this instance has no SMTP configured; ask an admin to verify the address (gitbayd admin email verify)")
144	}
145	// An authenticated account is not a mail cannon: a handful of codes an
146	// hour is plenty for a person and nothing for a script (#136).
147	if n, err := c.Store.CountEmailTokensSince(c.User.ID, time.Now().Add(-time.Hour)); err != nil {
148		return c.fail(protocol.ExitFailure, "%v", err)
149	} else if n >= maxEmailAddsPerHour {
150		return c.fail(protocol.ExitDenied, "%d verification mails in the last hour; try again later", n)
151	}
152	if err := c.Store.AddEmail(c.User.ID, args[0], "", false); err != nil {
153		return c.fail(protocol.ExitFailure, "%v", err)
154	}
155	if err := sendVerification(c.Cfg, c.Store, c.User.ID, args[0]); err != nil {
156		return c.fail(protocol.ExitFailure, "sending verification mail: %v", err)
157	}
158	return c.emit(map[string]string{"address": args[0], "status": "verification_sent"}, func(w io.Writer) {
159		fmt.Fprintf(w, "verification code sent to %s\n", args[0])
160	})
161}
162
163func runEmailVerify(c *Ctx, args []string) int {
164	if len(args) != 1 {
165		return c.usage()
166	}
167	hash := store.HashToken(args[0])
168	address, err := c.Store.ConsumeEmailToken(c.User.ID, hash)
169	if err != nil {
170		if errors.Is(err, store.ErrNotFound) {
171			// A code is scoped to the account that asked for it. Running
172			// this with the wrong key authenticates as the wrong account
173			// and looks exactly like a bad code, which is misleading when
174			// the code is fine and the key is not.
175			if other, e := c.Store.EmailTokenBelongsToAnotherUser(c.User.ID, hash); e == nil && other {
176				return c.fail(protocol.ExitDenied,
177					"that code belongs to a different account; this key authenticated you as %s. "+
178						"Re-run with the key registered to the account being verified: "+
179						"ssh -i <that key> git@<host> email verify <code>",
180					c.User.Username)
181			}
182			return c.fail(protocol.ExitUsage, "that code is invalid, expired, or already used")
183		}
184		return c.fail(protocol.ExitFailure, "%v", err)
185	}
186	if err := c.Store.VerifyEmail(c.User.ID, address, "smtp"); err != nil {
187		return c.fail(protocol.ExitFailure, "%v", err)
188	}
189	if err := c.Store.ClearPending(c.User.ID); err != nil {
190		return c.fail(protocol.ExitFailure, "%v", err)
191	}
192	return c.emit(map[string]string{"address": address, "status": "verified"}, func(w io.Writer) {
193		fmt.Fprintf(w, "%s verified; your account is active\n", address)
194	})
195}
196
197// RunRegister handles the one command an UNAUTHENTICATED key may run. It is
198// dispatched outside the normal registry: the caller has already checked
199// that registration is enabled and that argv[0] == "register".
200func RunRegister(cfg config.Config, st *store.Store, pub ssh.PublicKey, argv []string,
201	stdout, stderr io.Writer) int {
202	f, err := parseFlags(argv[1:], flagSpec{Values: []string{"--username", "--email", "--invite"}, MaxPos: 0,
203		Usage: "register --username <n> --email <a> | --invite <code>"})
204	if err != nil {
205		fmt.Fprintln(stderr, err)
206		return protocol.ExitUsage
207	}
208	username, email, invite := f.Value("--username"), f.Value("--email"), f.Value("--invite")
209	fail := func(code int, format string, a ...any) int {
210		fmt.Fprintf(stderr, format+"\n", a...)
211		return code
212	}
213	if username == "" {
214		return fail(protocol.ExitUsage, "usage: register --username <name> --email <address> | register --username <name> --invite <code>")
215	}
216	if err := policy.ValidateOwnerName(username); err != nil {
217		return fail(protocol.ExitUsage, "%v", err)
218	}
219
220	msg, errMsg, code := RegisterAccount(cfg, st, pub, username, email, invite)
221	if code != protocol.ExitOK {
222		return fail(code, "%s", errMsg)
223	}
224	fmt.Fprint(stdout, msg)
225	return protocol.ExitOK
226}
227
228// RegisterAccount creates an account for pub under the instance's
229// registration mode. On success it returns the human message and ExitOK;
230// otherwise an error message and the classifying exit code. Shared by the
231// SSH register command and the web signup form.
232func RegisterAccount(cfg config.Config, st *store.Store, pub ssh.PublicKey, username, email, invite string) (string, string, int) {
233	if err := policy.ValidateOwnerName(username); err != nil {
234		return "", err.Error(), protocol.ExitUsage
235	}
236	fp := ssh.FingerprintSHA256(pub)
237	switch cfg.Registration.Mode {
238	case "invite":
239		if invite == "" {
240			return "", "this instance is invite-only: an invite code is required", protocol.ExitDenied
241		}
242		// One transaction: a failure at any step leaves the invite
243		// redeemable and no partial account behind.
244		_, err := st.RedeemInvite(store.HashToken(invite), username, fp, pub.Type(), pub.Marshal())
245		if err != nil {
246			if errors.Is(err, store.ErrNotFound) {
247				return "", "that invite is invalid or already used", protocol.ExitDenied
248			}
249			return "", err.Error(), protocol.ExitUsage
250		}
251		st.Audit(0, "auth.registered", map[string]any{"user": username, "mode": "invite", "fingerprint": fp})
252		return fmt.Sprintf("welcome, %s — your account is active\n", username), "", protocol.ExitOK
253
254	case "open":
255		if email == "" || !strings.Contains(email, "@") {
256			return "", "a valid email address is required", protocol.ExitUsage
257		}
258		uid, err := st.RegisterOpen(username, email, fp, pub.Type(), pub.Marshal())
259		if err != nil {
260			return "", err.Error(), protocol.ExitUsage
261		}
262		if err := sendVerification(cfg, st, uid, email); err != nil {
263			return "", "sending verification mail: " + err.Error(), protocol.ExitFailure
264		}
265		st.Audit(uid, "auth.registered", map[string]any{"user": username, "mode": "open", "fingerprint": fp})
266		return fmt.Sprintf(
267			"account %s created. A verification code was sent to %s.\nActivate with:\n\n    ssh git@%s email verify <code>\n",
268			username, email, siteHost(cfg)), "", protocol.ExitOK
269
270	default:
271		return "", "registration is closed on this instance", protocol.ExitDenied
272	}
273}