// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "database/sql" "errors" "testing" "time" ) func TestLoginRechecksTheAccountInTheSessionTransaction(t *testing.T) { h := newWebHarness(t) alice := h.user("alice", roleUser) bob := h.user("bob", roleUser) resetHash := fakeHash("admin-reset-password") for _, c := range []struct { user userRow mutate func(u *userRow) }{ {alice, func(u *userRow) { u.PasswordHash = resetHash }}, {bob, func(u *userRow) { u.DeletedAt = sql.NullTime{Time: webNow, Valid: true} }}, } { h.store.onTx = func(st *fakeWebState) { c.mutate(&st.users[c.user.ID-1]) } res := h.postLogin(loginForm(c.user.Username, testPassword, ""), "") if res.status != 401 || len(res.header.Values("Set-Cookie")) != 0 || h.store.sessionCount(c.user.ID) != 0 { t.Fatalf("%s: %d %v", c.user.Username, res.status, res.header) } e := expectOneAudit(t, res, opLogin, 401) if res.audit[0].inTx || e.UserID.Int64 != c.user.ID || e.Error.String != msgInvalidLogin { t.Fatalf("%s: %+v", c.user.Username, res.audit[0]) } if h.store.user(c.user.ID).LastLoginAt.Valid { t.Fatalf("%s: last login touched", c.user.Username) } } if h.store.user(alice.ID).PasswordHash != resetHash || !h.store.user(bob.ID).DeletedAt.Valid { t.Fatal("the concurrent change was lost") } admin := h.user("admin", roleAdmin) carol := h.user("carol", roleUser) dave := h.user("dave", roleUser) at := h.login(admin) for _, c := range []struct { user userRow method, path string body string wantHash string wantDeletedAt bool }{ {carol, "PUT", "/users/carol/password", `{"password":"admin-reset-password"}`, resetHash, false}, {dave, "DELETE", "/users/dave", `{"confirm":"dave"}`, fakeHash(testPassword), true}, } { res := h.postLogin(loginForm(c.user.Username, testPassword, ""), "") if res.status != 303 { t.Fatalf("%s: login %d", c.user.Username, res.status) } session := responseCookie(t, res).Value if r := h.api(c.method, c.path, at, c.body); r.status != 204 { t.Fatalf("%s: %d %s", c.path, r.status, r.body) } if h.api("GET", "/account", session, "").status != 401 || h.store.sessionCount(c.user.ID) != 0 { t.Fatalf("%s: the session of the committed login survived", c.user.Username) } u := h.store.user(c.user.ID) if u.PasswordHash != c.wantHash || u.DeletedAt.Valid != c.wantDeletedAt { t.Fatalf("%s: %+v", c.user.Username, u) } } } func TestOwnPasswordChangeRechecksTheStoredHash(t *testing.T) { h := newWebHarness(t) admin := h.user("admin", roleAdmin) alice := h.user("alice", roleUser) at := h.login(admin) aliceSession := h.login(alice) h.login(alice) resetHash := fakeHash("admin-reset-password") h.store.onTx = func(st *fakeWebState) { st.users[alice.ID-1].PasswordHash = resetHash for k, s := range st.sessions { if s.UserID == alice.ID { delete(st.sessions, k) } } } res := h.api("PUT", "/account/password", aliceSession, `{"current":"secret-password","password":"own-new-password"}`) expectError(t, res, 409, `{"error":"the password was changed by another request"}`) if e := expectNoChange(t, res, opPasswordChange, 409); e.TargetUserID.Int64 != alice.ID { t.Fatalf("%+v", e) } if h.store.user(alice.ID).PasswordHash != resetHash || h.store.sessionCount(alice.ID) != 0 { t.Fatal("own change overwrote the admin reset") } bob := h.user("bob", roleUser) own, other := h.login(bob), h.login(bob) res = h.api("PUT", "/account/password", own, `{"current":"secret-password","password":"own-new-password"}`) if res.status != 204 || h.store.user(bob.ID).PasswordHash != fakeHash("own-new-password") { t.Fatalf("%d %s", res.status, res.body) } if h.api("GET", "/account", other, "").status != 401 || h.api("GET", "/account", own, "").status != 200 { t.Fatal("own change sessions") } if r := h.api("PUT", "/users/bob/password", at, `{"password":"admin-reset-password"}`); r.status != 204 { t.Fatal(r.status) } if h.store.user(bob.ID).PasswordHash != resetHash || h.store.sessionCount(bob.ID) != 0 { t.Fatal("admin reset after the own change") } carol := h.user("carol", roleUser) carolSession := h.login(carol) h.store.onTx = func(st *fakeWebState) { st.users[carol.ID-1].DeletedAt = sql.NullTime{Time: webNow, Valid: true} for k, session := range st.sessions { if session.UserID == carol.ID { delete(st.sessions, k) } } } res = h.api("PUT", "/account/password", carolSession, `{"current":"secret-password","password":"own-new-password"}`) if e := expectNoChange(t, res, opPasswordChange, 401); e.Error.String != msgAuthRequired || e.TargetUserID.Int64 != carol.ID { t.Fatalf("unexpected deletion race audit: %+v", e) } if h.store.user(carol.ID).PasswordHash != fakeHash(testPassword) || h.store.sessionCount(carol.ID) != 0 { t.Fatal("password change survived a concurrent deletion") } } func TestAdminChangesRecheckTheActingAdmin(t *testing.T) { mutations := map[string]func(st *fakeWebState){ "demoted": func(st *fakeWebState) { st.users[0].Role = roleUser }, "deleted": func(st *fakeWebState) { st.users[0].DeletedAt = sql.NullTime{Time: webNow, Valid: true} }, } requests := []struct{ method, path, body, op string }{ {"PUT", "/zones/other.org./users/bob", "", opDelegationGrant}, {"DELETE", "/zones/example.org./users/bob", "", opDelegationRevoke}, {"POST", "/users", `{"username":"newbie","role":"user","password":"long-enough-pw"}`, opUserCreate}, {"PUT", "/users/bob/role", `{"role":"admin"}`, opUserRole}, {"PUT", "/users/bob/password", `{"password":"reset-password-1"}`, opUserPassword}, {"DELETE", "/users/bob", `{"confirm":"bob"}`, opUserDelete}, } for name, mutate := range mutations { for _, r := range requests { h, token := usersHarness(t) h.store.addZone(otherZone) bob := h.store.user(h.users["bob"].ID) h.store.onLock = mutate res := h.api(r.method, r.path, token, r.body) expectError(t, res, 403, `{"error":"admin role required"}`) expectNoChange(t, res, r.op, 403) if h.store.user(bob.ID) != bob || !h.store.hasDelegation(testZone, bob.ID) || h.store.hasDelegation(otherZone, bob.ID) { t.Fatalf("%s %s: change kept", name, r.op) } if _, err := h.store.UserByUsername(t.Context(), "newbie"); !errors.Is(err, errRowNotFound) { t.Fatalf("%s %s: user created", name, r.op) } if h.store.called("LockActiveAdmins") != 1 { t.Fatalf("%s %s: actor not locked", name, r.op) } } } h, token := usersHarness(t) h.store.addZone(otherZone) for _, r := range requests[:2] { if res := h.api(r.method, r.path, token, r.body); res.status != 204 { t.Fatalf("%s: %d %s", r.op, res.status, res.body) } } admin := h.stored("admin") admin.Role = roleUser admin.UpdatedAt = webNow.Add(time.Minute) h.store.setUser(admin) if !h.store.hasDelegation(otherZone, h.users["bob"].ID) || h.store.hasDelegation(testZone, h.users["bob"].ID) { t.Fatal("changes committed before the demotion did not survive") } }