1
0
mirror of https://github.com/bitwarden/server.git synced 2024-12-05 14:23:30 +01:00
bitwarden-server/test/Core.Test/Utilities/CustomRedisProcessingStrategyTests.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

204 lines
6.5 KiB
C#
Raw Normal View History

using AspNetCoreRateLimit;
using Bit.Core.Settings;
using Bit.Core.Utilities;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
2023-08-10 17:03:42 +02:00
using NSubstitute;
using StackExchange.Redis;
using Xunit;
namespace Bit.Core.Test.Utilities;
public class CustomRedisProcessingStrategyTests
{
#region Sample RateLimit Options for Testing
private readonly GlobalSettings _sampleSettings = new()
{
DistributedIpRateLimiting = new GlobalSettings.DistributedIpRateLimitingSettings
{
Enabled = true,
MaxRedisTimeoutsThreshold = 2,
SlidingWindowSeconds = 5
}
};
private readonly ClientRequestIdentity _sampleClientId = new()
{
ClientId = "test",
ClientIp = "127.0.0.1",
HttpVerb = "GET",
Path = "/"
};
private readonly RateLimitRule _sampleRule = new() { Endpoint = "/", Limit = 5, Period = "1m", PeriodTimespan = TimeSpan.FromMinutes(1) };
private readonly RateLimitOptions _sampleOptions = new() { };
#endregion
2023-08-10 17:03:42 +02:00
private readonly ICounterKeyBuilder _mockCounterKeyBuilder = Substitute.For<ICounterKeyBuilder>();
private IDatabase _mockDb;
public CustomRedisProcessingStrategyTests()
{
2023-08-10 17:03:42 +02:00
_mockCounterKeyBuilder.Build(Arg.Any<ClientRequestIdentity>(), Arg.Any<RateLimitRule>())
.Returns(_sampleClientId.ClientId);
}
[Fact]
public async Task IncrementRateLimitCount_When_RedisIsHealthy()
{
// Arrange
var strategy = BuildProcessingStrategy();
// Act
2023-08-10 17:03:42 +02:00
var result = await strategy.ProcessRequestAsync(_sampleClientId, _sampleRule, _mockCounterKeyBuilder, _sampleOptions,
CancellationToken.None);
// Assert
Assert.Equal(1, result.Count);
2023-08-10 17:03:42 +02:00
VerifyRedisCalls(1);
}
[Fact]
public async Task SkipRateLimit_When_RedisIsDown()
{
// Arrange
var strategy = BuildProcessingStrategy(false);
// Act
2023-08-10 17:03:42 +02:00
var result = await strategy.ProcessRequestAsync(_sampleClientId, _sampleRule, _mockCounterKeyBuilder, _sampleOptions,
CancellationToken.None);
// Assert
Assert.Equal(0, result.Count);
2023-08-10 17:03:42 +02:00
VerifyRedisNotCalled();
}
[Fact]
public async Task SkipRateLimit_When_TimeoutThresholdExceeded()
{
// Arrange
2023-08-10 17:03:42 +02:00
var mockCache = Substitute.For<IMemoryCache>();
object existingCount = new CustomRedisProcessingStrategy.TimeoutCounter
{
Count = _sampleSettings.DistributedIpRateLimiting.MaxRedisTimeoutsThreshold + 1
};
2023-08-10 17:03:42 +02:00
mockCache.TryGetValue(Arg.Any<object>(), out existingCount).ReturnsForAnyArgs(x =>
{
x[1] = existingCount;
return true;
});
2023-08-10 17:03:42 +02:00
var strategy = BuildProcessingStrategy(mockCache: mockCache);
// Act
2023-08-10 17:03:42 +02:00
var result = await strategy.ProcessRequestAsync(_sampleClientId, _sampleRule, _mockCounterKeyBuilder, _sampleOptions,
CancellationToken.None);
// Assert
Assert.Equal(0, result.Count);
2023-08-10 17:03:42 +02:00
VerifyRedisNotCalled();
}
[Fact]
public async Task SkipRateLimit_When_RedisTimeoutException()
{
// Arrange
2023-08-10 17:03:42 +02:00
var mockCache = Substitute.For<IMemoryCache>();
var mockCacheEntry = Substitute.For<ICacheEntry>();
mockCache.CreateEntry(Arg.Any<object>()).Returns(mockCacheEntry);
2023-08-10 17:03:42 +02:00
var strategy = BuildProcessingStrategy(mockCache: mockCache, throwRedisTimeout: true);
// Act
2023-08-10 17:03:42 +02:00
var result = await strategy.ProcessRequestAsync(_sampleClientId, _sampleRule, _mockCounterKeyBuilder, _sampleOptions,
CancellationToken.None);
2023-08-10 17:03:42 +02:00
var timeoutCounter = ((CustomRedisProcessingStrategy.TimeoutCounter)mockCacheEntry.Value);
// Assert
Assert.Equal(0, result.Count); // Skip rate limiting
2023-08-10 17:03:42 +02:00
VerifyRedisCalls(1);
Assert.Equal(1, timeoutCounter.Count); // Timeout count increased/cached
2023-08-10 17:03:42 +02:00
Assert.NotNull(mockCacheEntry.AbsoluteExpiration);
mockCache.Received().CreateEntry(Arg.Any<object>());
}
[Fact]
public async Task BackoffRedis_After_ThresholdExceeded()
{
// Arrange
var memoryCache = new MemoryCache(new MemoryCacheOptions());
var strategy = BuildProcessingStrategy(mockCache: memoryCache, throwRedisTimeout: true);
// Act
// Redis Timeout 1
2023-08-10 17:03:42 +02:00
await strategy.ProcessRequestAsync(_sampleClientId, _sampleRule, _mockCounterKeyBuilder, _sampleOptions,
CancellationToken.None);
// Redis Timeout 2
2023-08-10 17:03:42 +02:00
await strategy.ProcessRequestAsync(_sampleClientId, _sampleRule, _mockCounterKeyBuilder, _sampleOptions,
CancellationToken.None);
// Skip Redis
2023-08-10 17:03:42 +02:00
await strategy.ProcessRequestAsync(_sampleClientId, _sampleRule, _mockCounterKeyBuilder, _sampleOptions,
CancellationToken.None);
// Assert
2023-08-10 17:03:42 +02:00
VerifyRedisCalls(_sampleSettings.DistributedIpRateLimiting.MaxRedisTimeoutsThreshold);
}
private void VerifyRedisCalls(int times)
{
_mockDb
.Received(times)
.ScriptEvaluateAsync(Arg.Any<LuaScript>(), Arg.Any<object>(), Arg.Any<CommandFlags>());
}
2023-08-10 17:03:42 +02:00
private void VerifyRedisNotCalled()
{
2023-08-10 17:03:42 +02:00
_mockDb
.DidNotReceive()
.ScriptEvaluateAsync(Arg.Any<LuaScript>(), Arg.Any<object>(), Arg.Any<CommandFlags>());
}
private CustomRedisProcessingStrategy BuildProcessingStrategy(
bool isRedisConnected = true,
bool throwRedisTimeout = false,
IMemoryCache mockCache = null)
{
2023-08-10 17:03:42 +02:00
var mockRedisConnection = Substitute.For<IConnectionMultiplexer>();
2023-08-10 17:03:42 +02:00
mockRedisConnection.IsConnected.Returns(isRedisConnected);
2023-08-10 17:03:42 +02:00
_mockDb = Substitute.For<IDatabase>();
var mockScriptEvaluate = _mockDb
2023-08-10 17:03:42 +02:00
.ScriptEvaluateAsync(Arg.Any<LuaScript>(), Arg.Any<object>(), Arg.Any<CommandFlags>());
if (throwRedisTimeout)
{
2023-08-10 17:03:42 +02:00
mockScriptEvaluate.Returns<RedisResult>(x => throw new RedisTimeoutException("Timeout", CommandStatus.WaitingToBeSent));
}
else
{
2023-08-10 17:03:42 +02:00
mockScriptEvaluate.Returns(RedisResult.Create(1));
}
2023-08-10 17:03:42 +02:00
mockRedisConnection.GetDatabase(Arg.Any<int>(), Arg.Any<object>())
.Returns(_mockDb);
2023-08-10 17:03:42 +02:00
var mockLogger = Substitute.For<ILogger<CustomRedisProcessingStrategy>>();
var mockConfig = Substitute.For<IRateLimitConfiguration>();
2023-08-10 17:03:42 +02:00
mockCache ??= Substitute.For<IMemoryCache>();
2023-08-10 17:03:42 +02:00
return new CustomRedisProcessingStrategy(mockRedisConnection, mockConfig,
mockLogger, mockCache, _sampleSettings);
}
}