Per-key rate limits on the public API

C# · ASP.NET Core · advanced · modification

Adds per-key rate limiting to the public API with the built-in `Microsoft.AspNetCore.RateLimiting` middleware. `RateLimiting/ApiRateLimits.cs` (new) registers a `per-api-key` policy, one token bucket per authenticated key id (bursts of 60, refilled at one request per second, no queue), and a rejection handler that answers a 429 problem with `Retry-After` taken from the limiter's lease. `Program.cs` registers it, adds `UseRateLimiter()` to the pipeline and applies the policy to the `/v1` group. `RateLimitTests.cs` (new) covers the burst and the 429, two keys, 401s and the health check.

Public REST API of Parcelly, a shipment-tracking service for merchants: ASP.NET Core 10 minimal API on .NET 10 (C# 14, nullable reference types enabled, implicit usings), xUnit tests. Existing and unchanged: `AddApiKeyAuthentication()` registers the `ApiKey` authentication scheme, which reads `Authorization: Bearer <secret>`, looks the secret up through `IApiKeyStore` and, for a known key, signs the request in with the claims `key_id` (the key's id: a non-empty, server-generated string, not the secret, unique across all organizations) and `org_id`. A request without the header gets no result and an unknown secret fails; either way the `/v1` group's `RequireAuthorization()` answers 401. Every endpoint `MapShipmentEndpoints` maps requires an API key, and none allows anonymous access. There are at most 20,000 API keys. `AddProblemDetails`, `UseExceptionHandler` and `UseStatusCodePages` make every error `application/problem+json`, and an unhandled exception becomes a generic 500. `/healthz` is the load balancer's health check. The API runs as a single instance behind a load balancer that already limits requests per client IP. `tests/Parcelly.Api.Tests/ApiFactory.cs` is the existing `WebApplicationFactory<Program>` fixture: `CreateClientWithKey(secret)` returns a client that sends that bearer secret (none for `null`), with the test keys `SecretA` (id `key_a`) and `SecretB` (id `key_b`).

Requirements

Files touched

Review this PR

C# practice