Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#1305 RateLimiting headers #1307

Open
wants to merge 21 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e741e62
Merge pull request #7 from ThreeMammals/develop
jlukawska Jul 15, 2023
1060ef9
set rate limiting headers on the proper httpcontext
jlukawska Jul 31, 2020
b2d4deb
Fix CS0169: The field '_responseStatusCode' is never used
raman-m Aug 2, 2023
f820be4
IDE1006 Naming rule violation: These words must begin with upper case…
raman-m Aug 2, 2023
1aac06a
Merge branch 'ThreeMammals:develop' into develop
jlukawska Apr 19, 2024
d174272
Merge remote-tracking branch 'origin/develop' into fix/1305-ratelimit…
Apr 29, 2024
0de9c39
fix after merge
Apr 29, 2024
03db4c5
CR fix
Apr 29, 2024
fa8c3e8
fix to tests
Apr 29, 2024
3ea824b
Merge branch 'develop' into fix/1305-ratelimiting-headers
raman-m Apr 30, 2024
ec15a65
fix Retry-After header
Apr 30, 2024
e852df9
Merge remote-tracking branch 'origin/fix/1305-ratelimiting-headers' i…
Apr 30, 2024
d01f253
merge fix
Apr 30, 2024
3530e7a
add Retry-After header checks in tests
Apr 30, 2024
eede977
refactor of ClientRateLimitTests
May 4, 2024
3f527fd
Merge pull request #10 from ThreeMammals/develop
jlukawska May 10, 2024
c30edac
Merge remote-tracking branch 'origin/develop' into fix/1305-ratelimit…
jlukawska May 12, 2024
98df368
merge fix
jlukawska May 12, 2024
c110a59
Merge remote-tracking branch 'origin/develop' into fix/1305-ratelimit…
jlukawska May 15, 2024
59e9886
Merge remote-tracking branch 'origin/develop' into fix/1305-ratelimit…
jlukawska Jun 29, 2024
53fbcd2
Merge remote-tracking branch 'origin/develop' into fix/1305-ratelimit…
jlukawska Jul 24, 2024
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
19 changes: 15 additions & 4 deletions src/Ocelot/RateLimiting/Middleware/RateLimitingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using Ocelot.Configuration;
using Ocelot.Logging;
using Ocelot.Middleware;
Expand All @@ -10,15 +12,18 @@ public class RateLimitingMiddleware : OcelotMiddleware
{
private readonly RequestDelegate _next;
private readonly IRateLimiting _limiter;
private readonly IServiceProvider _container;

public RateLimitingMiddleware(
RequestDelegate next,
IOcelotLoggerFactory factory,
IRateLimiting limiter)
IRateLimiting limiter,
IServiceProvider container)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Injecting the service provider instead of directly injecting the IHttpContextAccessor object can be considered a significant design flaw, in my opinion.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and it is a bad practice to embeded service provider

: base(factory.CreateLogger<RateLimitingMiddleware>())
{
_next = next;
_limiter = limiter;
_container = container;
}

public async Task Invoke(HttpContext httpContext)
Expand Down Expand Up @@ -71,8 +76,13 @@ public async Task Invoke(HttpContext httpContext)
//set X-Rate-Limit headers for the longest period
if (!options.DisableRateLimitHeaders)
{
var headers = _limiter.GetHeaders(httpContext, identity, options);
httpContext.Response.OnStarting(SetRateLimitHeaders, state: headers);
var httpContextAccessor = _container.GetService<IHttpContextAccessor>();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should check if the original http context is null - this shouldn't happen though -, why not use

var originalHttpContext = httpContextAccessor?.HttpContext;
if(originalHttpContext != null)
{
   var headers = _limiter.GetHeaders(originalHttpContext, identity, options);
   originalHttpContext.Response.OnStarting(SetRateLimitHeaders, state: headers);
}

instead?

if (httpContextAccessor != null)
{
var originalHttpContext = httpContextAccessor.HttpContext;
var headers = _limiter.GetHeaders(originalHttpContext, identity, options);
originalHttpContext.Response.OnStarting(SetRateLimitHeaders, state: headers);
}
}

await _next.Invoke(httpContext);
Expand Down Expand Up @@ -119,7 +129,8 @@ public virtual DownstreamResponse ReturnQuotaExceededResponse(HttpContext httpCo

if (!option.DisableRateLimitHeaders)
{
http.Headers.TryAddWithoutValidation("Retry-After", retryAfter); // in seconds, not date string
http.Headers.TryAddWithoutValidation(HeaderNames.RetryAfter, retryAfter); // in seconds, not date string
httpContext.Response.Headers[HeaderNames.RetryAfter] = retryAfter;
}

return new DownstreamResponse(http);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
using Ocelot.Configuration.File;

namespace Ocelot.AcceptanceTests.RateLimiting;
Expand Down Expand Up @@ -130,6 +131,92 @@ public void StatusShouldNotBeEqualTo429_PeriodTimespanValueIsGreaterThanPeriod()
.BDDfy();
}

[Fact]
public void should_set_ratelimiting_headers_on_response_when_DisableRateLimitHeaders_set_to_false()
{
int port = PortFinder.GetRandomPort();

var configuration = CreateConfigurationForCheckingHeaders(port, false);

this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/ClientRateLimit"))
.And(x => GivenThereIsAConfiguration(configuration))
.And(x => GivenOcelotIsRunning())
.When(x => WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1))
.Then(x => ThenRateLimitingHeadersExistInResponse(true))
.And(x => ThenRetryAfterHeaderExistsInResponse(false))
.When(x => WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 2))
.Then(x => ThenRateLimitingHeadersExistInResponse(true))
.And(x => ThenRetryAfterHeaderExistsInResponse(false))
.When(x => WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1))
.Then(x => ThenRateLimitingHeadersExistInResponse(false))
.And(x => ThenRetryAfterHeaderExistsInResponse(true))
.BDDfy();
}

[Fact]
public void should_not_set_ratelimiting_headers_on_response_when_DisableRateLimitHeaders_set_to_true()
{
int port = PortFinder.GetRandomPort();

var configuration = CreateConfigurationForCheckingHeaders(port, true);

this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/ClientRateLimit"))
.And(x => GivenThereIsAConfiguration(configuration))
.And(x => GivenOcelotIsRunning())
.When(x => WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1))
.Then(x => ThenRateLimitingHeadersExistInResponse(false))
.And(x => ThenRetryAfterHeaderExistsInResponse(false))
.When(x => WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 2))
.Then(x => ThenRateLimitingHeadersExistInResponse(false))
.And(x => ThenRetryAfterHeaderExistsInResponse(false))
.When(x => WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1))
.Then(x => ThenRateLimitingHeadersExistInResponse(false))
.And(x => ThenRetryAfterHeaderExistsInResponse(false))
.BDDfy();
}

private FileConfiguration CreateConfigurationForCheckingHeaders(int port, bool disableRateLimitHeaders)
{
return new FileConfiguration
{
Routes = new List<FileRoute>
{
new()
{
DownstreamPathTemplate = "/api/ClientRateLimit",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new()
{
Host = "localhost",
Port = port,
},
},
DownstreamScheme = "http",
UpstreamPathTemplate = "/api/ClientRateLimit",
UpstreamHttpMethod = new List<string> { "Get" },
RateLimitOptions = new FileRateLimitRule()
{
EnableRateLimiting = true,
ClientWhitelist = new List<string>(),
Limit = 3,
Period = "100s",
PeriodTimespan = 1000,
},
},
},
GlobalConfiguration = new FileGlobalConfiguration()
{
RateLimitOptions = new FileRateLimitOptions()
{
DisableRateLimitHeaders = disableRateLimitHeaders,
QuotaExceededMessage = "",
HttpStatusCode = 428,
},
},
};
}

private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath)
{
_serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, context =>
Expand Down Expand Up @@ -179,4 +266,16 @@ private static FileConfiguration GivenConfigurationWithRateLimitOptions(params F
};
return config;
}

private void ThenRateLimitingHeadersExistInResponse(bool headersExist)
{
_response.Headers.Contains("X-Rate-Limit-Limit").ShouldBe(headersExist);
_response.Headers.Contains("X-Rate-Limit-Remaining").ShouldBe(headersExist);
_response.Headers.Contains("X-Rate-Limit-Reset").ShouldBe(headersExist);
}

private void ThenRetryAfterHeaderExistsInResponse(bool headersExist)
{
_response.Headers.Contains(HeaderNames.RetryAfter).ShouldBe(headersExist);
}
}
Loading