internal/control/register.go

93b38a063b3b4b161a1baf976e92f53d02b1a221
gitbay/internal/control/register.go history · blame · raw

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