internal/control/register.go

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

201 lines · 7694 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}
 35
 36func siteHost(cfg config.Config) string {
 37	h := strings.TrimPrefix(strings.TrimPrefix(cfg.Server.SiteURL, "https://"), "http://")
 38	return strings.TrimSuffix(h, "/")
 39}
 40
 41func sendVerification(cfg config.Config, st *store.Store, userID int64, address string) error {
 42	code, hash, err := store.NewToken()
 43	if err != nil {
 44		return err
 45	}
 46	if err := st.CreateEmailToken(userID, address, hash, 24*time.Hour); err != nil {
 47		return err
 48	}
 49	body := fmt.Sprintf(
 50		"Someone (hopefully you) added this address to an account on %s.\n\n"+
 51			"To verify it, run:\n\n    ssh git@%s email verify %s\n\n"+
 52			"The code expires in 24 hours. If this wasn't you, ignore this mail.\n",
 53		siteHost(cfg), siteHost(cfg), code)
 54	return mail.Send(cfg, address, "verify your email on "+siteHost(cfg), body)
 55}
 56
 57func runEmailAdd(c *Ctx, args []string) int {
 58	if len(args) != 1 || !strings.Contains(args[0], "@") {
 59		return c.fail(protocol.ExitUsage, "usage: email add <address>")
 60	}
 61	if c.Cfg.Mail.SMTPHost == "" {
 62		return c.fail(protocol.ExitFailure, "this instance has no SMTP configured; ask an admin to verify the address (gitbayd admin email verify)")
 63	}
 64	if err := c.Store.AddEmail(c.User.ID, args[0], "", false); err != nil {
 65		return c.fail(protocol.ExitFailure, "%v", err)
 66	}
 67	if err := sendVerification(c.Cfg, c.Store, c.User.ID, args[0]); err != nil {
 68		return c.fail(protocol.ExitFailure, "sending verification mail: %v", err)
 69	}
 70	return c.emit(map[string]string{"address": args[0], "status": "verification_sent"}, func(w io.Writer) {
 71		fmt.Fprintf(w, "verification code sent to %s\n", args[0])
 72	})
 73}
 74
 75func runEmailVerify(c *Ctx, args []string) int {
 76	if len(args) != 1 {
 77		return c.fail(protocol.ExitUsage, "usage: email verify <code>")
 78	}
 79	hash := store.HashToken(args[0])
 80	address, err := c.Store.ConsumeEmailToken(c.User.ID, hash)
 81	if err != nil {
 82		if errors.Is(err, store.ErrNotFound) {
 83			// A code is scoped to the account that asked for it. Running
 84			// this with the wrong key authenticates as the wrong account
 85			// and looks exactly like a bad code, which is misleading when
 86			// the code is fine and the key is not.
 87			if other, e := c.Store.EmailTokenBelongsToAnotherUser(c.User.ID, hash); e == nil && other {
 88				return c.fail(protocol.ExitDenied,
 89					"that code belongs to a different account; this key authenticated you as %s. "+
 90						"Re-run with the key registered to the account being verified: "+
 91						"ssh -i <that key> git@<host> email verify <code>",
 92					c.User.Username)
 93			}
 94			return c.fail(protocol.ExitUsage, "that code is invalid, expired, or already used")
 95		}
 96		return c.fail(protocol.ExitFailure, "%v", err)
 97	}
 98	if err := c.Store.VerifyEmail(c.User.ID, address, "smtp"); err != nil {
 99		return c.fail(protocol.ExitFailure, "%v", err)
100	}
101	if err := c.Store.ClearPending(c.User.ID); err != nil {
102		return c.fail(protocol.ExitFailure, "%v", err)
103	}
104	return c.emit(map[string]string{"address": address, "status": "verified"}, func(w io.Writer) {
105		fmt.Fprintf(w, "%s verified; your account is active\n", address)
106	})
107}
108
109// RunRegister handles the one command an UNAUTHENTICATED key may run. It is
110// dispatched outside the normal registry: the caller has already checked
111// that registration is enabled and that argv[0] == "register".
112func RunRegister(cfg config.Config, st *store.Store, pub ssh.PublicKey, argv []string,
113	stdout, stderr io.Writer) int {
114	var username, email, invite string
115	args := argv[1:]
116	for i := 0; i < len(args); i++ {
117		switch args[i] {
118		case "--username", "--email", "--invite":
119			if i+1 >= len(args) {
120				fmt.Fprintf(stderr, "%s requires a value\n", args[i])
121				return protocol.ExitUsage
122			}
123			switch args[i] {
124			case "--username":
125				username = args[i+1]
126			case "--email":
127				email = args[i+1]
128			case "--invite":
129				invite = args[i+1]
130			}
131			i++
132		default:
133			fmt.Fprintf(stderr, "unexpected argument %q\n", args[i])
134			return protocol.ExitUsage
135		}
136	}
137	fail := func(code int, format string, a ...any) int {
138		fmt.Fprintf(stderr, format+"\n", a...)
139		return code
140	}
141	if username == "" {
142		return fail(protocol.ExitUsage, "usage: register --username <name> --email <address> | register --username <name> --invite <code>")
143	}
144	if err := policy.ValidateOwnerName(username); err != nil {
145		return fail(protocol.ExitUsage, "%v", err)
146	}
147
148	msg, errMsg, code := RegisterAccount(cfg, st, pub, username, email, invite)
149	if code != protocol.ExitOK {
150		return fail(code, "%s", errMsg)
151	}
152	fmt.Fprint(stdout, msg)
153	return protocol.ExitOK
154}
155
156// RegisterAccount creates an account for pub under the instance's
157// registration mode. On success it returns the human message and ExitOK;
158// otherwise an error message and the classifying exit code. Shared by the
159// SSH register command and the web signup form.
160func RegisterAccount(cfg config.Config, st *store.Store, pub ssh.PublicKey, username, email, invite string) (string, string, int) {
161	if err := policy.ValidateOwnerName(username); err != nil {
162		return "", err.Error(), protocol.ExitUsage
163	}
164	fp := ssh.FingerprintSHA256(pub)
165	switch cfg.Registration.Mode {
166	case "invite":
167		if invite == "" {
168			return "", "this instance is invite-only: an invite code is required", protocol.ExitDenied
169		}
170		// One transaction: a failure at any step leaves the invite
171		// redeemable and no partial account behind.
172		_, err := st.RedeemInvite(store.HashToken(invite), username, fp, pub.Type(), pub.Marshal())
173		if err != nil {
174			if errors.Is(err, store.ErrNotFound) {
175				return "", "that invite is invalid or already used", protocol.ExitDenied
176			}
177			return "", err.Error(), protocol.ExitUsage
178		}
179		st.Audit(0, "auth.registered", map[string]any{"user": username, "mode": "invite", "fingerprint": fp})
180		return fmt.Sprintf("welcome, %s — your account is active\n", username), "", protocol.ExitOK
181
182	case "open":
183		if email == "" || !strings.Contains(email, "@") {
184			return "", "a valid email address is required", protocol.ExitUsage
185		}
186		uid, err := st.RegisterOpen(username, email, fp, pub.Type(), pub.Marshal())
187		if err != nil {
188			return "", err.Error(), protocol.ExitUsage
189		}
190		if err := sendVerification(cfg, st, uid, email); err != nil {
191			return "", "sending verification mail: " + err.Error(), protocol.ExitFailure
192		}
193		st.Audit(uid, "auth.registered", map[string]any{"user": username, "mode": "open", "fingerprint": fp})
194		return fmt.Sprintf(
195			"account %s created. A verification code was sent to %s.\nActivate with:\n\n    ssh git@%s email verify <code>\n",
196			username, email, siteHost(cfg)), "", protocol.ExitOK
197
198	default:
199		return "", "registration is closed on this instance", protocol.ExitDenied
200	}
201}