Files
3x-ui/web/controller/login_limiter_test.go
Farhad H. P. Shirvan 10ebc6cbdc Implement CSRF protection and security hardening across the application (#4179)
* Implement CSRF protection and security hardening across the application

- Added CSRF token handling in axios requests and HTML templates.
- Introduced CSRF middleware to validate tokens for unsafe HTTP methods.
- Implemented login limiter to prevent brute-force attacks.
- Enhanced security headers in middleware for improved response security.
- Updated login notification to include safe metadata without passwords.
- Added tests for CSRF middleware and login limiter functionality.

* fix
2026-05-07 23:36:11 +02:00

75 lines
2.3 KiB
Go

package controller
import (
"testing"
"time"
)
func TestLoginLimiterBlocksAfterConfiguredFailures(t *testing.T) {
now := time.Date(2026, 5, 6, 12, 0, 0, 0, time.UTC)
limiter := newLoginLimiter(5, 5*time.Minute, 15*time.Minute)
limiter.now = func() time.Time { return now }
for i := 0; i < 4; i++ {
if _, blocked := limiter.registerFailure("192.0.2.10", "Admin"); blocked {
t.Fatalf("failure %d should not block yet", i+1)
}
if _, ok := limiter.allow("192.0.2.10", "admin"); !ok {
t.Fatalf("failure %d should still allow login attempts", i+1)
}
}
blockedUntil, blocked := limiter.registerFailure("192.0.2.10", "ADMIN")
if !blocked {
t.Fatal("fifth failure should start cooldown")
}
if want := now.Add(15 * time.Minute); !blockedUntil.Equal(want) {
t.Fatalf("blocked until %s, want %s", blockedUntil, want)
}
if _, ok := limiter.allow("192.0.2.10", "admin"); ok {
t.Fatal("login should be blocked during cooldown")
}
now = blockedUntil
if _, ok := limiter.allow("192.0.2.10", "admin"); !ok {
t.Fatal("login should be allowed after cooldown")
}
}
func TestLoginLimiterPrunesOldFailuresAndResetsOnSuccess(t *testing.T) {
now := time.Date(2026, 5, 6, 12, 0, 0, 0, time.UTC)
limiter := newLoginLimiter(5, 5*time.Minute, 15*time.Minute)
limiter.now = func() time.Time { return now }
for i := 0; i < 4; i++ {
limiter.registerFailure("192.0.2.10", "admin")
}
now = now.Add(6 * time.Minute)
if _, blocked := limiter.registerFailure("192.0.2.10", "admin"); blocked {
t.Fatal("old failures should be pruned outside the rolling window")
}
limiter.registerSuccess("192.0.2.10", "admin")
for i := 0; i < 4; i++ {
if _, blocked := limiter.registerFailure("192.0.2.10", "admin"); blocked {
t.Fatalf("success should reset previous failures; failure %d blocked", i+1)
}
}
}
func TestLoginLimiterSeparatesIPAndUsername(t *testing.T) {
now := time.Date(2026, 5, 6, 12, 0, 0, 0, time.UTC)
limiter := newLoginLimiter(5, 5*time.Minute, 15*time.Minute)
limiter.now = func() time.Time { return now }
for i := 0; i < 5; i++ {
limiter.registerFailure("192.0.2.10", "admin")
}
if _, ok := limiter.allow("192.0.2.11", "admin"); !ok {
t.Fatal("different IP should not be blocked")
}
if _, ok := limiter.allow("192.0.2.10", "other-admin"); !ok {
t.Fatal("different username should not be blocked")
}
}