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") }