Add endpoint tests with httptest
Two small refactors make the handlers testable: - extract route registration into routes() http.Handler (was inline in main) - initDB(dsn) takes a DSN so tests use an isolated temp-file DB loginJitter var lets tests disable the anti-timing sleep for speed. endpoints_test.go covers the main flows via httptest + cookie jar: register/login/headerbar, empty-then-populated feed, create requires auth, voting (new/toggle/switch, per-user tallies), vote auth + invalid mode, and account deletion (wrong/correct password, login fails after). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -27,6 +27,10 @@ var (
|
||||
reSpace = regexp.MustCompile(`\s+`)
|
||||
)
|
||||
|
||||
// loginJitter ist die Obergrenze (in ms) der zufälligen Login-Verzögerung gegen
|
||||
// Timing-Angriffe. Tests setzen den Wert auf 0, um die Verzögerung abzuschalten.
|
||||
var loginJitter = 2000
|
||||
|
||||
// getSession liest den session-Cookie und liefert die zugehörige, noch gültige Session.
|
||||
func getSession(r *http.Request) (*Session, bool) {
|
||||
c, err := r.Cookie("session")
|
||||
@@ -68,7 +72,9 @@ func handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
err := db.QueryRow(`SELECT uid, password FROM user WHERE username = ?`, username).Scan(&uid, &hash)
|
||||
|
||||
// Gegen Timing-Angriffe: immer eine kleine, zufällige Verzögerung.
|
||||
time.Sleep(time.Duration(rand.IntN(2000)) * time.Millisecond)
|
||||
if loginJitter > 0 {
|
||||
time.Sleep(time.Duration(rand.IntN(loginJitter)) * time.Millisecond)
|
||||
}
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
writeError(w, http.StatusUnauthorized, "Nutzername oder Passwort ist falsch.")
|
||||
|
||||
Reference in New Issue
Block a user