package web import ( "context" "errors" "net/http" "net/url" "strconv" "strings" "time" "supermarket/internal/appmail" "supermarket/internal/audit" "supermarket/internal/users" ) // Signing in and out, and resetting a password by email (the server // edition). // signinForm is what the sign-in pages show. type signinForm struct { Email, Next string Code bool // the second step: the authenticator's code Token string // the sign-in waiting for its code Problem string Sent bool // a reset link went out (or would have) Reset string } // safeNext is where to go after signing in: a path in this app, else the // Overview. func safeNext(next string) string { if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, `/\`) || strings.ContainsAny(next, "\r\n") { return "/" } return next } func (s *Server) signinPage(w http.ResponseWriter, r *http.Request) { if !s.signsIn() { http.Redirect(w, r, "/", http.StatusSeeOther) return } next := safeNext(r.URL.Query().Get("next")) if v, _ := s.lookupSession(r); v != nil { http.Redirect(w, r, next, http.StatusSeeOther) return } s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: signinForm{Next: next, Email: r.URL.Query().Get("email")}}) } func (s *Server) signinFail(w http.ResponseWriter, r *http.Request, f signinForm, code int) { w.WriteHeader(code) s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: f}) } const badSignIn = "That email address and password don't match an account." func (s *Server) signin(w http.ResponseWriter, r *http.Request) { if !s.signsIn() { http.NotFound(w, r) return } now := time.Now() email := strings.ToLower(strings.TrimSpace(r.PostFormValue("email"))) f := signinForm{Email: email, Next: safeNext(r.PostFormValue("next"))} ipKey, emailKey := "signin:ip:"+clientIP(r), "signin:email:"+email if s.throttled(ipKey, users.MaxFailsPerIP, now) || s.throttled(emailKey, users.MaxFailsPerEmail, now) { f.Problem = "Too many failed sign-ins: wait a quarter of an hour, then try again. If you've forgotten your password, reset it." s.signinFail(w, r, f, http.StatusTooManyRequests) return } u, err := users.ByEmail(s.DB, email) if err != nil && !errors.Is(err, users.ErrNotFound) { s.serverError(w, err) return } if err != nil { u = nil } ok := users.CheckPassword(u, r.PostFormValue("password")) if !ok { s.countFailure(ipKey, emailKey, u, now) f.Problem = badSignIn s.signinFail(w, r, f, http.StatusUnauthorized) return } // The password is right: now it's safe to say what else stops them. if msg := s.cannotSignIn(u); msg != "" { f.Problem = msg s.signinFail(w, r, f, http.StatusForbidden) return } if u.TwoFactor { token, err := users.NewLink(s.DB, users.CodeLink, u.ID, now) if err != nil { s.serverError(w, err) return } f.Code, f.Token = true, token s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: f}) return } s.finishSignIn(w, r, u, ipKey, emailKey, f.Next) } // cannotSignIn says why a user with the right password still can't sign // in, or "". func (s *Server) cannotSignIn(u *users.User) string { switch { case u.Locked(): return "This account is locked after too many failed sign-ins. To unlock it, reset your password (below), or ask an admin." case u.Status == users.Disabled: return "This account is turned off. Ask an admin if you need it again." case u.Status != users.Active || u.Kind != users.Person: return badSignIn } if s.multi() { if list, err := users.TeamsOf(s.platform(), u.ID); err != nil || len(list) == 0 { return "This account isn't part of any team any more." } return "" } if _, err := users.MembershipOf(s.DB, s.team(), u.ID); err != nil { return "This account isn't part of the team any more. Ask an admin if you need it again." } return "" } // signinCode is the second step, with the authenticator's code or a // recovery code. func (s *Server) signinCode(w http.ResponseWriter, r *http.Request) { if !s.signsIn() { http.NotFound(w, r) return } now := time.Now() token := r.PostFormValue("token") f := signinForm{Next: safeNext(r.PostFormValue("next")), Code: true, Token: token} id, err := users.PeekLink(s.DB, token, users.CodeLink, now) if err != nil { if !errors.Is(err, users.ErrBadLink) { s.serverError(w, err) return } f = signinForm{Next: f.Next, Problem: "That took too long: sign in again."} s.signinFail(w, r, f, http.StatusUnauthorized) return } u, err := users.ByID(s.DB, id) if err != nil { s.serverError(w, err) return } ipKey, emailKey := "signin:ip:"+clientIP(r), "signin:email:"+u.Email if s.throttled(ipKey, users.MaxFailsPerIP, now) || s.throttled(emailKey, users.MaxFailsPerEmail, now) { _ = users.DropLinks(s.DB, users.CodeLink, u.ID) f = signinForm{Next: f.Next, Problem: "Too many failed sign-ins: wait a quarter of an hour, then try again."} s.signinFail(w, r, f, http.StatusTooManyRequests) return } if msg := s.cannotSignIn(u); msg != "" { _ = users.DropLinks(s.DB, users.CodeLink, u.ID) s.signinFail(w, r, signinForm{Next: f.Next, Problem: msg}, http.StatusForbidden) return } code := strings.TrimSpace(r.PostFormValue("code")) ok := false if step, good := users.CheckTOTP(s.Secrets.Get(users.TOTPSecretName(u.ID)), code, u.TOTPStep(), now); good { if err := users.UseTOTPStep(s.DB, u, step); err != nil { s.serverError(w, err) return } ok = true } else if len(code) > 6 { if ok, err = users.UseRecoveryCode(s.DB, u, code); err != nil { s.serverError(w, err) return } if ok { s.Log.Info("signin: a recovery code was used", "user", u.Email, "left", u.RecoveryLeft) } } if !ok { s.countFailure(ipKey, emailKey, u, now) f.Problem = "That code isn't right. Codes change every 30 seconds; enter the one showing now, or a recovery code." s.signinFail(w, r, f, http.StatusUnauthorized) return } if _, err := users.UseLink(s.DB, token, users.CodeLink, now); err != nil { s.signinFail(w, r, signinForm{Next: f.Next, Problem: "That took too long: sign in again."}, http.StatusUnauthorized) return } s.finishSignIn(w, r, u, ipKey, emailKey, f.Next) } // finishSignIn starts the session, clears the failures, and goes on. func (s *Server) finishSignIn(w http.ResponseWriter, r *http.Request, u *users.User, ipKey, emailKey, next string) { if err := users.Unlock(s.DB, u.ID); err != nil { s.serverError(w, err) return } _ = users.ClearFails(s.DB, emailKey) if err := s.startSession(w, r, u); err != nil { s.serverError(w, err) return } s.Log.Info("signin", "user", u.Email, "ip", clientIP(r)) s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "signin", IP: clientIP(r)}) if u.TwoFactor && u.RecoveryLeft < 3 { redirect(w, r, "/settings/account#two-factor", "codes-low") return } http.Redirect(w, r, next, http.StatusSeeOther) } // throttled says whether key has failed too often lately. func (s *Server) throttled(key string, max int, now time.Time) bool { n, _ := users.Fails(s.DB, key, users.ThrottleWindow, now) return n >= max } // countFailure counts a failed sign-in against the IP, the address and // the account, which locks after too many; its owner is told. func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Time) { for _, k := range []string{ipKey, emailKey} { if err := users.Fail(s.DB, k, users.ThrottleWindow, now); err != nil { s.Log.Warn("signin: counting a failure", "err", err) } } ip := strings.TrimPrefix(ipKey, "signin:ip:") if u == nil { s.Log.Info("signin: failed, no such account", "key", emailKey, "ip", ip) s.record(audit.Entry{Action: "signin-failed", Target: strings.TrimPrefix(emailKey, "signin:email:"), Detail: "no such account", IP: ip}) return } s.Log.Info("signin: failed", "user", u.Email, "ip", ip) s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "signin-failed", Target: u.Email, IP: ip}) locked, err := users.FailedSignIn(s.DB, u, now) if err != nil { s.Log.Warn("signin: counting a failure", "err", err) return } if locked { s.Log.Warn("signin: account locked", "user", u.Email) s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "locked", Target: u.Email, Detail: strconv.Itoa(users.LockAfter) + " failed sign-ins in a row", IP: ip}) s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Your Supermarket account is locked", Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + "Your account at " + s.PublicURL + " was locked after " + strconv.Itoa(users.LockAfter) + " failed sign-ins in a row.\n\n" + "To unlock it, reset your password:\n" + s.PublicURL + "/forgot\n\nor ask an admin to unlock it.\n\n" + "If those sign-ins weren't you, someone may be guessing your password. A long password used nowhere else, " + "and two-factor sign-in (Settings → Your account), keep them out.\n"}) } } func (s *Server) signout(w http.ResponseWriter, r *http.Request) { if viewerOf(r).User != nil { s.audit(r, "signout", "", "") } if err := s.endSession(w, r); err != nil { s.serverError(w, err) return } redirect(w, r, "/signin", "signed-out") } // Resetting a password. func (s *Server) forgotPage(w http.ResponseWriter, r *http.Request) { if !s.signsIn() { http.NotFound(w, r) return } s.render(w, r, "forgot", page{Title: "Reset your password", Bare: true, Data: signinForm{Email: r.URL.Query().Get("email")}}) } func (s *Server) forgot(w http.ResponseWriter, r *http.Request) { if !s.signsIn() { http.NotFound(w, r) return } now := time.Now() email := strings.ToLower(strings.TrimSpace(r.PostFormValue("email"))) f := signinForm{Email: email, Sent: true} // The same answer whether or not there's an account, and the email is // sent in the background, so the page can't tell anyone which // addresses have one. Limited per IP and per address. ipKey, emailKey := "reset:ip:"+clientIP(r), "reset:email:"+email if s.throttled(ipKey, 10, now) || s.throttled(emailKey, 3, now) { f.Sent, f.Problem = false, "Several links were sent already: check your email (and its spam folder), or wait a quarter of an hour." w.WriteHeader(http.StatusTooManyRequests) s.render(w, r, "forgot", page{Title: "Reset your password", Bare: true, Data: f}) return } _ = users.Fail(s.DB, ipKey, users.ThrottleWindow, now) _ = users.Fail(s.DB, emailKey, users.ThrottleWindow, now) if u, err := users.ByEmail(s.DB, email); err == nil && u.Kind == users.Person && (u.Status == users.Active) { token, err := users.NewLink(s.DB, users.ResetLink, u.ID, now) if err != nil { s.serverError(w, err) return } s.Log.Info("signin: password reset asked for", "user", u.Email, "ip", clientIP(r)) s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "reset-asked", Target: u.Email, IP: clientIP(r)}) s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Reset your Supermarket password", Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + "Someone, probably you, asked to reset your password at " + s.PublicURL + ".\n\n" + "Choose a new one here, within an hour:\n" + s.PublicURL + "/reset/" + token + "\n\n" + "If it wasn't you, ignore this email: your password stays as it is.\n"}) } else if err != nil && !errors.Is(err, users.ErrNotFound) { s.serverError(w, err) return } s.render(w, r, "forgot", page{Title: "Reset your password", Bare: true, Data: f}) } func (s *Server) resetPage(w http.ResponseWriter, r *http.Request) { if !s.signsIn() { http.NotFound(w, r) return } token := r.PathValue("token") f := signinForm{Reset: token} if _, err := users.PeekLink(s.DB, token, users.ResetLink, time.Now()); err != nil { f.Reset, f.Problem = "", "This reset link has expired or was already used. Ask for a new one below." w.WriteHeader(http.StatusNotFound) } s.render(w, r, "forgot", page{Title: "Choose a new password", Bare: true, Data: f}) } func (s *Server) reset(w http.ResponseWriter, r *http.Request) { if !s.signsIn() { http.NotFound(w, r) return } now := time.Now() token := r.PathValue("token") f := signinForm{Reset: token} id, err := users.PeekLink(s.DB, token, users.ResetLink, now) if err != nil { s.resetPage(w, r) return } u, err := users.ByID(s.DB, id) if err != nil { s.serverError(w, err) return } pw := r.PostFormValue("password") if err := users.CheckNewPassword(pw, u.Email); err != nil { f.Problem = sentence(err.Error()) + "." } else if pw != r.PostFormValue("password2") { f.Problem = "The two passwords aren't the same." } if f.Problem != "" { w.WriteHeader(http.StatusUnprocessableEntity) s.render(w, r, "forgot", page{Title: "Choose a new password", Bare: true, Data: f}) return } if _, err := users.UseLink(s.DB, token, users.ResetLink, now); err != nil { s.resetPage(w, r) return } if err := users.SetPassword(s.DB, u, pw); err != nil { s.serverError(w, err) return } // The email proved who they are: the lock goes, and so does every // session, in case someone else had one. if err := users.Unlock(s.DB, u.ID); err != nil { s.serverError(w, err) return } if _, err := users.EndOtherSessions(s.DB, u.ID, ""); err != nil { s.serverError(w, err) return } _ = users.ClearFails(s.DB, "signin:email:"+u.Email) s.Log.Info("signin: password reset", "user", u.Email, "ip", clientIP(r)) s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "password-reset", Target: u.Email, IP: clientIP(r)}) redirect(w, r, "/signin?email="+url.QueryEscape(u.Email), "password-reset") } // sendMail sends the app's own mail in the background, so how long it // takes says nothing to the person waiting. func (s *Server) sendMail(m appmail.Message) { if s.Mail == nil { s.Log.Error("mail: no mail server (SUPERMARKET_MAIL_URL): not sent", "to", m.To, "subject", m.Subject) return } go func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() if err := s.Mail.Send(ctx, m); err != nil { s.Log.Error("mail: not sent", "to", m.To, "subject", m.Subject, "err", err) } }() } func nameSuffix(name string) string { if name = strings.TrimSpace(name); name != "" { return " " + strings.Fields(name)[0] } return "" } // RunAccounts forgets ended sessions, used-up links, old counts of failed // sign-ins, the audit log past two years and agents' calls past 30 days, // every hour. func (s *Server) RunAccounts(ctx context.Context) { tick := time.NewTicker(time.Hour) defer tick.Stop() for { s.jobDo(ctx, "accounts", func(_ context.Context, s *Server) { now := time.Now() if _, err := users.PruneSessions(s.DB, now); err != nil { s.Log.Warn("accounts: pruning sessions", "err", err) } if err := users.PruneLinks(s.DB, now); err != nil { s.Log.Warn("accounts: pruning links", "err", err) } if err := users.PruneThrottle(s.DB, now); err != nil { s.Log.Warn("accounts: pruning counts", "err", err) } s.pruneAudit(now) if err := users.PruneCalls(s.DB, now); err != nil { s.Log.Warn("accounts: pruning agents' calls", "err", err) } }) select { case <-ctx.Done(): return case <-tick.C: } } }