Fix auth throttle DoS and serialize admin bootstrap.

Evict/cap limiter keys, replace hard username lockouts with IP+user progressive delays cleared on success, and create bootstrap admins under the same advisory/mutex lock as role changes.
This commit is contained in:
2026-08-22 11:54:10 -07:00
parent 59513ab75e
commit 5bdaa8977f
7 changed files with 413 additions and 39 deletions
+9 -15
View File
@@ -71,7 +71,9 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
username := strings.TrimSpace(r.PostFormValue("username"))
password := r.PostFormValue("password")
next := safeNext(r.PostFormValue("next"))
if !s.allowLoginAttempt(w, r, store.NormalizeUsername(username)) {
userKey := store.NormalizeUsername(username)
ip := s.clientIP(r)
if !s.allowLoginAttempt(w, r, userKey) {
return
}
@@ -81,6 +83,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
hash = []byte(u.PasswordHash)
}
if err != nil || bcrypt.CompareHashAndPassword(hash, []byte(password)) != nil {
s.loginFail.record(loginFailKey(ip, userKey))
w.WriteHeader(http.StatusUnauthorized)
s.exec(w, "login", authPage{
page: s.basePage(r, "Sign in"),
@@ -90,6 +93,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
})
return
}
s.loginFail.clear(loginFailKey(ip, userKey))
if err := s.sessions.RenewToken(r.Context()); err != nil {
http.Error(w, "could not start session", http.StatusInternalServerError)
return
@@ -133,8 +137,8 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
return
}
role := store.RoleUser
if s.consumeAdminSetup(r, setupSecret) {
role = store.RoleAdmin
if setupSecretMatches(s.cfg.AdminSetupSecret, setupSecret) {
role = store.RoleAdmin // store downgrades if an admin already exists
}
u := &store.User{
Username: username,
@@ -154,21 +158,11 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusSeeOther)
}
// consumeAdminSetup grants first-admin when a strong one-time setup secret matches
// and no admin exists yet. Username alone is never enough.
func (s *Server) consumeAdminSetup(r *http.Request, provided string) bool {
want := s.cfg.AdminSetupSecret
func setupSecretMatches(want, provided string) bool {
if want == "" || provided == "" {
return false
}
if subtle.ConstantTimeCompare([]byte(provided), []byte(want)) != 1 {
return false
}
n, err := s.store.CountAdmins(r.Context())
if err != nil || n > 0 {
return false
}
return true
return subtle.ConstantTimeCompare([]byte(provided), []byte(want)) == 1
}
func (s *Server) handleAuthPrompt(w http.ResponseWriter, r *http.Request) {