feat: verified sign-up and several organizations per account
ci / image (pull_request) Successful in 3m59s
ci / build (pull_request) Successful in 5m46s
ci / test (pull_request) Successful in 12m32s
ci / lint (pull_request) Successful in 14m9s

New accounts confirm their email address before signing in: sign-up
mails a link valid for 24 hours, and its page confirms only when the
visitor presses the button, so mail scanners opening links do not sign
in. Confirming signs the account in; unconfirmed accounts are told so
only after giving the right password, can ask for a new link, and are
deleted after a week. UPTIME_SIGNUP_VERIFY requires confirmation always
in the cloud edition and self-hosted wherever mail can be sent; without
a mail server, sign-up that needs it stays closed.

One account per mailbox: users.email_key drops +suffixes, and dots for
Gmail, and is unique, including for accounts created through
invitations and SSO, which count as confirmed. A client address (IPv6:
its /64) may create UPTIME_SIGNUPS_PER_IP accounts a day, 2 by default;
refused sign-ups do not count.

Sign-up asks only for name, email and password. Accounts without an
organization are led to create one; signed-in users create further
organizations from the switcher, within the per-account limit, and
POST /api/v1/orgs does the same.

Closes #112
Closes #113

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 21:59:12 +01:00
1 parent d644312f25
commit 87b2f2a256
29 files changed
+1698 -377

No files matched your search

+1 -1
View File
@@ -60,7 +60,7 @@ func (r *receiver) kinds() []string {
func TestAlerting(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) { c.SMTPURL = mail.URL() })
e := newEnvWith(t, func(c *config.API) { c.SMTPURL, c.SignupVerify = mail.URL(), "off" })
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
+11 -2
View File
@@ -22,9 +22,18 @@ func paged(o obj) obj {
// show them.
var endpoints = []endpoint{
// Account
{method: "POST", path: "/api/v1/auth/signup", tag: "Account", summary: "Create an account and organization", public: true,
description: "Starts a session. Depending on the installation, sign-up is open, limited to the first user, or closed.",
{method: "POST", path: "/api/v1/auth/signup", tag: "Account", summary: "Create an account", public: true,
description: "Depending on the installation, sign-up is open, limited to the first user, or closed. Where addresses are confirmed, answers `{\"status\": \"verification_sent\"}` and mails a link; the account signs in after confirming. Otherwise starts a session, and `org_name`/`org_slug`, if given, create a first organization. One account per mailbox (+suffixes and Gmail dots count as the same address); a client address may create only a few accounts a day (`429 signup_limit`).",
req: signupRequest{}, resp: sessionStarted},
{method: "POST", path: "/api/v1/auth/verify", tag: "Account", summary: "Confirm an email address with the mailed token", public: true,
description: "Signs the account in. Tokens are valid for 24 hours and once; `410 verification_expired` otherwise.",
req: verifyRequest{}, resp: sessionStarted},
{method: "POST", path: "/api/v1/auth/verify/resend", tag: "Account", summary: "Mail a new confirmation link", public: true,
description: "Answers the same whether or not an unconfirmed account with that address exists.",
req: resendRequest{}, status: http.StatusNoContent},
{method: "POST", path: "/api/v1/orgs", tag: "Account", summary: "Create an organization", sessionOnly: true,
description: "The account owns it, and it becomes the active organization. Limited per account by the platform (`422 org_limit`).",
req: createOrgRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}, "slug": "", "redirect": ""}},
{method: "POST", path: "/api/v1/auth/login", tag: "Account", summary: "Sign in with email and password", public: true,
description: "Answers `{\"status\": \"totp_required\"}` when the account has two-factor authentication; continue with /auth/login/totp.",
req: loginRequest{}, resp: sessionStarted},
+3
View File
@@ -31,6 +31,9 @@ var auditActions = map[string]string{
"POST /api/v1/locale": "",
"POST /api/v1/markdown/preview": "",
"POST /api/v1/auth/signup": "account.signup",
"POST /api/v1/auth/verify": "account.verify",
"POST /api/v1/auth/verify/resend": "",
"POST /api/v1/orgs": "org.create",
"POST /api/v1/auth/login": "auth.login",
"POST /api/v1/auth/login/totp": "auth.login",
"POST /api/v1/auth/logout": "auth.logout",
+52 -11
View File
@@ -30,8 +30,11 @@ type signupRequest struct {
Email string `json:"email" binding:"required,email,max=320"`
Password string `json:"password" binding:"required,max=1024"`
DisplayName string `json:"display_name" binding:"max=200"`
OrgName string `json:"org_name" binding:"required,max=200"`
OrgSlug string `json:"org_slug" binding:"required,max=63"`
// OrgName and OrgSlug create a first organization at once, when no
// email confirmation is needed; otherwise the account creates one
// after confirming.
OrgName string `json:"org_name" binding:"max=200"`
OrgSlug string `json:"org_slug" binding:"max=63"`
}
func (s *Server) signup(c *gin.Context) {
@@ -50,6 +53,15 @@ func (s *Server) signup(c *gin.Context) {
fail(c, http.StatusForbidden, "signup_closed")
return
}
if left, err := s.signupsLeft(c); err != nil {
internalError(c, err)
return
} else if !left {
fail(c, http.StatusTooManyRequests, "signup_limit")
return
}
verify := s.verificationRequired()
withOrg := !verify && strings.TrimSpace(req.OrgName) != "" && strings.TrimSpace(req.OrgSlug) != ""
hash, err := auth.HashPassword(req.Password)
if errors.Is(err, auth.ErrPasswordTooShort) {
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
@@ -63,20 +75,27 @@ func (s *Server) signup(c *gin.Context) {
var user store.User
err = s.db.Tx(ctx, tenant.Org(orgID, uuid.Nil), func(q *store.Queries) error {
var err error
user, err = q.CreateUser(ctx, store.CreateUserParams{
params := store.CreateUserParams{
Email: normalizeEmail(req.Email),
DisplayName: strings.TrimSpace(req.DisplayName),
PasswordHash: &hash,
Locale: ptr(i18n.Lang(ctx)),
})
EmailKey: ptr(emailKey(req.Email)),
}
if !verify {
params.EmailVerifiedAt = ptr(time.Now())
}
user, err = q.CreateUser(ctx, params)
if err != nil {
return err
}
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
return err
}
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true}); err != nil {
return err
if withOrg {
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
return err
}
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true}); err != nil {
return err
}
}
// Whoever sets up a self-hosted installation operates it.
if s.cfg.Signup == config.SignupFirstUser && s.cfg.Edition == config.EditionSelfHosted {
@@ -85,7 +104,7 @@ func (s *Server) signup(c *gin.Context) {
return nil
})
switch {
case isUniqueViolation(err, "users_email_key"):
case isUniqueViolation(err, "users_email_key"), isUniqueViolation(err, "users_email_key_idx"):
fail(c, http.StatusConflict, "email_taken")
return
case isUniqueViolation(err, "orgs_slug_key"):
@@ -98,10 +117,27 @@ func (s *Server) signup(c *gin.Context) {
internalError(c, err)
return
}
s.countSignup(c)
if verify {
auditActor(c, user.ID)
if err := s.sendVerification(ctx, user); err != nil {
s.log.ErrorContext(ctx, "sending verification failed", "error", err)
fail(c, http.StatusBadGateway, "verification_mail_failed")
return
}
c.JSON(http.StatusOK, gin.H{"status": "verification_sent", "redirect": "/signup/sent"})
return
}
if !withOrg {
orgID = uuid.Nil
}
s.startSession(c, auth.NewSession{UserID: user.ID, OrgID: orgID, Locale: i18n.Lang(ctx), Method: auth.MethodPassword})
}
func (s *Server) signupAllowed(ctx context.Context) (bool, error) {
if s.signupClosedWithoutMail() {
return false, nil
}
switch s.cfg.Signup {
case config.SignupOpen:
return true, nil
@@ -159,11 +195,16 @@ func (s *Server) login(c *gin.Context) {
invalidCredentials(c)
return
}
// Only someone who knows the password learns of the suspension.
// Only someone who knows the password learns of the suspension or a
// missing confirmation.
if user.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
if user.EmailVerifiedAt == nil {
fail(c, http.StatusForbidden, "email_unverified")
return
}
if rehash {
s.rehashPassword(ctx, user.ID, req.Password)
}
+1 -1
View File
@@ -35,7 +35,7 @@ func latestOf(b *browser, id string) (bool, string, bool) {
func TestCheckerNetwork(t *testing.T) {
// In the cloud edition, platform checkers stay off private networks
// unless an admin allows it.
cloud := newEnvWith(t, func(c *config.API) { c.Edition = config.EditionCloud })
cloud := newEnvWith(t, func(c *config.API) { c.Edition, c.SignupVerify = config.EditionCloud, "off" })
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
+5
View File
@@ -63,6 +63,11 @@ func (s *Server) dashboard(c *gin.Context) {
internalError(c, err)
return
}
if len(me.Orgs) == 0 {
// New accounts start by creating an organization.
c.Redirect(http.StatusSeeOther, "/orgs/new")
return
}
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
if p != nil && me.Policy == "" {
data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range")))
+7 -3
View File
@@ -47,7 +47,7 @@ func (s *Server) RunHousekeeping(ctx context.Context) {
// tokens and incidents older than the daily aggregate.
func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
keep := s.cfg.Retention
var counts [6]int64
var counts [7]int64
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if keep.Housekeeping > 0 {
@@ -75,15 +75,19 @@ func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
if _, err = q.PurgeAlertmanagerAlerts(ctx, now.Add(-keepAlerts)); err != nil {
return err
}
if counts[6], err = q.PurgeUnverifiedUsers(ctx, now.Add(-unverifiedKeep)); err != nil {
return err
}
if keep.Daily > 0 {
before := now.Add(-keep.Daily)
counts[3], err = q.PurgeIncidents(ctx, &before)
}
return err
})
if err == nil && counts != [6]int64{} {
if err == nil && counts != [7]int64{} {
s.log.InfoContext(ctx, "housekeeping purged rows",
"notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3], "audit_events", counts[4], "evidence", counts[5])
"notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3], "audit_events", counts[4], "evidence", counts[5],
"unverified_accounts", counts[6])
}
return err
}
+4 -1
View File
@@ -279,13 +279,16 @@ func (s *Server) inviteSignup(c *gin.Context) {
}
var user store.User
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
// The organization invited this address, which stands in for
// confirming it.
user, err = q.CreateUser(ctx, store.CreateUserParams{
Email: inv.Email, DisplayName: strings.TrimSpace(req.DisplayName),
PasswordHash: &hash, Locale: ptr(i18n.Lang(ctx)),
EmailKey: ptr(emailKey(inv.Email)), EmailVerifiedAt: ptr(time.Now()),
})
return err
})
if isUniqueViolation(err, "users_email_key") {
if isUniqueViolation(err, "users_email_key") || isUniqueViolation(err, "users_email_key_idx") {
fail(c, http.StatusConflict, "email_taken")
return
}
+34
View File
@@ -27,6 +27,10 @@ import (
func (s *Server) registerPages(r gin.IRouter) {
r.GET("/login", s.loginPage)
r.GET("/signup", s.signupPage)
r.GET("/signup/sent", s.signupSentPage)
r.GET("/verify", s.verifyPage)
r.GET("/verify/resend", s.resendPage)
r.GET("/orgs/new", s.newOrgPage)
r.GET("/invite/:token", s.invitePage)
s.registerConsole(r)
r.GET("/settings/security", s.securityPage)
@@ -105,6 +109,36 @@ func (s *Server) signupPage(c *gin.Context) {
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title")))
}
func (s *Server) signupSentPage(c *gin.Context) {
web.Render(c, http.StatusOK, web.SignupSent(s.pageFor(c, "auth.verify.sent_title")))
}
// verifyPage confirms an address only when the visitor presses the
// button: mail scanners that open links must not sign in.
func (s *Server) verifyPage(c *gin.Context) {
web.Render(c, http.StatusOK, web.Verify(s.pageFor(c, "auth.verify.title"), c.Query("token")))
}
func (s *Server) resendPage(c *gin.Context) {
web.Render(c, http.StatusOK, web.ResendVerification(s.pageFor(c, "auth.verify.resend_title")))
}
// newOrgPage lets a signed-in account create an organization: the first
// one after signing up, or another.
func (s *Server) newOrgPage(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login?next=/orgs/new")
return
}
me, _, err := s.consoleMe(c, sess)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.NewOrgPage(s.pageFor(c, "orgs.new_title"), me))
}
// consoleMe loads the signed-in user and, if an organization is active,
// their permissions and policy state there. The principal is nil when the
// user has no active organization or is no longer a member.
+19
View File
@@ -73,3 +73,22 @@ func TestPageSlice(t *testing.T) {
t.Errorf("first %v, second %v, back %v", first, second, back)
}
}
func TestEmailKey(t *testing.T) {
for in, want := range map[string]string{
"Max.Power+uptime@googlemail.com": "maxpower@gmail.com",
"max.power@gmail.com": "maxpower@gmail.com",
"a.b+c@example.com": "a.b@example.com",
"A.B@Example.com": "a.b@example.com",
} {
if got := emailKey(in); got != want {
t.Errorf("emailKey(%q) = %q, want %q", in, got, want)
}
}
if clientKey("2001:db8:1:2:aaaa::1") != clientKey("2001:db8:1:2:bbbb::9") || clientKey("2001:db8:1:3::1") == clientKey("2001:db8:1:2::1") {
t.Error("IPv6 clients are not grouped by /64")
}
if clientKey("203.0.113.7") != "203.0.113.7" {
t.Error("IPv4 clients are grouped")
}
}
+3
View File
@@ -108,6 +108,9 @@ func (s *Server) Mount(r gin.IRouter) {
a := v1.Group("/auth")
a.POST("/signup", s.signup)
a.POST("/verify", s.verifyEmail)
a.POST("/verify/resend", s.resendVerification)
v1.POST("/orgs", auth.Require(), s.createOrg)
a.POST("/login", s.login)
a.POST("/login/totp", s.loginTOTP)
a.POST("/logout", s.logout)
+270
View File
@@ -0,0 +1,270 @@
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// New accounts confirm their email address before signing in, through a
// link mailed to them. One mailbox holds one account, aliases included,
// and a client address may create only a few accounts a day.
const (
verifyTTL = 24 * time.Hour
// unverifiedKeep is how long an account waits for confirmation.
unverifiedKeep = 7 * 24 * time.Hour
)
// emailKey identifies the mailbox behind an address: +suffixes are dropped
// everywhere, and Gmail ignores dots and treats googlemail.com as gmail.com.
// The migration adding users.email_key computes the same.
func emailKey(email string) string {
local, domain, ok := strings.Cut(strings.ToLower(strings.TrimSpace(email)), "@")
if !ok {
return strings.ToLower(email)
}
local, _, _ = strings.Cut(local, "+")
if domain == "gmail.com" || domain == "googlemail.com" {
local, domain = strings.ReplaceAll(local, ".", ""), "gmail.com"
}
return local + "@" + domain
}
// clientKey groups client addresses for sign-up limits: IPv6 clients
// usually hold a whole /64.
func clientKey(ip string) string {
a := net.ParseIP(ip)
if a == nil || a.To4() != nil {
return ip
}
return a.Mask(net.CIDRMask(64, 128)).String() + "/64"
}
// verificationRequired reports whether new accounts confirm their email.
func (s *Server) verificationRequired() bool {
switch s.cfg.SignupVerify {
case "required":
return true
case "off":
return false
}
return s.cloud() || s.smtp != nil
}
// signupsLeft reports whether the client may create another account.
func (s *Server) signupsLeft(c *gin.Context) (bool, error) {
if s.cfg.SignupsPerIP == 0 {
return true, nil
}
n, err := s.rdb.Get(c.Request.Context(), "signups:"+clientKey(c.ClientIP())).Int()
if errors.Is(err, redis.Nil) {
return true, nil
}
return n < s.cfg.SignupsPerIP, err
}
// countSignup counts a created account against the client's daily limit.
func (s *Server) countSignup(c *gin.Context) {
if s.cfg.SignupsPerIP == 0 {
return
}
ctx := c.Request.Context()
key := "signups:" + clientKey(c.ClientIP())
pipe := s.rdb.TxPipeline()
pipe.Incr(ctx, key)
pipe.ExpireNX(ctx, key, 24*time.Hour)
if _, err := pipe.Exec(ctx); err != nil {
s.log.WarnContext(ctx, "counting sign-up failed", "error", err)
}
}
func verifyKey(token string) string {
sum := sha256.Sum256([]byte(token))
return "verify:" + hex.EncodeToString(sum[:])
}
// sendVerification mails u a link that confirms their address.
func (s *Server) sendVerification(ctx context.Context, u store.User) error {
if s.smtp == nil {
return errors.New("api: no mail server to send verification")
}
token := auth.RandomToken()
if err := s.rdb.Set(ctx, verifyKey(token), u.ID.String(), verifyTTL).Err(); err != nil {
return err
}
l := s.catalog.Match(deref(u.Locale))
link := strings.TrimSuffix(s.cfg.PublicURL, "/") + "/verify?token=" + url.QueryEscape(token)
data := map[string]any{"Link": link, "Hours": int(verifyTTL.Hours())}
return s.smtp.Send(ctx, notify.Mail{
To: []string{u.Email}, Subject: l.T("email.verify.subject", data), Body: l.T("email.verify.body", data),
})
}
type verifyRequest struct {
Token string `json:"token" binding:"required,max=200"`
}
// verifyEmail confirms the address the token was mailed to and signs the
// account in: whoever holds the link controls the mailbox.
func (s *Server) verifyEmail(c *gin.Context) {
var req verifyRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
if !s.limit(c, "verify:ip:"+c.ClientIP(), 30, 15*time.Minute) {
return
}
raw, err := s.rdb.GetDel(ctx, verifyKey(req.Token)).Result()
id, perr := uuid.Parse(raw)
if errors.Is(err, redis.Nil) || perr != nil {
fail(c, http.StatusGone, "verification_expired")
return
}
if err != nil {
internalError(c, err)
return
}
var u store.User
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
u, err = q.MarkEmailVerified(ctx, id)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusGone, "verification_expired")
return
}
if err != nil {
internalError(c, err)
return
}
auditActor(c, u.ID)
if u.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
s.finishLogin(c, u.ID, auth.MethodPassword)
}
type resendRequest struct {
Email string `json:"email" binding:"required,email,max=320"`
}
// resendVerification mails a new link to an unconfirmed account. It
// answers the same whether or not such an account exists.
func (s *Server) resendVerification(c *gin.Context) {
var req resendRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
email := normalizeEmail(req.Email)
if !s.limit(c, "resend:ip:"+c.ClientIP(), 10, time.Hour) || !s.limit(c, "resend:email:"+email, 3, time.Hour) {
return
}
var u store.User
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
u, err = q.GetUserByEmail(ctx, email)
return err
})
switch {
case errors.Is(err, pgx.ErrNoRows):
case err != nil:
internalError(c, err)
return
case u.EmailVerifiedAt == nil && u.DisabledAt == nil:
if err := s.sendVerification(ctx, u); err != nil {
s.log.ErrorContext(ctx, "sending verification failed", "error", err)
}
}
c.Status(http.StatusNoContent)
}
type createOrgRequest struct {
Name string `json:"name" binding:"required,max=200"`
Slug string `json:"slug" binding:"required,max=63"`
}
// createOrg creates an organization owned by the signed-in account and
// makes it the active one.
func (s *Server) createOrg(c *gin.Context) {
var req createOrgRequest
if !bind(c, &req) {
return
}
sess := auth.Current(c)
ctx := c.Request.Context()
u, err := s.loadUser(ctx, sess.UserID)
if err != nil {
internalError(c, err)
return
}
max := s.platformLimits(ctx).OrgsPerAccount
if u.LimitOrgs != nil {
max = int(*u.LimitOrgs)
}
orgID := uuid.New()
err = s.db.Tx(ctx, tenant.Org(orgID, sess.UserID), func(q *store.Queries) error {
if max > 0 {
// Serialize the account's creations to count them reliably.
if err := q.LockOrgUsage(ctx, u.ID); err != nil {
return err
}
n, err := q.CountOwnedOrgs(ctx, u.ID)
if err != nil {
return err
}
if n >= int64(max) {
return limitError{"org_limit", max}
}
}
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(strings.TrimSpace(req.Slug)), Name: strings.TrimSpace(req.Name)}); err != nil {
return err
}
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: u.ID, IsOwner: true})
})
switch {
case failLimit(c, err):
return
case isUniqueViolation(err, "orgs_slug_key"):
fail(c, http.StatusConflict, "slug_taken")
return
case isCheckViolation(err):
fail(c, http.StatusUnprocessableEntity, "invalid_slug")
return
case err != nil:
internalError(c, err)
return
}
auditOrg(c, orgID)
if err := s.sessions.SwitchOrg(ctx, sess, orgID); err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, gin.H{"id": orgID, "slug": strings.ToLower(strings.TrimSpace(req.Slug)), "redirect": "/"})
}
// signupClosedWithoutMail tells whether sign-up must wait for a mail
// server: accounts need confirming but no link could be sent.
func (s *Server) signupClosedWithoutMail() bool {
return s.verificationRequired() && s.smtp == nil
}
+138
View File
@@ -0,0 +1,138 @@
package api_test
import (
"context"
"net/http"
"regexp"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
)
var verifyLink = regexp.MustCompile(`/verify\?token=([A-Za-z0-9_\-]+)`)
func TestVerifiedSignup(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) {
c.SMTPURL, c.SignupVerify, c.SignupsPerIP = mail.URL(), "auto", 2
})
// mailFor waits for the n-th mail and returns its confirmation token.
tokenOf := func(n int, to string) string {
t.Helper()
waitFor(t, 5*time.Second, "the confirmation mail", func() bool { return len(mail.Messages()) >= n })
msg := mail.Messages()[n-1]
if !strings.Contains(strings.Join(msg.To, ","), to) {
t.Fatalf("mail %d went to %v, want %s", n, msg.To, to)
}
m := verifyLink.FindStringSubmatch(msg.Data)
if m == nil {
t.Fatalf("mail lacks the link: %s", msg.Data)
}
return m[1]
}
box := uniq("max.power")
email := strings.ToUpper(box[:1]) + box[1:] + "+uptime@googlemail.com"
lower := strings.ToLower(email)
// Signing up mails a link instead of signing in.
b := e.browser(t)
st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{"email": email, "password": testPassword, "display_name": "Max"})
if st != http.StatusOK || body["status"] != "verification_sent" {
t.Fatalf("signup = %d %v", st, body)
}
if st, _ := b.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
t.Errorf("signed in before confirming: %d", st)
}
token := tokenOf(1, lower)
// Unconfirmed accounts cannot sign in; only the right password says why.
st, body = e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": testPassword})
expect(t, "sign-in before confirming", st, body, http.StatusForbidden, "email_unverified")
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": "wrong password"}); st != http.StatusUnauthorized {
t.Error("a wrong password reveals the missing confirmation")
}
// The same mailbox under another address is refused.
st, body = e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": strings.ReplaceAll(box, ".", "") + "@gmail.com", "password": testPassword})
expect(t, "alias of an existing account", st, body, http.StatusConflict, "email_taken")
// Resending answers alike for unknown addresses and mails only real ones.
if st, _ := e.browser(t).do("POST", "/api/v1/auth/verify/resend", map[string]any{"email": "nobody@" + uniq("x") + ".test"}); st != http.StatusNoContent {
t.Errorf("resend for unknown = %d", st)
}
if st, _ := e.browser(t).do("POST", "/api/v1/auth/verify/resend", map[string]any{"email": email}); st != http.StatusNoContent {
t.Errorf("resend = %d", st)
}
tokenOf(2, lower)
if n := len(mail.Messages()); n != 2 {
t.Errorf("%d mails, want 2", n)
}
// The link page asks before confirming; confirming signs in once.
if _, _, html := b.page("/verify?token=" + token); !strings.Contains(html, `name="token"`) {
t.Error("the link page lacks its form")
}
if st, body := b.do("POST", "/api/v1/auth/verify", map[string]any{"token": token}); st != http.StatusOK {
t.Fatalf("verify = %d %v", st, body)
}
st, body = e.browser(t).do("POST", "/api/v1/auth/verify", map[string]any{"token": token})
expect(t, "token used twice", st, body, http.StatusGone, "verification_expired")
// Without an organization, the console asks for one.
if got := b.visit("/"); got.Path != "/orgs/new" {
t.Errorf("dashboard leads to %s, want /orgs/new", got.Path)
}
slug := uniq("max-")
if st, body := b.do("POST", "/api/v1/orgs", map[string]any{"name": "Max Corp", "slug": slug}); st != http.StatusCreated {
t.Fatalf("create org = %d %v", st, body)
}
if got := b.visit("/"); got.Path != "/" {
t.Errorf("dashboard leads to %s after creating an organization", got.Path)
}
_, me := b.do("GET", "/api/v1/me", nil)
if !strings.Contains(mustJSON(me), slug) {
t.Errorf("me lacks the new organization: %v", me)
}
// The account limit on organizations.
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(context.Background(), `UPDATE users SET limit_orgs = 1 WHERE email = $1`, lower)
return err
})
st, body = b.do("POST", "/api/v1/orgs", map[string]any{"name": "Second", "slug": uniq("max2-")})
expect(t, "second organization", st, body, http.StatusUnprocessableEntity, "org_limit")
// Two accounts per client address and day; refused sign-ups do not count.
if st, body := e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": "two@" + uniq("x") + ".test", "password": testPassword}); st != http.StatusOK {
t.Fatalf("second account = %d %v", st, body)
}
st, body = e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": "three@" + uniq("x") + ".test", "password": testPassword})
expect(t, "third account", st, body, http.StatusTooManyRequests, "signup_limit")
// Unconfirmed accounts go after a week.
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(context.Background(), `UPDATE users SET created_at = now() - interval '8 days' WHERE email_verified_at IS NULL AND email LIKE 'two@%'`)
return err
})
if err := e.api.Housekeep(context.Background(), time.Now()); err != nil {
t.Fatal(err)
}
var left int
_ = e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(context.Background(), `SELECT count(*) FROM users WHERE email LIKE 'two@%' AND created_at < now() - interval '7 days'`).Scan(&left)
})
if left != 0 {
t.Error("an unconfirmed account outlived its week")
}
}
func TestSignupNeedsMail(t *testing.T) {
e := newEnvWith(t, func(c *config.API) { c.SignupVerify = "required" })
st, body := e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": "a@" + uniq("x") + ".test", "password": testPassword})
expect(t, "sign-up without a mail server", st, body, http.StatusForbidden, "signup_closed")
}
+7
View File
@@ -319,10 +319,17 @@ func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl s
} else if !errors.Is(err, pgx.ErrNoRows) {
return err
}
// Another address of the same mailbox has an account.
if taken, err := q.EmailKeyTaken(ctx, ptr(emailKey(email))); err != nil || taken {
code = "sso_link_required"
return err
}
// The identity provider confirmed the address.
u, err := q.CreateUser(ctx, store.CreateUserParams{
Email: email,
DisplayName: truncate(strings.TrimSpace(cl.Name), 200),
Locale: ptr(i18n.Lang(ctx)),
EmailKey: ptr(emailKey(email)), EmailVerifiedAt: ptr(time.Now()),
})
if err != nil {
return err