forked from gongxuegit/tiku-backend.net
feat: add rate limiting and startup options validation
This commit is contained in:
17
Tiku.Api/Options/ApiRateLimitOptions.cs
Normal file
17
Tiku.Api/Options/ApiRateLimitOptions.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace Tiku.Api.Options;
|
||||
|
||||
public sealed class ApiRateLimitOptions
|
||||
{
|
||||
public const string SectionName = "RateLimiting";
|
||||
|
||||
public bool Enabled { get; set; } = true;
|
||||
|
||||
[System.ComponentModel.DataAnnotations.Range(1, 100_000)]
|
||||
public int PermitLimit { get; set; } = 600;
|
||||
|
||||
[System.ComponentModel.DataAnnotations.Range(1, 86_400)]
|
||||
public int WindowSeconds { get; set; } = 60;
|
||||
|
||||
[System.ComponentModel.DataAnnotations.Range(0, 10_000)]
|
||||
public int QueueLimit { get; set; }
|
||||
}
|
||||
@@ -5,8 +5,16 @@ public sealed class CorsOptions
|
||||
public const string SectionName = "Cors";
|
||||
public const string PolicyName = "TikuCors";
|
||||
|
||||
[System.ComponentModel.DataAnnotations.Required]
|
||||
public string[] AllowedOrigins { get; set; } = [];
|
||||
|
||||
[System.ComponentModel.DataAnnotations.Required]
|
||||
[System.ComponentModel.DataAnnotations.MinLength(1)]
|
||||
public string[] AllowedHeaders { get; set; } = ["Authorization", "Content-Type", "x-tenant-code"];
|
||||
|
||||
[System.ComponentModel.DataAnnotations.Required]
|
||||
[System.ComponentModel.DataAnnotations.MinLength(1)]
|
||||
public string[] AllowedMethods { get; set; } = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
|
||||
|
||||
public bool AllowCredentials { get; set; }
|
||||
}
|
||||
|
||||
21
Tiku.Api/Options/OptionsValidation.cs
Normal file
21
Tiku.Api/Options/OptionsValidation.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
namespace Tiku.Api.Options;
|
||||
|
||||
public static class OptionsValidation
|
||||
{
|
||||
public static bool BeValidCorsOptions(CorsOptions options)
|
||||
{
|
||||
if (options.AllowCredentials && options.AllowedOrigins.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return options.AllowedOrigins.All(IsHttpOrigin);
|
||||
}
|
||||
|
||||
private static bool IsHttpOrigin(string origin)
|
||||
{
|
||||
return Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
|
||||
(uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) &&
|
||||
string.IsNullOrEmpty(uri.PathAndQuery.Trim('/'));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user