40 lines
969 B
Go
40 lines
969 B
Go
package auth
|
|
|
|
import (
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestLoginRateLimiter_Allow(t *testing.T) {
|
|
lim := NewLoginRateLimiter(3, time.Minute, 10*time.Second)
|
|
key := "127.0.0.1"
|
|
for i := 0; i < 3; i++ {
|
|
if !lim.Allow(key) {
|
|
t.Fatalf("should allow attempt %d", i)
|
|
}
|
|
lim.RecordFailure(key)
|
|
}
|
|
if lim.Allow(key) {
|
|
t.Fatalf("should block after 3 failures")
|
|
}
|
|
// After block duration with 0 block, should allow immediately (no block)
|
|
lim2 := NewLoginRateLimiter(5, time.Minute, 0)
|
|
for i := 0; i < 5; i++ {
|
|
lim2.RecordFailure(key)
|
|
}
|
|
// With block 0, Allow should reset after reaching max and not block
|
|
if !lim2.Allow(key) {
|
|
t.Fatalf("with 0 block duration, should allow after max")
|
|
}
|
|
}
|
|
|
|
func TestLoginRateLimiter_SuccessClears(t *testing.T) {
|
|
lim := NewLoginRateLimiter(3, time.Minute, 10*time.Second)
|
|
key := "1.2.3.4"
|
|
lim.RecordFailure(key)
|
|
lim.RecordFailure(key)
|
|
lim.RecordSuccess(key)
|
|
if !lim.Allow(key) {
|
|
t.Fatalf("success should clear")
|
|
}
|
|
}
|