55 lines
1.8 KiB
C#
55 lines
1.8 KiB
C#
using NTP.Application.Auth;
|
|
|
|
namespace NTP.Tests;
|
|
|
|
internal sealed class FakeTimeProvider(DateTimeOffset start) : TimeProvider
|
|
{
|
|
private DateTimeOffset _now = start;
|
|
public override DateTimeOffset GetUtcNow() => _now;
|
|
public void Advance(TimeSpan by) => _now += by;
|
|
}
|
|
|
|
public class LoginThrottleTests
|
|
{
|
|
private static (LoginThrottle t, FakeTimeProvider clock) Make()
|
|
{
|
|
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 1, 1, 8, 0, 0, TimeSpan.Zero));
|
|
return (new LoginThrottle(clock), clock);
|
|
}
|
|
|
|
[Fact]
|
|
public void Blocks_a_login_after_five_failures_and_frees_it_after_the_window()
|
|
{
|
|
var (t, clock) = Make();
|
|
for (var i = 0; i < LoginThrottle.MaxPerLogin; i++)
|
|
{
|
|
Assert.Null(t.BlockedFor("aseza.1", $"10.0.0.{i}")); // different addresses: the limit follows the login
|
|
t.RecordFailure("aseza.1", $"10.0.0.{i}");
|
|
}
|
|
Assert.NotNull(t.BlockedFor("aseza.1", "10.9.9.9"));
|
|
Assert.Null(t.BlockedFor("aseza.2", "10.9.9.9")); // another login is not affected
|
|
|
|
clock.Advance(LoginThrottle.Window + TimeSpan.FromSeconds(1));
|
|
Assert.Null(t.BlockedFor("aseza.1", "10.9.9.9"));
|
|
}
|
|
|
|
[Fact]
|
|
public void Success_clears_the_login()
|
|
{
|
|
var (t, _) = Make();
|
|
for (var i = 0; i < 4; i++) t.RecordFailure("aseza.1", "10.0.0.1");
|
|
t.RecordSuccess("aseza.1");
|
|
t.RecordFailure("aseza.1", "10.0.0.1");
|
|
Assert.Null(t.BlockedFor("aseza.1", "10.0.0.1"));
|
|
}
|
|
|
|
[Fact]
|
|
public void Blocks_an_address_that_tries_many_logins()
|
|
{
|
|
var (t, _) = Make();
|
|
for (var i = 0; i < LoginThrottle.MaxPerIp; i++) t.RecordFailure($"aseza.{i}", "10.0.0.1");
|
|
Assert.NotNull(t.BlockedFor("aseza.new", "10.0.0.1"));
|
|
Assert.Null(t.BlockedFor("aseza.new", "10.0.0.2"));
|
|
}
|
|
}
|