Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using System.Net;
using Xunit.Abstractions;

namespace RateLimitingDotNET8.Tests;
namespace RateLimiting.Tests;

public class CustomerControllerConcurrencyLiveTests : IClassFixture<WebApplicationFactory<Program>>
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using System.Net;

namespace RateLimiting.Tests;

public class CustomerControllerPolicyTests : IClassFixture<WebApplicationFactory<Program>>
{
private const int FixedPermitLimit = 20;
private const int SlidingPermitLimit = 10;
private const int TokenLimit = 10;

private readonly HttpClient _client;

public CustomerControllerPolicyTests(WebApplicationFactory<Program> factory)
{
_client = factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddAuthentication(defaultScheme: "TestScheme")
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
"TestScheme", options => { });
});
})
.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
}

[Fact]
public async Task WhenActionHasNoAttribute_ThenTheControllerPolicyLimitsIt()
{
for (var i = 0; i < FixedPermitLimit; i++)
{
var allowed = await _client.GetAsync("/Customer/Index");
Assert.Equal(HttpStatusCode.OK, allowed.StatusCode);
}

var rejected = await _client.GetAsync("/Customer/Index");

Assert.Equal(HttpStatusCode.TooManyRequests, rejected.StatusCode);
}

[Fact]
public async Task WhenActionHasItsOwnAttribute_ThenItOverridesTheControllerPolicy()
{
// The controller carries [EnableRateLimiting(Policies.Fixed)] at 20 permits,
// the action carries [EnableRateLimiting(Policies.Sliding)] at 10. If the
// controller's policy were the one in force, request 11 would still be allowed.
for (var i = 0; i < SlidingPermitLimit; i++)
{
var allowed = await _client.GetAsync("/Customer/Details");
Assert.Equal(HttpStatusCode.OK, allowed.StatusCode);
}

var rejected = await _client.GetAsync("/Customer/Details");

Assert.Equal(HttpStatusCode.TooManyRequests, rejected.StatusCode);
}

[Fact]
public async Task WhenATokenBucketRequestIsRejected_ThenOnRejectedWritesRetryAfter()
{
HttpResponseMessage? rejected = null;

for (var i = 0; i <= TokenLimit && rejected is null; i++)
{
var response = await _client.GetAsync("/Customer/GetById");
if (response.StatusCode == HttpStatusCode.TooManyRequests)
{
rejected = response;
}
}

Assert.NotNull(rejected);
Assert.True(rejected!.Headers.TryGetValues("Retry-After", out var values));
Assert.True(int.Parse(values!.Single()) > 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using Microsoft.Extensions.DependencyInjection;
using System.Net;

namespace RateLimitingDotNET8.Tests;
namespace RateLimiting.Tests;
public class CustomerControllerTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using System.Net;
using System.Threading.RateLimiting;

namespace RateLimiting.Tests;

public class GlobalLimiterTests : IClassFixture<WebApplicationFactory<Program>>
{
private const int GlobalPermitLimit = 5;

private readonly HttpClient _client;

public GlobalLimiterTests(WebApplicationFactory<Program> factory)
{
_client = factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddAuthentication(defaultScheme: "TestScheme")
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
"TestScheme", options => { });

// Repeated AddRateLimiter calls configure the same RateLimiterOptions
// instance, so this global limiter is added to the ones Program.cs registers.
services.AddRateLimiter(limiterOptions =>
{
limiterOptions.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(
_ => RateLimitPartition.GetFixedWindowLimiter("global", _ =>
new FixedWindowRateLimiterOptions
{
PermitLimit = GlobalPermitLimit,
Window = TimeSpan.FromMinutes(1)
}));
});
});
})
.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
}

[Fact]
public async Task WhenTheGlobalLimitIsSpent_ThenAnEndpointInsideItsOwnLimitIsStillRejected()
{
// /Customer/Index is under the controller's fixed policy at 20 permits, so
// anything rejected inside the first six requests came from the global limiter.
for (var i = 0; i < GlobalPermitLimit; i++)
{
var allowed = await _client.GetAsync("/Customer/Index");
Assert.Equal(HttpStatusCode.OK, allowed.StatusCode);
}

var rejected = await _client.GetAsync("/Customer/Index");

Assert.Equal(HttpStatusCode.TooManyRequests, rejected.StatusCode);
}

[Fact]
public async Task WhenAnActionDisablesRateLimiting_ThenTheGlobalLimiterDoesNotApply()
{
for (var i = 0; i < GlobalPermitLimit * 2; i++)
{
var response = await _client.GetAsync("/Customer/SpecialOffer");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

Expand All @@ -10,21 +10,21 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.11" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<PackageReference Include="coverlet.collector" Version="10.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\RateLimitingDotNET8\RateLimitingDotNET8.csproj" />
<ProjectReference Include="..\RateLimiting\RateLimiting.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34309.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RateLimitingDotNET8", "RateLimitingDotNET8\RateLimitingDotNET8.csproj", "{080CC0E5-4B65-41EB-A34A-D810C414820D}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RateLimiting", "RateLimiting\RateLimiting.csproj", "{080CC0E5-4B65-41EB-A34A-D810C414820D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RateLimitingDotNET8.Tests", "RateLimitingDotNET8.Tests\RateLimitingDotNET8.Tests.csproj", "{B8FEBE55-F1D9-49FB-ADDE-2B456A195DB1}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RateLimiting.Tests", "RateLimiting.Tests\RateLimiting.Tests.csproj", "{B8FEBE55-F1D9-49FB-ADDE-2B456A195DB1}"
ProjectSection(ProjectDependencies) = postProject
{080CC0E5-4B65-41EB-A34A-D810C414820D} = {080CC0E5-4B65-41EB-A34A-D810C414820D}
EndProjectSection
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RateLimitingDotNET8;
namespace RateLimiting;

public static class ConfigurationSettingsExtension
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;

namespace RateLimitingDotNET8.Controllers;
namespace RateLimiting.Controllers;

//[EnableRateLimiting(Policies.Fixed)]
[EnableRateLimiting(Policies.Fixed)]
[ApiController]
[Route("customer")]
public class CustomerController : ControllerBase
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
namespace RateLimitingDotNET8;
namespace RateLimiting;

public class RateLimiterOptions
public class LimiterSettings
{
public int QueueLimit { get; set; } = default!;
}

public class FixedOptions : RateLimiterOptions
public class FixedOptions : LimiterSettings
{
public const string Fixed = "FixedOptions";
public int PermitLimit { get; set; } = default!;
public double Window { get; set; } = default!;
}

public class SlidingWindowOptions : RateLimiterOptions
public class SlidingWindowOptions : LimiterSettings
{
public const string Sliding = "SlidingWindowOptions";

Expand All @@ -21,7 +21,7 @@ public class SlidingWindowOptions : RateLimiterOptions
public int SegmentsPerWindow { get; set; } = default!;
}

public class TokenBucketOptions : RateLimiterOptions
public class TokenBucketOptions : LimiterSettings
{
public const string Token = "TokenBucketOptions";

Expand All @@ -31,7 +31,7 @@ public class TokenBucketOptions : RateLimiterOptions
public bool AutoReplenishment { get; set; } = default!;
}

public class ConcurrencyOptions : RateLimiterOptions
public class ConcurrencyOptions : LimiterSettings
{
public const string Concurrency = "ConcurrencyOptions";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RateLimitingDotNET8;
namespace RateLimiting;

public static class Policies
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using RateLimitingDotNET8;
using RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSettings(builder.Configuration);

RateLimiters.RejectionHandling(builder);

RateLimiters.FixedRateLimiter(builder);

RateLimiters.SlidingRateLimiter(builder);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,31 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using System.Globalization;
using System.Threading.RateLimiting;

namespace RateLimitingDotNET8;
namespace RateLimiting;

public static class RateLimiters
{
public static void RejectionHandling(WebApplicationBuilder builder)
{
builder.Services.AddRateLimiter(limiterOptions =>
{
limiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests;

limiterOptions.OnRejected = (context, cancellationToken) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.RetryAfter =
((int)retryAfter.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo);
}

return ValueTask.CompletedTask;
};
});
}

public static void FixedRateLimiter(WebApplicationBuilder builder)
{
var fixedOptions = GetOptionValues<FixedOptions>(builder);
Expand Down Expand Up @@ -67,7 +86,7 @@ public static void ConcurrencyRateLimiter(WebApplicationBuilder builder)

public static void AuthorizationRateLimiter(WebApplicationBuilder builder)
{
var authorizedLimiterOptions = builder.Configuration.GetSection(AuthorizedOptions.Authorized).Get<AuthorizedOptions>();
var authorizedLimiterOptions = GetOptionValues<AuthorizedOptions>(builder);

var unauthorizedLimiterOptions = GetOptionValues<UnauthorizedOptions>(builder);

Expand All @@ -76,7 +95,6 @@ public static void AuthorizationRateLimiter(WebApplicationBuilder builder)

builder.Services.AddRateLimiter(limiterOptions =>
{
limiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
limiterOptions.AddPolicy(policyName: Policies.Authorization, partitioner: httpContext =>
{
var accessToken = httpContext.GetTokenAsync("access_token").Result;
Expand Down Expand Up @@ -144,9 +162,6 @@ public static void MinimalApiRateLimiting(WebApplication app)
}


private static T GetOptionValues<T>(WebApplicationBuilder builder) where T : class
{
var serviceProvider = builder.Services.BuildServiceProvider();
return serviceProvider.GetRequiredService<IOptions<T>>().Value;
}
private static T GetOptionValues<T>(WebApplicationBuilder builder) where T : class, new()
=> builder.Configuration.GetSection(typeof(T).Name).Get<T>() ?? new T();
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.3" />
</ItemGroup>

</Project>
Loading