feat: add rate limiting and startup options validation

This commit is contained in:
xiong
2026-07-26 13:46:17 +08:00
parent f4783c5de3
commit 015c9b5582
9 changed files with 204 additions and 2 deletions

View 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; }
}

View File

@@ -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; }
}

View 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('/'));
}
}