forked from gongxuegit/tiku-backend.net
feat: add rate limiting and startup options validation
This commit is contained in:
@@ -2,7 +2,9 @@ using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Tiku.Api.Options;
|
||||
using Tiku.Application.Security;
|
||||
using Tiku.Domain.Tenancy;
|
||||
|
||||
@@ -71,6 +73,54 @@ public sealed class SecurityFoundationTests
|
||||
Assert.Contains("true", body, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Global_rate_limiter_returns_too_many_requests_problem()
|
||||
{
|
||||
await using var factory = new ApiTestFactory();
|
||||
using var client = factory.CreateClient();
|
||||
|
||||
using var firstResponse = await client.GetAsync("/api/health");
|
||||
HttpResponseMessage? rejectedResponse = null;
|
||||
for (var index = 0; index < 1200; index++)
|
||||
{
|
||||
rejectedResponse?.Dispose();
|
||||
rejectedResponse = await client.GetAsync("/api/health");
|
||||
}
|
||||
|
||||
using var secondResponse = rejectedResponse ?? throw new InvalidOperationException("Rate limit test did not send a second request.");
|
||||
var body = JsonDocument.Parse(await secondResponse.Content.ReadAsStringAsync());
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, secondResponse.StatusCode);
|
||||
Assert.Equal("rate_limited", body.RootElement.GetProperty("code").GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("https://tenant.example.com", true)]
|
||||
[InlineData("http://localhost:5173", true)]
|
||||
[InlineData("localhost:5173", false)]
|
||||
[InlineData("https://tenant.example.com/path", false)]
|
||||
public void Cors_options_validation_requires_absolute_http_origins(string origin, bool expected)
|
||||
{
|
||||
var options = new CorsOptions
|
||||
{
|
||||
AllowedOrigins = [origin]
|
||||
};
|
||||
|
||||
Assert.Equal(expected, OptionsValidation.BeValidCorsOptions(options));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cors_options_validation_requires_explicit_origins_when_credentials_are_enabled()
|
||||
{
|
||||
var options = new CorsOptions
|
||||
{
|
||||
AllowCredentials = true
|
||||
};
|
||||
|
||||
Assert.False(OptionsValidation.BeValidCorsOptions(options));
|
||||
}
|
||||
|
||||
private static ApiTestFactory CreateFactory()
|
||||
{
|
||||
return new ApiTestFactory();
|
||||
|
||||
Reference in New Issue
Block a user