fix: login refuses a not-activated account while require_activation is on

The refusal is the same 401 invalid-login answer as a wrong password and is counted by the login throttle.
The activation is checked after the password and before the deactivation restore, so a refused account stays deactivated.
require_activation false keeps the previous behaviour.
This commit is contained in:
Jakub Zych
2026-10-22 21:25:53 +02:00
parent 930b1587a0
commit 15ff9793ba
6 changed files with 287 additions and 23 deletions

View File

@@ -57,7 +57,7 @@ func TestLogin(t *testing.T) {
if err != nil {
t.Fatal(err)
}
user := &models.User{Email: "ada-login@example.test", Password: hash}
user := &models.User{Email: "ada-login@example.test", Password: hash, IsActivated: true}
if err := gdb.Create(user).Error; err != nil {
t.Fatal(err)
}
@@ -116,7 +116,7 @@ func TestLogin(t *testing.T) {
now := time.Now()
ip := "192.0.2.1"
throttled := &models.User{Email: "throttled@example.test", Password: hash}
throttled := &models.User{Email: "throttled@example.test", Password: hash, IsActivated: true}
if err := gdb.Create(throttled).Error; err != nil {
t.Fatal(err)
}
@@ -130,7 +130,7 @@ func TestLogin(t *testing.T) {
}
loc := "en"
soft := &models.User{Email: "soft@example.test", Password: hash, PreferredLocale: &loc}
soft := &models.User{Email: "soft@example.test", Password: hash, IsActivated: true, PreferredLocale: &loc}
if err := gdb.Create(soft).Error; err != nil {
t.Fatal(err)
}
@@ -163,7 +163,7 @@ func TestLoginSixthAttempt(t *testing.T) {
if err != nil {
t.Fatal(err)
}
user := &models.User{Email: "sixth@example.test", Password: hash}
user := &models.User{Email: "sixth@example.test", Password: hash, IsActivated: true}
if err := gdb.Create(user).Error; err != nil {
t.Fatal(err)
}
@@ -192,6 +192,201 @@ func TestLoginSixthAttempt(t *testing.T) {
}
}
// TestLoginRequiresActivation pins the activation gate of POST /login:
// with golem15.user.activation.require_activation on (the default) the
// correct password of a not-activated account gets the same 401
// invalid-login answer as a wrong password and counts as a failed attempt,
// and an account that is also deactivated stays deactivated. With the key
// off, and for activated accounts, login and the deactivation restore work
// as before.
func TestLoginRequiresActivation(t *testing.T) {
hash, err := bouncer.HashPassword(10, "correct-horse")
if err != nil {
t.Fatal(err)
}
newApp := func(t *testing.T, require *bool) (*backpack.App, *gorm.DB) {
t.Helper()
app, gdb := sessionApp(t, "0s")
if require != nil {
if err := app.Config.Set("golem15.user.activation.require_activation", *require); err != nil {
t.Fatal(err)
}
}
return app, gdb
}
on, off := true, false
create := func(t *testing.T, gdb *gorm.DB, email string, activated, deleted bool) *models.User {
t.Helper()
loc := "en"
user := &models.User{Email: email, Password: hash, IsActivated: activated, PreferredLocale: &loc}
if err := gdb.Create(user).Error; err != nil {
t.Fatal(err)
}
if deleted {
if err := gdb.Model(user).Update("deleted_at", time.Now()).Error; err != nil {
t.Fatal(err)
}
}
return user
}
login := func(app *backpack.App, email, password string) *httptest.ResponseRecorder {
return postJSON(t, controllers.Login(app), "/_user/api/v1/login", `{"email":"`+email+`","password":"`+password+`"}`)
}
reload := func(t *testing.T, gdb *gorm.DB, id uint) models.User {
t.Helper()
var u models.User
if err := gdb.Unscoped().First(&u, id).Error; err != nil {
t.Fatal(err)
}
return u
}
attempts := func(t *testing.T, gdb *gorm.DB, id uint) models.Throttle {
t.Helper()
var row models.Throttle
if err := gdb.Where("user_id = ?", id).Take(&row).Error; err != nil {
t.Fatal(err)
}
return row
}
refused := func(t *testing.T, rec *httptest.ResponseRecorder) {
t.Helper()
if rec.Code != http.StatusUnauthorized || rec.Body.String() != invalidLoginBody {
t.Fatalf("want the invalid-login 401, got %d %s", rec.Code, rec.Body.String())
}
}
signedIn := func(t *testing.T, rec *httptest.ResponseRecorder, user *models.User) {
t.Helper()
if rec.Code != http.StatusOK {
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
token, _ := body["token"].(string)
if token == "" {
t.Fatalf("no token in %s", rec.Body.String())
}
if sub := parseToken(t, token)["sub"]; sub != strconv.FormatUint(uint64(user.ID), 10) {
t.Fatalf("sub = %v", sub)
}
}
mailer := func(t *testing.T, app *backpack.App) *captureMail {
t.Helper()
mail := &captureMail{}
if err := app.Publish[postcard.Mailer](mail); err != nil {
t.Fatal(err)
}
return mail
}
t.Run("default_refuses", func(t *testing.T) {
app, gdb := newApp(t, nil)
user := create(t, gdb, "act-default@example.test", false, false)
rec := login(app, user.Email, "correct-horse")
refused(t, rec)
if strings.Contains(rec.Body.String(), "token") {
t.Fatalf("refusal carries a token: %s", rec.Body.String())
}
if got := reload(t, gdb, user.ID); got.LastSeen != nil {
t.Fatalf("refusal stamped last_seen %v", got.LastSeen)
}
if row := attempts(t, gdb, user.ID); row.Attempts != 1 {
t.Fatalf("throttle after refusal: %+v", row)
}
})
t.Run("same_as_wrong_password", func(t *testing.T) {
app, gdb := newApp(t, nil)
user := create(t, gdb, "act-same@example.test", false, false)
right := login(app, user.Email, "correct-horse")
if row := attempts(t, gdb, user.ID); row.Attempts != 1 {
t.Fatalf("throttle after the correct password: %+v", row)
}
wrong := login(app, user.Email, "wrong-horse")
if row := attempts(t, gdb, user.ID); row.Attempts != 2 {
t.Fatalf("throttle after the wrong password: %+v", row)
}
refused(t, right)
if right.Code != wrong.Code || right.Body.String() != wrong.Body.String() {
t.Fatalf("correct %d %s, wrong %d %s", right.Code, right.Body.String(), wrong.Code, wrong.Body.String())
}
for _, h := range []string{"Content-Type", "Cache-Control"} {
if a, b := right.Header().Get(h), wrong.Header().Get(h); a != b || a == "" {
t.Fatalf("%s: correct %q, wrong %q", h, a, b)
}
}
})
t.Run("explicit_true_refuses", func(t *testing.T) {
app, gdb := newApp(t, &on)
user := create(t, gdb, "act-true@example.test", false, false)
refused(t, login(app, user.Email, "correct-horse"))
})
t.Run("refusals_suspend", func(t *testing.T) {
app, gdb := newApp(t, nil)
user := create(t, gdb, "act-suspend@example.test", false, false)
for i := 1; i <= 5; i++ {
refused(t, login(app, user.Email, "correct-horse"))
}
if row := attempts(t, gdb, user.ID); row.Attempts != 5 || !row.IsSuspended {
t.Fatalf("after 5 refusals: %+v", row)
}
})
t.Run("off_allows", func(t *testing.T) {
app, gdb := newApp(t, &off)
user := create(t, gdb, "act-off@example.test", false, false)
signedIn(t, login(app, user.Email, "correct-horse"), user)
})
t.Run("activated_allows", func(t *testing.T) {
app, gdb := newApp(t, nil)
user := create(t, gdb, "act-yes@example.test", true, false)
signedIn(t, login(app, user.Email, "correct-horse"), user)
})
t.Run("deactivated_activated_restores", func(t *testing.T) {
app, gdb := newApp(t, nil)
user := create(t, gdb, "act-restore@example.test", true, true)
mail := mailer(t, app)
signedIn(t, login(app, user.Email, "correct-horse"), user)
if got := reload(t, gdb, user.ID); got.DeletedAt.Valid {
t.Fatal("deactivated activated account was not restored")
}
if len(mail.got) != 1 || mail.got[0] != "golem15.user::mail.reactivate-en" {
t.Fatalf("reactivate template = %#v", mail.got)
}
})
t.Run("deactivated_inactive_refused", func(t *testing.T) {
app, gdb := newApp(t, nil)
user := create(t, gdb, "act-both@example.test", false, true)
mail := mailer(t, app)
refused(t, login(app, user.Email, "correct-horse"))
if got := reload(t, gdb, user.ID); !got.DeletedAt.Valid {
t.Fatal("refused account was restored")
}
if len(mail.got) != 0 {
t.Fatalf("refusal sent mail %#v", mail.got)
}
})
t.Run("deactivated_inactive_off_restores", func(t *testing.T) {
app, gdb := newApp(t, &off)
user := create(t, gdb, "act-both-off@example.test", false, true)
mail := mailer(t, app)
signedIn(t, login(app, user.Email, "correct-horse"), user)
if got := reload(t, gdb, user.ID); got.DeletedAt.Valid {
t.Fatal("account was not restored with require_activation off")
}
if len(mail.got) != 1 || mail.got[0] != "golem15.user::mail.reactivate-en" {
t.Fatalf("reactivate template = %#v", mail.got)
}
})
}
func TestLogout(t *testing.T) {
app, gdb := sessionApp(t, "0s")
token := loginToken(t, app, gdb, "logout@example.test")
@@ -361,6 +556,8 @@ func (c *captureMail) Send(_ context.Context, msg postcard.Message) error {
return nil
}
// loginToken inserts an activated account with the password "correct-horse"
// (insertUser) and signs it in through POST /login, returning the token.
func loginToken(t *testing.T, app *backpack.App, gdb *gorm.DB, email string) string {
t.Helper()
insertUser(t, gdb, email, "correct-horse")
@@ -379,19 +576,49 @@ func loginToken(t *testing.T, app *backpack.App, gdb *gorm.DB, email string) str
return token
}
// insertUser creates an activated account with password, an ordinary
// account that can sign in through POST /login.
func insertUser(t *testing.T, gdb *gorm.DB, email, password string) *models.User {
t.Helper()
return createUser(t, gdb, email, password, true)
}
// insertInactiveUser creates a not-activated account with password. While
// golem15.user.activation.require_activation is on (the default) POST /login
// refuses it.
func insertInactiveUser(t *testing.T, gdb *gorm.DB, email, password string) *models.User {
t.Helper()
return createUser(t, gdb, email, password, false)
}
func createUser(t *testing.T, gdb *gorm.DB, email, password string, activated bool) *models.User {
t.Helper()
hash, err := bouncer.HashPassword(10, password)
if err != nil {
t.Fatal(err)
}
user := &models.User{Email: email, Password: hash}
user := &models.User{Email: email, Password: hash, IsActivated: activated}
if err := gdb.Create(user).Error; err != nil {
t.Fatal(err)
}
return user
}
// inactiveSessionToken inserts a not-activated account (insertInactiveUser)
// and mints its session with controllers.IssueToken, the session such an
// account gets from /register when require_activation is off.
func inactiveSessionToken(t *testing.T, app *backpack.App, gdb *gorm.DB, email string) string {
t.Helper()
user := insertInactiveUser(t, gdb, email, "correct-horse")
req := httptest.NewRequest(http.MethodPost, "/_user/api/v1/login", nil)
req.Host = "example.com"
token, err := controllers.IssueToken(app, user, req)
if err != nil {
t.Fatal(err)
}
return token
}
func postJSON(t *testing.T, h http.HandlerFunc, path, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))