Bundle: redb-route / redb.Route.Http.Hosting (redb.Route.Http.Hosting.txt), 10 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Http.Hosting/ConcurrencyLimitOptions.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/ConcurrencyLimitOptions.cs ---- using System.Threading.RateLimiting; namespace redb.Route.Http; /// /// Per-registration admission limit for one route on the shared Kestrel host. Kestrel itself /// accepts an unbounded number of concurrent requests; this caps how many of them may EXECUTE /// a given route's handler at once, sheds the overflow with an immediate status reply /// (load shedding, not backpressure — the industry norm: ASP.NET ConcurrencyLimiter policies, /// nginx limit_conn, Envoy max_concurrent_requests), and leaves every other registration on the /// same listener untouched. /// /// Backed by : up to permits, /// an optional FIFO wait queue of , everything beyond answered with /// + Retry-After before any pipeline work happens. /// /// public sealed class ConcurrencyLimitOptions { /// Maximum concurrent executions of the route handler. Must be at least 1. public required int MaxConcurrentRequests { get; init; } /// /// How many requests over the limit WAIT for a permit (FIFO) instead of being rejected. /// 0 (default) = reject immediately once the permits are taken. /// public int RequestQueueLimit { get; init; } /// Status code for a shed request. Default 429 Too Many Requests. public int RejectStatusCode { get; init; } = 429; /// Value of the Retry-After header on a shed request; 0 = do not send it. Default 1. public int RetryAfterSeconds { get; init; } = 1; /// /// Invoked once per shed request, before the reject response is written. The hosting layer /// deliberately knows nothing about redb.Route endpoint statistics — a connector passes /// endpoint.RecordRejected here. /// public Action? OnRejected { get; init; } internal void Validate() { if (MaxConcurrentRequests < 1) throw new ArgumentOutOfRangeException(nameof(MaxConcurrentRequests), MaxConcurrentRequests, "maxConcurrentRequests must be at least 1 (omit the limit entirely for unlimited)."); if (RequestQueueLimit < 0) throw new ArgumentOutOfRangeException(nameof(RequestQueueLimit), RequestQueueLimit, "requestQueueLimit cannot be negative."); if (RejectStatusCode is < 400 or > 599) throw new ArgumentOutOfRangeException(nameof(RejectStatusCode), RejectStatusCode, "rejectStatusCode must be a 4xx or 5xx status code."); if (RetryAfterSeconds < 0) throw new ArgumentOutOfRangeException(nameof(RetryAfterSeconds), RetryAfterSeconds, "retryAfterSeconds cannot be negative (0 = do not send the header)."); } internal ConcurrencyLimiter CreateLimiter() => new(new ConcurrencyLimiterOptions { PermitLimit = MaxConcurrentRequests, QueueLimit = RequestQueueLimit, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, }); /// /// Validates the option quartet as it appears on an ENDPOINT, where 0 for /// means "feature off" (unlike this class, whose /// instances always describe an active limit). One validator for every connector that /// exposes the options, so the rules cannot drift apart. /// public static void ValidateShape(int maxConcurrentRequests, int requestQueueLimit, int rejectStatusCode, int retryAfterSeconds) { if (maxConcurrentRequests < 0) throw new ArgumentException("maxConcurrentRequests must be >= 0 (0 = unlimited)."); if (requestQueueLimit < 0) throw new ArgumentException("requestQueueLimit must be >= 0."); if (maxConcurrentRequests == 0 && requestQueueLimit > 0) throw new ArgumentException( "requestQueueLimit without maxConcurrentRequests is meaningless: there is no limit to queue behind. Set maxConcurrentRequests >= 1."); if (rejectStatusCode is < 400 or > 599) throw new ArgumentException("rejectStatusCode must be a 4xx or 5xx status code."); if (retryAfterSeconds < 0) throw new ArgumentException("retryAfterSeconds must be >= 0 (0 = do not send the header)."); } /// /// Builds the registration-level limit from endpoint options, or null when the feature is off /// ( = 0). is the /// connector's statistics hook (endpoint.RecordRejected). /// public static ConcurrencyLimitOptions? FromEndpoint(int maxConcurrentRequests, int requestQueueLimit, int rejectStatusCode, int retryAfterSeconds, Action? onRejected) => maxConcurrentRequests <= 0 ? null : new ConcurrencyLimitOptions { MaxConcurrentRequests = maxConcurrentRequests, RequestQueueLimit = requestQueueLimit, RejectStatusCode = rejectStatusCode, RetryAfterSeconds = retryAfterSeconds, OnRejected = onRejected, }; } Path: redb-route/redb.Route.Http.Hosting/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace redb.Route.Http; /// /// Registration for the shared Kestrel hosting infrastructure. /// public static class HostingServiceCollectionExtensions { /// /// Registers the shared as a single instance for the container. /// Idempotent () /// so every HTTP-based transport (redb.Route.Http, redb.Route.As2, …) can call it and they all /// share ONE server manager — one Kestrel per host:port, with routes multiplexed across connectors. /// public static IServiceCollection AddRedbRouteHttpHosting(this IServiceCollection services) => AddRedbRouteHttpHosting(services, null); /// /// Registers the shared host and applies to its /// . Safe to call more than once: every call contributes its /// configuration, the manager is still created once, and the options are read when the manager /// is first resolved. Connectors register the host with no configuration; the process that /// owns the deployment (a worker, a test fixture) is the one that adds trusted proxies. /// Example: services.AddRedbRouteHttpHosting(o => o.TrustedProxies.Add("10.0.0.5")); /// public static IServiceCollection AddRedbRouteHttpHosting( this IServiceCollection services, Action? configure) { services.AddOptions(); if (configure is not null) services.Configure(configure); services.TryAddSingleton(sp => new SharedHttpServerManager( sp.GetRequiredService>().Value, sp.GetService()?.CreateLogger())); return services; } } Path: redb-route/redb.Route.Http.Hosting/ForwardedHeaderResolver.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/ForwardedHeaderResolver.cs ---- using System.Net; namespace redb.Route.Http; /// /// Outcome of resolving the forwarded headers of one request. /// /// The address to treat as the client. Equal to the socket peer when /// nothing applied. /// The scheme the client used (http / https), or null when the /// header was absent, unreadable, or the peer is not trusted. /// True when came out of /// X-Forwarded-For rather than the socket. /// How many trusted proxy entries were skipped while walking the chain. public readonly record struct ForwardedResolution( IPAddress? ClientAddress, string? Scheme, bool AddressApplied, int TrustedHops); /// /// Turns X-Forwarded-For and X-Forwarded-Proto into a client address and scheme, /// given the socket peer and the set of proxies the host trusts. Pure: no HttpContext, no /// I/O, so it is unit-testable on strings and survives a change of HTTP engine unchanged. /// /// /// /// Every proxy in a chain appends the address it accepted the connection from, so a client's own /// entries always sit to the left of the entry the first trusted proxy wrote. The chain is /// therefore walked from the right: trusted entries are skipped, and the first entry that is not /// a trusted proxy is the client. A header from a peer that is not itself trusted is ignored /// outright, because nothing in it was written by anyone we trust. /// /// /// An entry that does not parse as an address stops the walk and the socket peer is kept. It /// must not be skipped: skipping would carry the walk past the last trusted hop into the part of /// the header the client controls. /// /// /// X-Forwarded-Proto is read in step with the address: with k trusted hops skipped, /// the scheme is the entry k positions from the right, which is the scheme observed by the /// proxy that talked to the client. A single value is used as is. /// /// /// Not handled, deliberately: the RFC 7239 Forwarded header, and X-Forwarded-Host. /// Rewriting the host changes what redirects and absolute URLs point at and needs an allow-list /// of its own; it is a separate decision. /// /// public static class ForwardedHeaderResolver { /// Header name for the client address chain. public const string ForwardedFor = "X-Forwarded-For"; /// Header name for the client scheme. public const string ForwardedProto = "X-Forwarded-Proto"; /// /// Resolves the client address and scheme for one request. /// /// The address the connection was accepted from. Null yields an /// untouched result. /// Raw X-Forwarded-For value, comma separated, or null. /// Raw X-Forwarded-Proto value, or null. /// The proxies the host trusts. public static ForwardedResolution Resolve( IPAddress? socketPeer, string? forwardedFor, string? forwardedProto, TrustedProxyOptions trust) { ArgumentNullException.ThrowIfNull(trust); if (socketPeer is null || !trust.IsEnabled || !trust.IsTrusted(socketPeer)) return new ForwardedResolution(socketPeer, null, false, 0); var client = socketPeer; var applied = false; var trustedHops = 0; var chain = SplitChain(forwardedFor); if (chain.Count > 0) { var found = false; for (var i = chain.Count - 1; i >= 0; i--) { if (!TryParseHop(chain[i], out var hop)) { // Unreadable entry: stop here and keep the socket peer. Walking on would reach // the client-controlled part of the header. return new ForwardedResolution(socketPeer, null, false, trustedHops); } if (trust.IsTrusted(hop)) { trustedHops++; continue; } client = hop; applied = true; found = true; break; } // Every entry was a trusted proxy (a proxy calling through itself, a health check): // the socket peer stays, and the scheme below still applies. if (!found) client = socketPeer; } var scheme = ResolveScheme(forwardedProto, trustedHops); return new ForwardedResolution(client, scheme, applied, trustedHops); } private static string? ResolveScheme(string? forwardedProto, int trustedHops) { var values = SplitChain(forwardedProto); if (values.Count == 0) return null; var index = Math.Max(0, values.Count - 1 - trustedHops); var value = values[index]; if (value.Equals("https", StringComparison.OrdinalIgnoreCase)) return "https"; if (value.Equals("http", StringComparison.OrdinalIgnoreCase)) return "http"; return null; } private static List SplitChain(string? raw) { if (string.IsNullOrWhiteSpace(raw)) return []; return raw .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .ToList(); } /// /// Parses one chain entry, tolerating the forms proxies actually emit: a bare IPv4 or IPv6 /// address, IPv4:port, and [IPv6]:port. IPv4-mapped IPv6 is folded to IPv4 so /// it compares with a list written in IPv4. /// internal static bool TryParseHop(string token, out IPAddress address) { address = IPAddress.None; var value = token; if (value.StartsWith('[')) { var end = value.IndexOf(']'); if (end < 0) return false; value = value.Substring(1, end - 1); } else if (value.Count(c => c == ':') == 1) { // IPv4:port. A bare IPv6 address carries several colons and is left alone. value = value[..value.IndexOf(':')]; } if (!IPAddress.TryParse(value, out var parsed)) return false; address = TrustedProxyOptions.Normalize(parsed); return true; } } Path: redb-route/redb.Route.Http.Hosting/HttpHostingOptions.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/HttpHostingOptions.cs ---- using System.Security.Claims; using Microsoft.AspNetCore.Http; namespace redb.Route.Http; /// /// Process-wide settings of the shared Kestrel host. One instance serves every listener the /// opens, because the things configured here (which proxies /// to trust) describe the deployment the process runs in, not any single route. /// /// /// /// services.AddRedbRouteHttpHosting(o => o.TrustedProxies.Add("10.0.0.5").Add("10.1.0.0/16")); /// /// public sealed class HttpHostingOptions { /// Reverse proxies allowed to set the client address and scheme. Empty by default. public TrustedProxyOptions TrustedProxies { get; } = new(); /// Server-wide TLS material, used by listeners whose endpoint does not carry its own. public ServerTlsOptions Tls { get; } = new(); /// Kestrel connection ceilings applied to every listener the manager opens. public HostConnectionLimits Limits { get; } = new(); /// /// Identifies the caller of each request on every listener the manager opens. Null (the default) /// leaves requests unidentified and the host byte-for-byte what it was. /// /// It runs once per request: after trusted-proxy resolution, so it sees the client's real address /// and scheme; after CORS, so a preflight never reaches it; and before any transport sees the /// request. A non-null result is kept in HttpContext.Items under /// , and the HTTP, gRPC, SOAP, AS2, WebSocket and /// SignalR consumers put it on the exchange (ExchangePrincipal). /// /// /// It identifies; it does not authorize. Return null for an anonymous caller: such a request /// is still served, because one listener carries routes with different requirements, and whether /// an anonymous caller is acceptable is each route's decision. A resolver that throws fails the /// request with 500 and an error log instead — one that could not decide must not quietly hand the /// route an anonymous caller that may not be one. Build the identity with an authentication type /// (new ClaimsIdentity(claims, "Bearer")): code that reads the principal treats an identity that /// is not authenticated as anonymous. /// /// /// A transport's own authenticate hook (WsComponent.Authenticate, /// SignalRComponent.Authenticate) takes precedence on that transport's paths. /// /// /// /// /// services.AddRedbRouteHttpHosting(o => o.ResolvePrincipal = ctx => /// myTokenValidator.ValidateAsync(ctx.Request.Headers.Authorization.ToString())); /// /// public Func>? ResolvePrincipal { get; set; } } /// /// Coarse host-wide backstop: Kestrel's own connection ceilings, applied to every listener this /// process opens. Kestrel's defaults are unlimited; these protect the whole port. The fine-grained /// tool is the per-route admission limit () — this is the /// fuse, not the thermostat. /// public sealed class HostConnectionLimits { /// Maximum concurrent connections per listener. Null (default) = Kestrel default (unlimited). public long? MaxConcurrentConnections { get; set; } /// /// Maximum concurrent upgraded connections (WebSockets) per listener. /// Null (default) = Kestrel default (unlimited). /// public long? MaxConcurrentUpgradedConnections { get; set; } } /// /// The host's own TLS material. A listener that asks for TLS resolves its certificate from the /// endpoint first (sslCertPath, or a named connection factory), and falls back to what is /// set here — the same shape as Camel's global SSLContextParameters and Spring Boot's SSL /// bundles, where a certificate on the endpoint is an override rather than a requirement. /// /// Nothing here turns TLS on: ssl stays an explicit per-endpoint decision. This only /// answers "with which certificate". A listener that asks for TLS and finds no certificate in /// either place refuses to bind. /// /// /// /// /// services.AddRedbRouteHttpHosting(o => o.Tls.DefaultCertificatePath = "/certs/server.pfx"); /// /// public sealed class ServerTlsOptions { /// /// Certificate served by any TLS listener that has none of its own. Takes precedence over /// , which is the convenience form of the same thing. /// public System.Security.Cryptography.X509Certificates.X509Certificate2? DefaultCertificate { get; set; } /// Path to a PFX file serving the same role as . public string? DefaultCertificatePath { get; set; } /// Password for . public string? DefaultCertificatePassword { get; set; } /// True when the host can supply a certificate to a listener that has none. internal bool HasDefault => DefaultCertificate is not null || !string.IsNullOrEmpty(DefaultCertificatePath); } Path: redb-route/redb.Route.Http.Hosting/HttpProtocol.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/HttpProtocol.cs ---- namespace redb.Route.Http; /// /// HTTP protocol version for the Kestrel host. Lives in the shared hosting assembly (kept in the /// redb.Route.Http namespace for source compatibility) because both the server manager and the /// HTTP connector's options reference it. /// public enum HttpProtocol { /// HTTP/1.1 only. Http1, /// HTTP/2 only. Requires HTTPS on most clients. Http2, /// HTTP/1.1 and HTTP/2 (default). Negotiated via ALPN. Http1And2, /// HTTP/3 only (QUIC). Requires HTTPS. Http3, /// HTTP/1.1, HTTP/2, and HTTP/3. Http1And2And3 } Path: redb-route/redb.Route.Http.Hosting/README.md 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/README.md ---- # redb.Route.Http.Hosting > Documentation and articles: Shared Kestrel HTTP hosting infrastructure for the [redb.Route](../redb.Route) ESB framework. Provides `SharedHttpServerManager` — a multiplexing HTTP server (one Kestrel per `host:port`, many routes) used by HTTP-based transports (`redb.Route.Http`, `redb.Route.As2`, …). Extracting it here lets those connectors share one server manager **without depending on each other**: register it once with `services.AddRedbRouteHttpHosting()` (idempotent), and every connector resolves the same singleton — so an HTTP route and an AS2 route in the same worker share one Kestrel and never fight over a port. Standalone hosting only — depends on the ASP.NET runtime, not on redb.Route core or any connector. ## How a connector finds the manager Every HTTP-based connector — `http`, `signalr`, `ws`, `soap`, `grpc`, `as2` — resolves it in one order: 1. the manager assigned to the component (`AddRedbRouteHttp()`, `AddRedbRouteSignalR()`, … do this); 2. the `SharedHttpServerManager` the route context was given — `context.Resolve()`, which reads the context's own services (`AddService`) first and then its DI container; 3. what the connector does on its own — a private manager for `signalr`, `ws`, `soap`, `grpc` and `as2`, so a hand-built component stays usable; a refusal for `http`, because an `http:` consumer binds a port and which port it binds is the host's decision. Step 2 is what a module host needs: it builds a context per module and adds components by scanning, so nothing assigns the manager, while the one shared instance is already in the container. It also works the other way round — a host with no container at all can leave the manager on the context itself: ```csharp context.AddService(typeof(SharedHttpServerManager), manager); ``` The lookup is lazy, so the manager may be supplied before or after the components are added. ## TLS: asking for it selects the socket A listener registered with `ssl: true` resolves its server certificate from, in order: 1. the endpoint — `sslCertPath` / `sslCertPassword` on the route URI; 2. a named connection factory, so the password stays out of the URI; 3. the host default set here. ```csharp services.AddRedbRouteHttpHosting(o => o.Tls.DefaultCertificatePath = "/certs/server.pfx"); // or an already-loaded certificate: services.AddRedbRouteHttpHosting(o => o.Tls.DefaultCertificate = cert); ``` This is the shape Camel gives global `SSLContextParameters` and Spring Boot gives SSL bundles: a certificate on the endpoint is an override, not a requirement. Nothing here turns TLS on — `ssl` stays an explicit per-endpoint decision; the host only answers "with which certificate". **A listener that asks for TLS and finds no certificate anywhere refuses to bind.** It does not fall back to a plaintext socket, which is what nginx, httpd, Jetty, Spring Boot and Kestrel's own `UseHttps()` all do, and for the same reason: an open port behind an `https://` banner is not "TLS off", it is a silent downgrade that operators cannot see. ## Trusted proxies Behind a reverse proxy the socket peer is the proxy, and the client's address and scheme travel in `X-Forwarded-For` / `X-Forwarded-Proto`. Which proxies to believe is a property of the process, so it is set once on the host and applies to every listener and every consumer on it: ```csharp services.AddRedbRouteHttpHosting(o => o.TrustedProxies.Add("10.0.0.5").Add("10.1.0.0/16")); // or, constructing the manager by hand: var hosting = new HttpHostingOptions(); hosting.TrustedProxies.Add("10.0.0.5"); var manager = new SharedHttpServerManager(hosting); ``` Rules, in the order they apply: | Situation | Outcome | |---|---| | No proxy listed | Headers ignored, socket peer is the client. The default. | | Peer not in the list | Headers ignored: nothing in them was written by anyone trusted. | | Peer trusted, `X-Forwarded-For` present | Walked from the right past every listed proxy; the first address that is not one is the client. A chain of any length resolves. | | An entry does not parse | The walk stops and the socket peer is kept. Skipping would reach the client-controlled left part. | | Every entry is a trusted proxy | Socket peer kept (a proxy calling through itself, a health check). | | `X-Forwarded-Proto` present, peer trusted | `Request.Scheme` rewritten, read in step with the address; `ForwardScheme = false` turns this off. | The originals are kept in `HttpContext.Items` under `SharedHttpServerManager.OriginalRemoteAddressItem` and `OriginalSchemeItem`. Keep the list to the proxies you operate: a network an attacker can send from lets them choose their own client address. `X-Forwarded-Host` and the RFC 7239 `Forwarded` header are not handled. The walk is `ForwardedHeaderResolver`, a pure function with no `HttpContext` in it, so it can be unit-tested on strings and reused by a host that is not Kestrel. ## Caller identity Who sent a request is decided the same way as which proxies to believe: once for the process, applied to every listener and every consumer on it. ```csharp services.AddRedbRouteHttpHosting(o => o.ResolvePrincipal = ctx => myTokenValidator.ValidateAsync(ctx.Request.Headers.Authorization.ToString())); ``` The resolver returns a `ClaimsPrincipal`, or `null` for an anonymous caller. Build the identity with an authentication type (`new ClaimsIdentity(claims, "Bearer")`): code that reads the principal, the LLM tool claims source among it, treats an identity that is not authenticated as anonymous. The HTTP, gRPC, SOAP, AS2, WebSocket and SignalR consumers put the result on the exchange, and a route reads it with `ExchangePrincipal.Get(exchange)`. That is Camel's `Exchange.AUTHENTICATION` shape: an exchange property, so a caller cannot send it as a header, and every child exchange (a split part, a sub-route, a tool call) inherits it. | Situation | Outcome | |---|---| | No resolver | Nothing runs, exchanges carry no identity. The default. | | Resolver returns a principal | Kept in `HttpContext.Items` under `SharedHttpServerManager.PrincipalItem`, then put on the exchange. | | Resolver returns `null` | The request is served without an identity. Turning anonymous callers away is a route's decision: one port carries routes with different requirements. | | Resolver throws | 500, the route does not run, the error is logged, and the exception text never reaches the caller. A resolver that cannot decide must not downgrade the caller to anonymous; return `null` yourself when that is the right answer. | | CORS preflight | Answered before the resolver runs. | | WebSocket or SignalR with its own `Authenticate` | The transport's hook decides on its paths. | The resolver runs after trusted-proxy resolution, so a check that looks at the address sees the client, not the proxy. Under DI resolver failures go to the host's logger factory; a manager built by hand logs them only when given a logger (`new SharedHttpServerManager(options, logger)`). A component added by hand without a `ServerManager` falls back to a private manager with default options and does not see this setting. ## Endpoints of a component's own Routes go into the route table (`RegisterRoute`). A component that brings ASP.NET endpoints instead, a SignalR hub, a framework's handlers, maps them with `RegisterEndpoints`, onto a listener that may already be serving: ```csharp public sealed class StatusComponent(SharedHttpServerManager manager) : IAsyncDisposable { private ServiceProvider? _services; private EndpointRegistration? _registration; public void Start(string host, int port) { // The component's own container: the listener's is the manager's and stays closed. _services = new ServiceCollection().AddRouting().AddSingleton().BuildServiceProvider(); _registration = manager.RegisterEndpoints(host, port, _services, endpoints => endpoints.MapGet("/status", (StatusSource status) => status.Current()) // A gate of the component's own is an endpoint convention, not middleware. .AddEndpointFilter(async (ctx, next) => IsAllowed(ctx.HttpContext) ? await next(ctx) : Results.StatusCode(403))); } public async ValueTask DisposeAsync() { _registration?.Dispose(); // the endpoints leave the listener if (_services is not null) await _services.DisposeAsync(); } } ``` - `map` runs on an `IEndpointRouteBuilder` whose `ServiceProvider` is the container you pass, so a framework that takes its pieces from there (`MapHub`, `MapConnections`) builds them from your container. - Every request to those endpoints runs in a scope of that container: `HttpContext.RequestServices` and minimal API parameters resolve from it. - The endpoints join a running listener through endpoint routing and leave it the same way when the registration is disposed; the connections the listener already serves are not touched. A literal path of theirs wins over the route table, whose catch-all comes last. - A registration occupies the listener like a route: the listener stays up while any route or registration is on it. - A registration brings no middleware. The pipeline (trusted proxies, CORS, the caller's principal, WebSocket upgrades) is fixed when the listener starts; the first route or registration on a port decides its TLS. Every listener accepts WebSocket upgrades (`UseWebSockets` is part of every pipeline and acts on upgrade requests only), so endpoints mapped later can accept sockets. `EnableWebSockets(host, port, keepAlive)` sets the keep-alive of a listener that has not started yet. Part of the redb.Route family. Path: redb-route/redb.Route.Http.Hosting/SharedEndpoints.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/SharedEndpoints.cs ---- using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Primitives; namespace redb.Route.Http; /// /// Endpoints a transport mapped onto a shared listener with /// : framework endpoints of its own (a SignalR hub, a gRPC /// service, minimal API handlers) served from a service container of its own. Holding the registration keeps the /// listener alive; disposing it removes the endpoints from the running listener, and the listener stops once nothing /// occupies it any more. /// public sealed class EndpointRegistration : IDisposable { private readonly SharedHttpServerManager _manager; private int _disposed; internal EndpointRegistration(SharedHttpServerManager manager, string host, int port, IServiceProvider services, IReadOnlyList endpoints) { _manager = manager; Host = host; Port = port; Services = services; Endpoints = endpoints; } /// Bind host of the listener the endpoints are on. public string Host { get; } /// Bind port of the listener the endpoints are on. public int Port { get; } /// The container the endpoints were mapped with and that serves their requests. public IServiceProvider Services { get; } /// The endpoints, as the listener serves them. public IReadOnlyList Endpoints { get; } /// Removes the endpoints from the listener. Disposing twice is safe. public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) _manager.UnregisterEndpoints(this); } } /// /// The a registration maps on: its services are the registration's container, so /// a framework that resolves its pieces from (MapHub, MapConnections, MapGrpcService) /// takes them from there and not from the listener. /// internal sealed class RegistrationRouteBuilder(IServiceProvider services) : IEndpointRouteBuilder { public IServiceProvider ServiceProvider { get; } = services; public ICollection DataSources { get; } = new List(); public IApplicationBuilder CreateApplicationBuilder() => new ApplicationBuilder(ServiceProvider); /// /// The mapped endpoints, each served in a request scope of the registration's container: a handler, a hub /// (Context.GetHttpContext().RequestServices) or minimal API parameter binding sees the services the /// endpoints were mapped with. /// public IReadOnlyList Build() { var scopes = ServiceProvider.GetRequiredService(); return DataSources.SelectMany(source => source.Endpoints).Select(endpoint => endpoint is RouteEndpoint route && route.RequestDelegate is { } handler ? new RouteEndpoint(InScope(handler, scopes), route.RoutePattern, route.Order, route.Metadata, route.DisplayName) : endpoint).ToArray(); } private static RequestDelegate InScope(RequestDelegate handler, IServiceScopeFactory scopes) => async context => { var listenerServices = context.RequestServices; await using var scope = scopes.CreateAsyncScope(); context.RequestServices = scope.ServiceProvider; try { await handler(context).ConfigureAwait(false); } finally { context.RequestServices = listenerServices; } }; } /// /// The endpoints of the registrations of one listener, added and removed while it runs: endpoint routing watches the /// change token and rebuilds its matcher, so a registration reaches a running listener without touching the /// connections it already serves. /// internal sealed class DynamicEndpointSource : EndpointDataSource { private readonly object _gate = new(); private readonly List _registrations = []; private Endpoint[] _endpoints = []; private CancellationTokenSource _changed = new(); public int Count { get { lock (_gate) return _registrations.Count; } } public void Add(EndpointRegistration registration) => Change(() => _registrations.Add(registration)); public bool Remove(EndpointRegistration registration) { var removed = false; Change(() => removed = _registrations.Remove(registration)); return removed; } private void Change(Action change) { CancellationTokenSource previous; lock (_gate) { change(); _endpoints = _registrations.SelectMany(r => r.Endpoints).ToArray(); previous = _changed; _changed = new CancellationTokenSource(); } previous.Cancel(); previous.Dispose(); } public override IReadOnlyList Endpoints => Volatile.Read(ref _endpoints); public override IChangeToken GetChangeToken() { lock (_gate) return new CancellationChangeToken(_changed.Token); } } 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); Path: redb-route/redb.Route.Http.Hosting/TrustedProxyOptions.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/TrustedProxyOptions.cs ---- using System.Net; namespace redb.Route.Http; /// /// The set of reverse proxies the shared Kestrel host trusts to speak for the client. /// /// /// /// A proxy chain is a property of the process, not of a module or a route: two routes on one /// port never sit behind different proxies. So the list lives on the host, next to TLS and the /// protocol set, and every HTTP-based transport on that host (Http, Soap, As2, Grpc, the Tsak /// management API) sees the resolved client address without doing anything itself. /// /// /// Secure by default: with no entries the host ignores X-Forwarded-For and /// X-Forwarded-Proto entirely and the socket peer is the client. Add exactly the addresses /// or networks of the proxies you operate. A list that is too wide (a whole cloud range where an /// attacker can rent a machine) hands that attacker the right to choose its own client address. /// /// public sealed class TrustedProxyOptions { /// Individual addresses of trusted reverse proxies. public List KnownProxies { get; } = new(); /// CIDR networks of trusted reverse proxies. public List KnownNetworks { get; } = new(); /// /// Rewrite the request scheme from X-Forwarded-Proto when the peer is trusted. On by /// default: behind a TLS-terminating proxy the URL a route sees (redbHttp.Url) must be /// the one the client used, or anything that compares against it (DPoP htu, SCIM /// Location, redirect URIs) compares against the wrong origin. /// public bool ForwardScheme { get; set; } = true; /// True when at least one proxy or network is listed. public bool IsEnabled => KnownProxies.Count > 0 || KnownNetworks.Count > 0; /// /// Adds a trusted proxy given as a bare address (10.0.0.5, ::1) or a CIDR /// network (10.0.0.0/8). The form is decided by the presence of a slash. /// /// The value is neither an address nor a CIDR network. public TrustedProxyOptions Add(string addressOrNetwork) { ArgumentException.ThrowIfNullOrWhiteSpace(addressOrNetwork); var value = addressOrNetwork.Trim(); if (value.Contains('/')) { if (!IPNetwork.TryParse(value, out var network)) throw new FormatException($"'{value}' is not a valid CIDR network."); KnownNetworks.Add(network); return this; } if (!IPAddress.TryParse(value, out var address)) throw new FormatException($"'{value}' is not a valid IP address."); KnownProxies.Add(Normalize(address)); return this; } /// /// Whether belongs to a trusted proxy. IPv4-mapped IPv6 addresses /// (::ffff:10.0.0.5, which is how a dual-stack socket reports an IPv4 peer) compare as /// their IPv4 form, so a list written in IPv4 matches either way. /// public bool IsTrusted(IPAddress address) { ArgumentNullException.ThrowIfNull(address); var ip = Normalize(address); foreach (var known in KnownProxies) { if (known.Equals(ip)) return true; } foreach (var network in KnownNetworks) { if (network.Contains(ip)) return true; } return false; } /// /// Folds an IPv4-mapped IPv6 address to its IPv4 form; any other address is returned as is. /// Public so a caller building the list from values, rather than /// through , can store them in the same form compares. /// public static IPAddress Normalize(IPAddress address) => address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address; } Path: redb-route/redb.Route.Http.Hosting/redb.Route.Http.Hosting.csproj 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/redb.Route.Http.Hosting.csproj ---- redb.Route.Http.Hosting Shared Kestrel HTTP hosting infrastructure for redb.Route: a multiplexing server manager used by HTTP-based transports (redb.Route.Http, redb.Route.As2, ...). esb;http;kestrel;hosting;redb README.md