Path: redb-route/redb.Route.Http.Hosting/SharedHttpServerManager.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Http.Hosting/SharedHttpServerManager.cs ---- using System.Collections.Concurrent; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Claims; using System.Security.Cryptography.X509Certificates; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Template; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Https; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace redb.Route.Http; /// /// Manages shared Kestrel server instances across multiple route contexts. /// One server per (host, port) combination. Multiple consumers can register routes /// on the same port. Supports dynamic route addition/removal at runtime. /// public sealed class SharedHttpServerManager : IAsyncDisposable { private readonly ConcurrentDictionary _servers = new(StringComparer.OrdinalIgnoreCase); private readonly object _lock = new(); private readonly HttpHostingOptions _options; private readonly ILogger? _logger; /// Key under which the pre-resolution socket address is kept in HttpContext.Items. public const string OriginalRemoteAddressItem = "redb.OriginalRemoteAddress"; /// Key under which the pre-resolution scheme is kept in HttpContext.Items. public const string OriginalSchemeItem = "redb.OriginalScheme"; /// /// Key under which the caller's principal, as produced by , /// is kept in HttpContext.Items. Absent when no resolver is configured or it returned null. /// public const string PrincipalItem = "redb.Principal"; /// Creates a manager with default options: no trusted proxies, forwarded headers ignored. public SharedHttpServerManager() : this(null) { } /// /// Creates a manager with explicit host options. Under DI the options arrive through /// AddRedbRouteHttpHosting(configure); a host that constructs the manager by hand /// passes them here. /// public SharedHttpServerManager(HttpHostingOptions? options) : this(options, null) { } /// /// Creates a manager with host options and a logger for the failures that happen before any /// transport sees a request — a principal resolver that throws. The listener's own logging is /// switched off, so without this logger such a failure is visible only as the 500 it produces. /// public SharedHttpServerManager(HttpHostingOptions? options, ILogger? logger) { _options = options ?? new HttpHostingOptions(); _logger = logger; } /// /// Returns the principal the host resolved for this request (), or null. /// This is what a consumer copies onto the exchange it builds from the request. /// public static ClaimsPrincipal? GetResolvedPrincipal(HttpContext context) { ArgumentNullException.ThrowIfNull(context); return context.Items.TryGetValue(PrincipalItem, out var raw) ? raw as ClaimsPrincipal : null; } /// The process-wide host options this manager applies to every listener it opens. public HttpHostingOptions Options => _options; /// Number of active servers. public int ServerCount => _servers.Count; /// /// Registers a route handler on the shared server for the given host:port. /// Creates the server if it does not yet exist. /// /// Bind address (e.g. "0.0.0.0"). /// Bind port. /// Route path template (e.g. "/api/users/{id}"). /// Allowed HTTP methods (comma-separated) or null for all. /// The async request handler delegate. /// Whether this server uses HTTPS. /// PFX certificate path for HTTPS. /// PFX certificate password. /// Optional per-route CORS configuration. When supplied, the /// shared server installs a single CORS middleware that dispatches per matched route, so /// different routes on the same (host, port) can declare different CORS policies. /// When null, no CORS headers are emitted for this route. /// Max request body size (0 = unlimited). /// HTTP protocol set for the listener. Every route on a given /// (host, port) must agree — a mismatch throws rather than silently keeping the first value. /// Client-certificate policy (mTLS). Belongs to the TLS /// handshake, so it is per listener and must agree across routes on the same port. /// Extra check on a presented client certificate, applied /// on top of Kestrel's chain validation (e.g. a thumbprint allow-list). /// Optional per-registration admission limit: caps concurrent /// executions of and sheds the overflow with a status reply before /// any pipeline work. Strictly per-route — neighbors on the same listener are unaffected. /// A registration handle that can be used to unregister the route. public RouteRegistration RegisterRoute( string host, int port, string pathTemplate, string? methods, Func handler, bool ssl = false, string? sslCertPath = null, string? sslCertPassword = null, RouteCorsOptions? corsOptions = null, long maxRequestBodySize = 0, HttpProtocol protocol = HttpProtocol.Http1And2, ClientCertificateMode? clientCertificateMode = null, Func? clientCertificateValidation = null, ConcurrencyLimitOptions? concurrencyLimit = null) { concurrencyLimit?.Validate(); var key = BuildKey(host, port); lock (_lock) { var entry = _servers.GetOrAdd(key, _ => new ServerEntry(host, port, ssl, sslCertPath, sslCertPassword, maxRequestBodySize, protocol, clientCertificateMode, clientCertificateValidation)); // Validate scheme consistency if (entry.Ssl != ssl) throw new InvalidOperationException( $"Server on {host}:{port} is already registered as {(entry.Ssl ? "HTTPS" : "HTTP")}. " + $"Cannot register a {(ssl ? "HTTPS" : "HTTP")} route on the same port."); // One listener cannot speak two protocol sets. Silently keeping the first value used to send // a gRPC route to an HTTP/1.1 listener, where every call fails with an unreadable framing // error instead of a configuration one. if (entry.Protocol != protocol) throw new InvalidOperationException( $"Server on {host}:{port} is already listening as {entry.Protocol}. " + $"Cannot register a {protocol} route on the same port — use a separate port."); // Same reasoning for mTLS: the client-certificate policy belongs to the TLS handshake, so it // is per listener, not per route. if (entry.ClientCertificateMode != clientCertificateMode) throw new InvalidOperationException( $"Server on {host}:{port} is already registered with client-certificate mode " + $"'{entry.ClientCertificateMode?.ToString() ?? "none"}'. Cannot register a route with " + $"'{clientCertificateMode?.ToString() ?? "none"}' on the same port."); // Admission limit is strictly per-registration: several routes share one listener, and a // saturated neighbor must not eat this route's budget (nor the other way around). System.Threading.RateLimiting.ConcurrencyLimiter? limiter = null; if (concurrencyLimit is not null) { limiter = concurrencyLimit.CreateLimiter(); handler = WrapWithConcurrencyLimit(handler, concurrencyLimit, limiter); } var registration = new RouteRegistration(key, pathTemplate, methods, handler, corsOptions) { Limiter = limiter, }; entry.Routes.Add(registration); entry.InvalidateRouteTable(); // Track whether the server needs to install the CORS dispatch middleware. // Once any route registers with CORS, the middleware is enabled for the lifetime // of the server (it is a no-op for routes that do not have CORS configured). if (corsOptions is not null) entry.CorsEnabled = true; return registration; } } /// /// Declares the listener on : for a transport that serves WebSocket /// upgrades, with its TLS settings when this is the listener's first registration, and its keep-alive. Every /// listener accepts upgrades (UseWebSockets() is part of every pipeline: endpoints mapped onto a running /// listener, a SignalR hub, cannot add it later, and it touches only upgrade requests). The keep-alive is read /// when the listener is built; on a running listener the call changes nothing. /// /// Listener host. /// Listener port. /// /// Ping interval for idle connections. It is a property of the listener, not of a route, so the /// first non-null value wins and later ones are ignored. /// /// The listener terminates TLS, when this is its first registration. /// Server certificate of a TLS listener. /// Password of . public void EnableWebSockets(string host, int port, TimeSpan? keepAliveInterval = null, bool ssl = false, string? sslCertPath = null, string? sslCertPassword = null) { var key = BuildKey(host, port); lock (_lock) { // The TLS settings travel with the call because this may be the first touch of the // listener: an entry created as plain HTTP here would then collide with the wss route // the consumer registers a moment later. var entry = _servers.GetOrAdd(key, _ => new ServerEntry(host, port, ssl, sslCertPath, sslCertPassword, 0, HttpProtocol.Http1And2, null, null)); // Every listener accepts WebSocket upgrades (a hub mapped onto it later needs them, and // middleware cannot be added to a running pipeline); what this call still decides is the // keep-alive, read when the listener is built. A running listener keeps its own. if (!entry.IsStarted) entry.WebSocketKeepAlive ??= keepAliveInterval; } } /// /// Maps endpoints of a transport's own onto the listener on :, before /// or after it started: a SignalR hub, a gRPC service, minimal API handlers. runs on an /// whose is /// , so a framework that takes its pieces from there (MapHub, MapConnections) builds /// them from the transport's container and not from the listener's, which this package keeps to itself. Every /// request to the endpoints runs in a scope of (HttpContext.RequestServices). /// /// The endpoints join the running listener through endpoint routing, beside the route table: literal paths of /// theirs win over the catch-all of the route table, and the connections the listener already serves are left /// alone. Disposing the returned registration removes them the same way. The listener stays up while any route or /// registration occupies it. /// /// /// A registration brings no middleware: the listener's pipeline (trusted proxies, CORS, the caller's principal, /// WebSocket upgrades) is fixed when it is built. A gate of the transport's own belongs on its endpoints, as an /// endpoint convention inside . /// /// /// Listener host. /// Listener port. /// The transport's container: the services its endpoints are built and served with. /// Maps the endpoints. /// The listener terminates TLS, when this is its first registration. /// Server certificate of a TLS listener. /// Password of . public EndpointRegistration RegisterEndpoints( string host, int port, IServiceProvider services, Action map, bool ssl = false, string? sslCertPath = null, string? sslCertPassword = null) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(map); var builder = new RegistrationRouteBuilder(services); map(builder); var endpoints = builder.Build(); if (endpoints.Count == 0) throw new ArgumentException("The map callback mapped no endpoint.", nameof(map)); var key = BuildKey(host, port); lock (_lock) { // A transport that maps its own endpoints may never call RegisterRoute, so this can be the only place its // TLS settings ever reach the listener. var entry = _servers.GetOrAdd(key, _ => new ServerEntry(host, port, ssl, sslCertPath, sslCertPassword, 0, HttpProtocol.Http1And2, null, null)); if (ssl && !entry.Ssl) throw new InvalidOperationException( $"Server on {host}:{port} is already registered as HTTP. Cannot add HTTPS endpoints to the same port."); var registration = new EndpointRegistration(this, host, port, services, endpoints); entry.Endpoints.Add(registration); return registration; } } /// Removes the endpoints of a registration (). internal void UnregisterEndpoints(EndpointRegistration registration) { lock (_lock) { if (_servers.TryGetValue(BuildKey(registration.Host, registration.Port), out var entry)) entry.Endpoints.Remove(registration); } } /// /// Unregisters a route. If no routes remain on the server, it will be stopped on next StopServer call. /// public void UnregisterRoute(RouteRegistration registration) { lock (_lock) { if (_servers.TryGetValue(registration.ServerKey, out var entry)) { entry.Routes.Remove(registration); entry.InvalidateRouteTable(); } } // Outside the lock: releases queued waiters (their leases come back non-acquired → reject). registration.Limiter?.Dispose(); } /// /// Wraps a route handler with the admission limit: acquire a permit (waiting in the FIFO queue /// when one is configured), or shed the request with the configured status + Retry-After before /// any pipeline work. The wait is bound to RequestAborted, so a client that gives up /// leaves the queue instead of holding a slot. /// private static Func WrapWithConcurrencyLimit( Func inner, ConcurrencyLimitOptions limit, System.Threading.RateLimiting.ConcurrencyLimiter limiter) { return async ctx => { using var lease = await limiter.AcquireAsync(1, ctx.RequestAborted).ConfigureAwait(false); if (!lease.IsAcquired) { limit.OnRejected?.Invoke(); ctx.Response.StatusCode = limit.RejectStatusCode; if (limit.RetryAfterSeconds > 0) ctx.Response.Headers.RetryAfter = limit.RetryAfterSeconds.ToString(); return; } await inner(ctx).ConfigureAwait(false); }; } /// /// Ensures the server for the given host:port is started. /// If already running, this is a no-op. /// public async Task EnsureStarted(string host, int port, CancellationToken ct = default) { var key = BuildKey(host, port); ServerEntry entry; lock (_lock) { if (!_servers.TryGetValue(key, out entry!)) throw new InvalidOperationException($"No routes registered for {host}:{port}."); } if (entry.IsStarted) return; await StartServer(entry, ct).ConfigureAwait(false); } /// /// Stops the server for the given host:port if it has no remaining routes. /// public async Task StopIfEmpty(string host, int port, CancellationToken ct = default) { var key = BuildKey(host, port); ServerEntry? entry; lock (_lock) { if (!_servers.TryGetValue(key, out entry)) return; // Endpoints of a transport's own (a hub) occupy the listener without a route, so both have to // be empty before the socket can go away under a transport that is still serving. if (entry.Routes.Count > 0 || entry.Endpoints.Count > 0) return; _servers.TryRemove(key, out _); } await StopServer(entry, ct).ConfigureAwait(false); } /// /// Gets the base URL for a server. Available after EnsureStarted. /// public string? GetBaseUrl(string host, int port) { var key = BuildKey(host, port); if (_servers.TryGetValue(key, out var entry) && entry.IsStarted) { var scheme = entry.Ssl ? "https" : "http"; var displayHost = host == "0.0.0.0" ? "localhost" : host; return $"{scheme}://{displayHost}:{port}"; } return null; } /// public async ValueTask DisposeAsync() { foreach (var entry in _servers.Values) { await StopServer(entry, CancellationToken.None).ConfigureAwait(false); } _servers.Clear(); } // ── Private ── /// /// Turns the host of an endpoint URI into an address Kestrel can bind. Plain /// IPAddress.Parse threw a bare FormatException on any name; a DNS name is /// resolved here, and a name that resolves to nothing fails with a message that names the /// host. localhost never reaches this method — it has its own Kestrel helper. /// private static IPAddress ResolveBindAddress(string host) { if (IPAddress.TryParse(host, out var parsed)) return parsed; if (string.IsNullOrWhiteSpace(host) || host == "*" || host == "+") return IPAddress.Any; try { var resolved = Dns.GetHostAddresses(host); if (resolved.Length > 0) return resolved[0]; } catch (Exception ex) when (ex is SocketException or ArgumentException) { throw new ArgumentException( $"Cannot bind a listener to host '{host}': it is neither an IP address nor a resolvable name. " + "Use an address the machine owns, 0.0.0.0 for every interface, or localhost.", ex); } throw new ArgumentException( $"Cannot bind a listener to host '{host}': the name resolved to no addresses."); } /// /// Where a TLS listener's certificate comes from: the endpoint, then the host-wide default. /// Resolved before the host is built, so a misconfiguration fails at the bind with a message /// about the certificate rather than somewhere inside Kestrel's startup. /// private (System.Security.Cryptography.X509Certificates.X509Certificate2? Certificate, string? Path, string? Password) ResolveServerCertificate(ServerEntry entry) { if (!entry.Ssl) return (null, null, null); if (!string.IsNullOrEmpty(entry.SslCertPath)) return (null, entry.SslCertPath, entry.SslCertPassword); if (_options.Tls.DefaultCertificate is { } shared) return (shared, null, null); if (!string.IsNullOrEmpty(_options.Tls.DefaultCertificatePath)) return (null, _options.Tls.DefaultCertificatePath, _options.Tls.DefaultCertificatePassword); // Historically this fell through to a PLAINTEXT listener while GetBaseUrl and every log // line reported https://. Refusing to bind is what nginx, httpd, Jetty, Spring Boot and // Kestrel's own UseHttps() all do: TLS asked for and no certificate is a configuration // error, never a downgrade. throw new InvalidOperationException( $"Listener on {entry.Host}:{entry.Port} is configured for TLS but no server certificate could be " + "resolved. Set it on the endpoint (sslCertPath/sslCertPassword, or a named connectionFactory " + "carrying them), or give the host a default: " + "AddRedbRouteHttpHosting(o => o.Tls.DefaultCertificatePath = ...). Refusing to bind, because " + "without a certificate the listener would serve plaintext while reporting https://."); } private async Task StartServer(ServerEntry entry, CancellationToken ct) { if (entry.IsStarted) return; var certificate = ResolveServerCertificate(entry); var builder = WebApplication.CreateSlimBuilder(); builder.WebHost.ConfigureKestrel(kestrel => { var protocols = entry.Protocol switch { HttpProtocol.Http1 => Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1, HttpProtocol.Http2 => Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2, HttpProtocol.Http1And2 => Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2, HttpProtocol.Http3 => Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http3, HttpProtocol.Http1And2And3 => Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2AndHttp3, _ => Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2 }; void Configure(ListenOptions listenOptions) { listenOptions.Protocols = protocols; if (!entry.Ssl) return; void ConfigureHttps(HttpsConnectionAdapterOptions httpsOptions) { if (entry.ClientCertificateMode is { } mode) httpsOptions.ClientCertificateMode = mode; if (entry.ClientCertificateValidation is { } validate) httpsOptions.ClientCertificateValidation = (cert, chain, errors) => validate(cert, chain, errors); } if (certificate.Certificate is { } instance) listenOptions.UseHttps(instance, ConfigureHttps); else listenOptions.UseHttps(certificate.Path!, certificate.Password, ConfigureHttps); } // "localhost" goes through Kestrel's own helper, which binds BOTH loopbacks: picking one // IP for it would leave a client that resolved localhost to the other one unable to // connect. Everything else is an address, or a name resolved to one. if (string.Equals(entry.Host, "localhost", StringComparison.OrdinalIgnoreCase)) kestrel.ListenLocalhost(entry.Port, Configure); else kestrel.Listen(ResolveBindAddress(entry.Host), entry.Port, Configure); if (entry.MaxRequestBodySize > 0) kestrel.Limits.MaxRequestBodySize = entry.MaxRequestBodySize; else kestrel.Limits.MaxRequestBodySize = null; // Host-wide connection backstop (HostConnectionLimits): Kestrel's own defaults are // unlimited; leave them untouched unless the deployment set a ceiling. if (_options.Limits.MaxConcurrentConnections is { } maxConn) kestrel.Limits.MaxConcurrentConnections = maxConn; if (_options.Limits.MaxConcurrentUpgradedConnections is { } maxUpgraded) kestrel.Limits.MaxConcurrentUpgradedConnections = maxUpgraded; }); builder.Logging.ClearProviders(); // The listener's container is its own: a transport's endpoints come with their own container // (RegisterEndpoints), so nothing has to be added to this one before Build(). var app = builder.Build(); // Trusted-proxy resolution. Installed first, before anything reads the connection: every // consumer on this listener (Http, Soap, As2, Grpc, the Tsak management API) takes the client // address from Connection.RemoteIpAddress and the URL scheme from Request.Scheme, so rewriting // them here is the one place that covers all of them. Not installed at all when no proxy is // trusted, which keeps the default host byte-for-byte what it was. if (_options.TrustedProxies.IsEnabled) { app.Use(TrustedProxyMiddleware(_options.TrustedProxies)); } // Per-route CORS dispatch middleware. // Installed once per server. For each request it locates the matching route (path-only, // method-agnostic so that OPTIONS preflight finds the underlying route) and applies // that route's CORS policy. Routes registered without CORS get no headers. if (entry.CorsEnabled) { app.Use(CorsDispatchMiddleware(entry)); } // Caller identity (HttpHostingOptions.ResolvePrincipal), opt-in per process. After the proxy // resolution so the resolver sees the real client, after CORS so a preflight never reaches // it, and before the transport configurators so a hub's own gate sees the host's principal. if (_options.ResolvePrincipal is { } resolvePrincipal) { app.Use(PrincipalMiddleware(resolvePrincipal, _logger)); } // WebSocket upgrades, on every listener: endpoints mapped onto it later (a SignalR hub) cannot add the // middleware to a running pipeline, and it acts on upgrade requests only. Installed after the proxy/CORS // middleware so an upgrade request is seen with its real client address, and before the endpoints so a // handler can accept the socket. var wsOptions = new WebSocketOptions(); if (entry.WebSocketKeepAlive is { } keepAlive) wsOptions.KeepAliveInterval = keepAlive; app.UseWebSockets(wsOptions); // Endpoints of the transports' own (RegisterEndpoints), added and removed while the listener runs. ((IEndpointRouteBuilder)app).DataSources.Add(entry.Endpoints); // Single catch-all handler — our RouteTable dispatches dynamically. Last in order: a registered endpoint // that matches a path as well as the catch-all does is the one that serves it. app.Map("/{**path}", (HttpContext ctx) => HandleCatchAll(entry, ctx)).WithOrder(int.MaxValue); // Also handle root path app.MapGet("/", (HttpContext ctx) => HandleCatchAll(entry, ctx)).WithOrder(int.MaxValue); app.MapPost("/", (HttpContext ctx) => HandleCatchAll(entry, ctx)).WithOrder(int.MaxValue); app.MapPut("/", (HttpContext ctx) => HandleCatchAll(entry, ctx)).WithOrder(int.MaxValue); app.MapDelete("/", (HttpContext ctx) => HandleCatchAll(entry, ctx)).WithOrder(int.MaxValue); app.MapMethods("/", ["PATCH", "HEAD", "OPTIONS"], (HttpContext ctx) => HandleCatchAll(entry, ctx)).WithOrder(int.MaxValue); entry.App = app; try { await app.StartAsync(ct).ConfigureAwait(false); } catch { // A port still taken: the listener that did not start is let go, and the next start builds a new one. entry.App = null; await app.DisposeAsync().ConfigureAwait(false); throw; } entry.IsStarted = true; } private static async Task HandleCatchAll(ServerEntry entry, HttpContext ctx) { var requestPath = ctx.Request.Path.Value ?? "/"; var requestMethod = ctx.Request.Method; // Find matching route var match = entry.MatchRoute(requestPath, requestMethod); if (match.Registration is null) { // If path matched but method didn't, return 405 ctx.Response.StatusCode = match.PathMatched ? StatusCodes.Status405MethodNotAllowed : StatusCodes.Status404NotFound; return; } // Store route values for handlers to extract if (match.RouteValues is not null) { ctx.Items["__redbRouteValues"] = match.RouteValues; } await match.Registration.Handler(ctx).ConfigureAwait(false); } /// /// Builds the trusted-proxy delegate for one listener. It hands the socket peer and the two /// forwarded headers to and writes the outcome back into /// the connection and the request, keeping the originals in HttpContext.Items under /// / for diagnostics. /// All the policy lives in the resolver; this is the ten lines that know about Kestrel. /// private static Func, Task> TrustedProxyMiddleware(TrustedProxyOptions trust) { return (ctx, next) => { var peer = ctx.Connection.RemoteIpAddress; var headers = ctx.Request.Headers; var resolved = ForwardedHeaderResolver.Resolve( peer, headers[ForwardedHeaderResolver.ForwardedFor].ToString(), headers[ForwardedHeaderResolver.ForwardedProto].ToString(), trust); if (resolved.AddressApplied && resolved.ClientAddress is not null) { ctx.Items[OriginalRemoteAddressItem] = peer; ctx.Connection.RemoteIpAddress = resolved.ClientAddress; } if (trust.ForwardScheme && resolved.Scheme is not null && !string.Equals(resolved.Scheme, ctx.Request.Scheme, StringComparison.OrdinalIgnoreCase)) { ctx.Items[OriginalSchemeItem] = ctx.Request.Scheme; ctx.Request.Scheme = resolved.Scheme; } return next(); }; } /// /// Builds the caller-identity delegate: runs the host's resolver once per request and keeps a /// non-null result in HttpContext.Items under . An anonymous /// request passes through untouched; a request whose resolver failed does not, because letting it /// through would hand the route an anonymous caller that may not be one. /// private static Func, Task> PrincipalMiddleware( Func> resolve, ILogger? logger) { return async (ctx, next) => { ClaimsPrincipal? principal; try { principal = await resolve(ctx).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { // The text stays in the log: it describes the resolver (a key endpoint, a token store), // nothing the caller should read. logger?.LogError(ex, "Principal resolver failed for {Method} {Path}", ctx.Request.Method, ctx.Request.Path); ctx.Response.StatusCode = StatusCodes.Status500InternalServerError; return; } if (principal is not null) ctx.Items[PrincipalItem] = principal; await next().ConfigureAwait(false); }; } /// /// Builds the per-route CORS dispatch middleware. The middleware locates the route by /// path (method-agnostic so OPTIONS preflight resolves the underlying route's policy), /// then applies that route's : /// /// resolves the allowed origin via the resolver delegate or the static whitelist; /// echoes the resolved origin in Access-Control-Allow-Origin with Vary: Origin; /// reflects requested headers and methods on preflight (RFC 6454 §7.3 friendly); /// guards the wildcard-with-credentials footgun at request time. /// /// Routes without CORS options receive no headers \u2014 the middleware is transparent for them. /// private static Func, Task> CorsDispatchMiddleware(ServerEntry entry) { return async (ctx, next) => { var requestPath = ctx.Request.Path.Value ?? "/"; var route = entry.MatchByPath(requestPath); var cors = route?.Cors; if (cors is null) { await next().ConfigureAwait(false); return; } var requestOrigin = ctx.Request.Headers["Origin"].ToString(); var resolved = ResolveOrigin(cors, ctx.Request, requestOrigin); // C15 / browser footgun: wildcard with credentials is rejected by browsers. // Demote to "no CORS headers" so the request fails closed instead of emitting // headers the browser will refuse and confusing the developer. if (resolved == "*" && cors.AllowCredentials) resolved = null; if (resolved is not null) { ctx.Response.Headers["Access-Control-Allow-Origin"] = resolved; // Vary: Origin is mandatory whenever the response varies by request Origin // (i.e. always when a resolver/whitelist is in play). Without it, intermediate // caches will serve the wrong CORS headers to the wrong origin. AppendVary(ctx.Response.Headers, "Origin"); if (cors.AllowCredentials) ctx.Response.Headers["Access-Control-Allow-Credentials"] = "true"; // Preflight reflection: echo back exactly what the browser asked for, falling // back to the route's static method list or "*" only when the request did not // advertise a specific method/headers set. if (HttpMethods.IsOptions(ctx.Request.Method)) { var requestedMethod = ctx.Request.Headers["Access-Control-Request-Method"].ToString(); ctx.Response.Headers["Access-Control-Allow-Methods"] = !string.IsNullOrEmpty(requestedMethod) ? requestedMethod : (cors.AllowedMethods ?? route!.Methods ?? "*"); var requestedHeaders = ctx.Request.Headers["Access-Control-Request-Headers"].ToString(); ctx.Response.Headers["Access-Control-Allow-Headers"] = !string.IsNullOrEmpty(requestedHeaders) ? requestedHeaders : (cors.AllowCredentials ? "Content-Type, Authorization" : "*"); ctx.Response.Headers["Access-Control-Max-Age"] = cors.MaxAgeSeconds.ToString(); } } // Always short-circuit OPTIONS preflight \u2014 even when the origin was rejected, // returning 204 with no CORS headers is the correct browser-friendly behaviour // (browser will then reject the request without escalating to the actual call). if (HttpMethods.IsOptions(ctx.Request.Method)) { ctx.Response.StatusCode = StatusCodes.Status204NoContent; return; } await next().ConfigureAwait(false); }; } private static string? ResolveOrigin(RouteCorsOptions cors, HttpRequest request, string requestOrigin) { // Resolver delegate wins; allowed to return "*", a specific origin, or null. if (cors.OriginsResolver is { } resolver) return resolver(request); var allowed = cors.AllowedOrigins; if (string.IsNullOrEmpty(allowed)) return null; // Wildcard whitelist: emit "*" verbatim. Browsers ignore "*" with credentials \u2014 // the caller-side guard above demotes that combination to null. if (allowed == "*") return "*"; // Explicit whitelist: only echo back the request's Origin if it appears in the // comma-separated list. Browsers cannot consume a CSV in Access-Control-Allow-Origin, // so we must single-select. if (string.IsNullOrEmpty(requestOrigin)) return null; foreach (var entry in allowed.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { if (entry.Equals(requestOrigin, StringComparison.OrdinalIgnoreCase)) return entry; } return null; } private static void AppendVary(IHeaderDictionary headers, string value) { var current = headers["Vary"].ToString(); if (string.IsNullOrEmpty(current)) { headers["Vary"] = value; return; } // Avoid duplicating "Origin" if some other middleware already added it. foreach (var part in current.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { if (part.Equals(value, StringComparison.OrdinalIgnoreCase)) return; } headers["Vary"] = current + ", " + value; } private static async Task StopServer(ServerEntry entry, CancellationToken ct) { if (entry.App is not null && entry.IsStarted) { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); try { await entry.App.StopAsync(cts.Token).ConfigureAwait(false); } catch (OperationCanceledException) { } await entry.App.DisposeAsync().ConfigureAwait(false); entry.App = null; entry.IsStarted = false; } } private static string BuildKey(string host, int port) => $"{host}:{port}"; // ── Inner types ── internal sealed class ServerEntry { public string Host { get; } public int Port { get; } public bool Ssl { get; } public string? SslCertPath { get; } public string? SslCertPassword { get; } public long MaxRequestBodySize { get; } public HttpProtocol Protocol { get; } public List Routes { get; } = []; public WebApplication? App { get; set; } public bool IsStarted { get; set; } /// /// True when at least one registered route declared CORS options. The shared CORS /// dispatch middleware is installed iff this is true at server-build time. /// public bool CorsEnabled { get; set; } /// Keep-alive interval for the WebSocket middleware; null leaves the framework default. public TimeSpan? WebSocketKeepAlive { get; set; } /// /// Endpoints of the transports' own (a SignalR hub), each with its container. They are occupants of the /// listener just like routes: the server stays up while any of them is present, and stops when the last /// one leaves. /// public DynamicEndpointSource Endpoints { get; } = new(); private readonly TemplateMatcher[] _matchers = []; private volatile (TemplateMatcher matcher, RouteRegistration reg, string[]? methods)[]? _compiled; /// /// Drops the compiled route table so the next request rebuilds it. Called on every register and /// unregister: a count comparison missed an unregister + register pair (a route restart, a REST /// redeploy) and kept dispatching to a removed handler. /// public void InvalidateRouteTable() => _compiled = null; /// Client-certificate policy for the listener (mTLS). Null = do not request one. public ClientCertificateMode? ClientCertificateMode { get; } /// /// Extra check applied to a presented client certificate on top of Kestrel's chain validation /// (for example an allow-list of thumbprints). /// public Func? ClientCertificateValidation { get; } public ServerEntry(string host, int port, bool ssl, string? sslCertPath, string? sslCertPassword, long maxRequestBodySize, HttpProtocol protocol = HttpProtocol.Http1And2, ClientCertificateMode? clientCertificateMode = null, Func? clientCertificateValidation = null) { Host = host; Port = port; Ssl = ssl; SslCertPath = sslCertPath; SslCertPassword = sslCertPassword; MaxRequestBodySize = maxRequestBodySize; Protocol = protocol; ClientCertificateMode = clientCertificateMode; ClientCertificateValidation = clientCertificateValidation; } public RouteMatch MatchRoute(string requestPath, string requestMethod) { // Compile route table lazily / on change var compiled = GetCompiled(); var pathMatched = false; foreach (var (matcher, reg, methods) in compiled) { var values = new RouteValueDictionary(); if (!matcher.TryMatch(requestPath, values)) continue; pathMatched = true; // Check method filter if (methods is not null && !methods.Any(m => m.Equals(requestMethod, StringComparison.OrdinalIgnoreCase))) continue; return new RouteMatch(reg, values, true); } return new RouteMatch(null, null, pathMatched); } /// /// Returns the first route whose path template matches , /// regardless of HTTP method. Used by the CORS dispatch middleware so that an OPTIONS /// preflight can locate the underlying route's CORS policy even when OPTIONS is not /// in the route's allowed-methods list. /// public RouteRegistration? MatchByPath(string requestPath) { var compiled = GetCompiled(); foreach (var (matcher, reg, _) in compiled) { var values = new RouteValueDictionary(); if (matcher.TryMatch(requestPath, values)) return reg; } return null; } private (TemplateMatcher matcher, RouteRegistration reg, string[]? methods)[] GetCompiled() { var compiled = _compiled; if (compiled is not null) return compiled; // Build, then order by specificity so a concrete path (e.g. "/api/echo") is matched // BEFORE a catch-all ("/{**path}") registered on the same (host, port). Without this // the table was pure registration order and a catch-all would swallow every later // route. Specificity ranking (literal-heavy first, catch-all last) matches what // callers intuitively expect from ASP.NET-style routing. Registration order is the // stable tie-breaker, so equal-specificity routes keep their old first-wins behaviour. var built = new (TemplateMatcher matcher, RouteRegistration reg, string[]? methods, int order, RouteSpecificity spec)[Routes.Count]; for (var i = 0; i < Routes.Count; i++) { var reg = Routes[i]; var template = TemplateParser.Parse(reg.PathTemplate.TrimStart('/')); var matcher = new TemplateMatcher(template, new RouteValueDictionary()); var methods = ParseMethods(reg.Methods); built[i] = (matcher, reg, methods, i, Analyze(template)); } _compiled = built .OrderBy(x => x.spec.HasCatchAll ? 1 : 0) // concrete paths first, catch-all last .ThenByDescending(x => x.spec.Literals) // more literal segments = more specific .ThenBy(x => x.spec.Parameters) // fewer parameters = more specific .ThenBy(x => x.order) // stable: preserve registration order on ties .Select(x => (x.matcher, x.reg, x.methods)) .ToArray(); return _compiled; } /// Specificity facts about a parsed route template, used to rank match order. private readonly record struct RouteSpecificity(bool HasCatchAll, int Literals, int Parameters); private static RouteSpecificity Analyze(RouteTemplate template) { var hasCatchAll = false; int literals = 0, parameters = 0; foreach (var segment in template.Segments) { foreach (var part in segment.Parts) { if (part.IsCatchAll) hasCatchAll = true; else if (part.IsParameter) parameters++; else if (part.IsLiteral) literals++; } } return new RouteSpecificity(hasCatchAll, literals, parameters); } private static string[]? ParseMethods(string? methods) { if (string.IsNullOrEmpty(methods)) return null; return methods.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); } } } /// /// Handle for a registered route on a shared server. /// public sealed class RouteRegistration { internal string ServerKey { get; } /// The route path template. public string PathTemplate { get; } /// Allowed methods (comma-separated) or null for all methods. public string? Methods { get; } /// The request handler. public Func Handler { get; } /// /// Optional per-route CORS configuration. When set, the shared server applies these /// CORS headers for requests matching . /// public RouteCorsOptions? Cors { get; } /// /// Admission limiter backing this registration's maxConcurrentRequests, when one is /// configured. Owned by the registration; disposed on unregister. /// internal System.Threading.RateLimiting.ConcurrencyLimiter? Limiter { get; init; } internal RouteRegistration(string serverKey, string pathTemplate, string? methods, Func handler, RouteCorsOptions? cors = null) { ServerKey = serverKey; PathTemplate = pathTemplate; Methods = methods; Handler = handler; Cors = cors; } } /// /// Per-route CORS configuration applied by the shared HTTP server's dispatch middleware. /// All fields are immutable. The middleware enforces the wildcard-with-credentials rule /// at request time regardless of which field the origin came from. /// /// Comma-separated whitelist of allowed origins. May contain a single /// "*" for public endpoints (only when is false). /// Comma-separated list emitted in Access-Control-Allow-Methods /// when the request is a preflight; if null, the route's method filter is used; if also null, *. /// Sets Access-Control-Allow-Credentials: true when true. /// Optional per-request resolver. Receives the request and returns /// the origin to echo back, "*", or null (origin not allowed). Takes precedence over /// . /// Value emitted in Access-Control-Max-Age. Default 86400 (24h). public sealed record RouteCorsOptions( string? AllowedOrigins, string? AllowedMethods, bool AllowCredentials, Func? OriginsResolver = null, int MaxAgeSeconds = 86_400); /// /// Result of route matching with path-match and method-match distinction. /// internal readonly record struct RouteMatch( RouteRegistration? Registration, RouteValueDictionary? RouteValues, bool PathMatched);