Bundle: redb-route / tests/redb.Route.Tests.Http (tests.redb.Route.Tests.Http.txt), 36 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/tests/redb.Route.Tests.Http/CorsDispatchTests.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/tests/redb.Route.Tests.Http/CorsDispatchTests.cs
----
using System.Net;
using Microsoft.AspNetCore.Http;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// Tests for the per-route CORS dispatch middleware in .
/// Verifies the contract introduced in C15 (Sprint C):
///
/// - resolver delegate wins over the static whitelist;
/// - multi-origin CSV is matched against the request Origin, never echoed verbatim;
/// - Vary: Origin is always emitted whenever CORS headers are present;
/// - preflight (OPTIONS) reflects the request's Access-Control-Request-Headers/-Method;
/// - wildcard * combined with credentials is demoted to "no headers" at request time;
/// - two routes on the same (host, port) with different policies do not collide.
///
///
[Collection("HttpServer")]
public class CorsDispatchTests : IAsyncLifetime
{
private SharedHttpServerManager _serverManager = null!;
private HttpClient _client = null!;
private int _port;
private readonly List _registrations = [];
public Task InitializeAsync()
{
_port = GetFreePort();
_serverManager = new SharedHttpServerManager();
_client = new HttpClient();
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
_client.Dispose();
foreach (var reg in _registrations)
_serverManager.UnregisterRoute(reg);
await _serverManager.DisposeAsync();
}
private async Task RegisterAsync(string path, RouteCorsOptions cors, string? methods = null)
{
var reg = _serverManager.RegisterRoute(
"127.0.0.1", _port, path, methods,
ctx => { ctx.Response.StatusCode = 200; return Task.CompletedTask; },
corsOptions: cors);
_registrations.Add(reg);
await _serverManager.EnsureStarted("127.0.0.1", _port);
return reg;
}
// ── Static whitelist ──
[Fact]
public async Task SingleOrigin_Echoes_Origin_AndAddsVary()
{
await RegisterAsync("/webhook", new RouteCorsOptions(
AllowedOrigins: "https://example.com",
AllowedMethods: null,
AllowCredentials: false));
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/webhook");
req.Headers.Add("Origin", "https://example.com");
var res = await _client.SendAsync(req);
res.StatusCode.Should().Be(HttpStatusCode.OK);
res.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be("https://example.com");
res.Headers.GetValues("Vary").Should().Contain(v => v.Contains("Origin"));
}
[Fact]
public async Task SingleOrigin_OriginNotAllowed_NoCorsHeaders()
{
await RegisterAsync("/webhook", new RouteCorsOptions(
AllowedOrigins: "https://example.com",
AllowedMethods: null,
AllowCredentials: false));
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/webhook");
req.Headers.Add("Origin", "https://evil.com");
var res = await _client.SendAsync(req);
// Request still succeeds (the server must not 4xx unallowed origins on simple requests --
// it's the browser's job to reject). But no CORS headers are emitted, so the browser will
// refuse to expose the response to the calling page.
res.StatusCode.Should().Be(HttpStatusCode.OK);
res.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse();
}
[Fact]
public async Task MultiOrigin_Csv_MatchesAndEchoesSingle()
{
await RegisterAsync("/webhook", new RouteCorsOptions(
AllowedOrigins: "https://a.com, https://b.com, https://c.com",
AllowedMethods: null,
AllowCredentials: false));
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/webhook");
req.Headers.Add("Origin", "https://b.com");
var res = await _client.SendAsync(req);
// Browsers cannot consume a CSV in Access-Control-Allow-Origin -- the dispatch must
// single-select and echo back exactly the matching origin.
res.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be("https://b.com");
res.Headers.GetValues("Vary").Should().Contain(v => v.Contains("Origin"));
}
// ── Resolver delegate ──
[Fact]
public async Task Resolver_TakesPrecedence_OverStaticWhitelist()
{
Func resolver = _ => "https://from-resolver.com";
await RegisterAsync("/webhook", new RouteCorsOptions(
AllowedOrigins: "https://from-static.com",
AllowedMethods: null,
AllowCredentials: false,
OriginsResolver: resolver));
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/webhook");
req.Headers.Add("Origin", "https://from-static.com");
var res = await _client.SendAsync(req);
res.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be("https://from-resolver.com");
}
[Fact]
public async Task Resolver_ReturnsNull_NoCorsHeaders()
{
Func resolver = _ => null;
await RegisterAsync("/webhook", new RouteCorsOptions(
AllowedOrigins: null,
AllowedMethods: null,
AllowCredentials: false,
OriginsResolver: resolver));
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/webhook");
req.Headers.Add("Origin", "https://anything.com");
var res = await _client.SendAsync(req);
res.StatusCode.Should().Be(HttpStatusCode.OK);
res.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse();
}
[Fact]
public async Task Resolver_ReceivesActualRequest()
{
// Capture extracted values, not the HttpRequest itself -- Kestrel pools HttpContext
// and the request features become disposed once the response completes.
string? capturedPath = null;
string? capturedMethod = null;
string? capturedOrigin = null;
Func resolver = req =>
{
capturedPath = req.Path.Value;
capturedMethod = req.Method;
capturedOrigin = req.Headers["Origin"];
return capturedOrigin;
};
await RegisterAsync("/webhook", new RouteCorsOptions(
AllowedOrigins: null,
AllowedMethods: null,
AllowCredentials: false,
OriginsResolver: resolver));
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/webhook");
req.Headers.Add("Origin", "https://app.example.com");
await _client.SendAsync(req);
capturedPath.Should().Be("/webhook");
capturedMethod.Should().Be("GET");
capturedOrigin.Should().Be("https://app.example.com");
}
// ── Preflight reflection ──
[Fact]
public async Task Preflight_EchoesRequestedHeadersAndMethod()
{
await RegisterAsync("/webhook", new RouteCorsOptions(
AllowedOrigins: "https://app.com",
AllowedMethods: "GET,POST",
AllowCredentials: false),
methods: "GET,POST");
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Options, $"http://127.0.0.1:{_port}/webhook");
req.Headers.Add("Origin", "https://app.com");
req.Headers.Add("Access-Control-Request-Method", "POST");
req.Headers.Add("Access-Control-Request-Headers", "Authorization, X-Custom");
var res = await _client.SendAsync(req);
res.StatusCode.Should().Be(HttpStatusCode.NoContent);
res.Headers.GetValues("Access-Control-Allow-Methods").Single().Should().Be("POST");
res.Headers.GetValues("Access-Control-Allow-Headers").Single().Should().Be("Authorization, X-Custom");
res.Headers.GetValues("Access-Control-Max-Age").Single().Should().Be("86400");
}
[Fact]
public async Task Preflight_DisallowedOrigin_Returns204_NoCorsHeaders()
{
await RegisterAsync("/webhook", new RouteCorsOptions(
AllowedOrigins: "https://app.com",
AllowedMethods: null,
AllowCredentials: false));
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Options, $"http://127.0.0.1:{_port}/webhook");
req.Headers.Add("Origin", "https://evil.com");
req.Headers.Add("Access-Control-Request-Method", "POST");
var res = await _client.SendAsync(req);
// Preflight must always 204 (browser-friendly), but no Allow-Origin tells the browser
// to fail the actual request without retrying.
res.StatusCode.Should().Be(HttpStatusCode.NoContent);
res.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse();
}
// ── Wildcard + credentials guard ──
[Fact]
public async Task Wildcard_WithCredentials_DemotedToNoHeaders()
{
// Static-whitelist case: validation in HttpEndpointOptions blocks this at config time
// for the consumer-API path, but RouteCorsOptions is also reachable directly via
// SharedHttpServerManager.RegisterRoute, so the request-time guard is the last line of
// defence. We test a resolver that returns "*" to exercise that path.
Func resolver = _ => "*";
await RegisterAsync("/webhook", new RouteCorsOptions(
AllowedOrigins: null,
AllowedMethods: null,
AllowCredentials: true,
OriginsResolver: resolver));
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/webhook");
req.Headers.Add("Origin", "https://app.com");
var res = await _client.SendAsync(req);
res.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse();
res.Headers.Contains("Access-Control-Allow-Credentials").Should().BeFalse();
}
// ── Per-route dispatch ──
[Fact]
public async Task TwoRoutes_SamePort_DifferentPolicies_DoNotCollide()
{
// Route A: public wildcard
await RegisterAsync("/public", new RouteCorsOptions(
AllowedOrigins: "*",
AllowedMethods: null,
AllowCredentials: false));
// Route B: strict whitelist with credentials
await RegisterAsync("/private", new RouteCorsOptions(
AllowedOrigins: "https://trusted.com",
AllowedMethods: null,
AllowCredentials: true));
var pub = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/public");
pub.Headers.Add("Origin", "https://anything.com");
var pubRes = await _client.SendAsync(pub);
pubRes.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be("*");
pubRes.Headers.Contains("Access-Control-Allow-Credentials").Should().BeFalse();
var priv = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/private");
priv.Headers.Add("Origin", "https://trusted.com");
var privRes = await _client.SendAsync(priv);
privRes.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be("https://trusted.com");
privRes.Headers.GetValues("Access-Control-Allow-Credentials").Single().Should().Be("true");
// Route B from an untrusted origin: no CORS headers, even though Route A on the same
// port would have allowed any origin. This is the bug-fix the per-route dispatcher closes.
var privEvil = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/private");
privEvil.Headers.Add("Origin", "https://evil.com");
var privEvilRes = await _client.SendAsync(privEvil);
privEvilRes.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse();
}
[Fact]
public async Task RouteWithoutCors_DoesNotEmitHeaders_EvenWhenSiblingHasCors()
{
// Sibling on the same port enables CORS, which causes the dispatch middleware to be
// installed -- but the no-CORS route must remain transparent (no headers emitted).
await RegisterAsync("/with-cors", new RouteCorsOptions(
AllowedOrigins: "*",
AllowedMethods: null,
AllowCredentials: false));
var noCors = _serverManager.RegisterRoute(
"127.0.0.1", _port, "/no-cors", null,
ctx => { ctx.Response.StatusCode = 200; return Task.CompletedTask; });
_registrations.Add(noCors);
await _serverManager.EnsureStarted("127.0.0.1", _port);
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/no-cors");
req.Headers.Add("Origin", "https://anything.com");
var res = await _client.SendAsync(req);
res.StatusCode.Should().Be(HttpStatusCode.OK);
res.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse();
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/ForwardedHeaderResolverTests.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/tests/redb.Route.Tests.Http/ForwardedHeaderResolverTests.cs
----
using System.Net;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// Pure tests for : the trust model on strings, with no
/// Kestrel involved. The host-level behaviour (the resolved address and scheme reaching the
/// exchange) is covered by .
///
public class ForwardedHeaderResolverTests
{
private static readonly IPAddress Peer = IPAddress.Parse("10.0.0.1");
private static readonly IPAddress Client = IPAddress.Parse("203.0.113.7");
private static TrustedProxyOptions Trust(params string[] entries)
{
var t = new TrustedProxyOptions();
foreach (var e in entries) t.Add(e);
return t;
}
// ── Trust gate ──
[Fact]
public void NoTrustedProxies_HeaderIgnored_PeerIsClient()
{
var r = ForwardedHeaderResolver.Resolve(Peer, "203.0.113.7", "https", new TrustedProxyOptions());
r.ClientAddress.Should().Be(Peer);
r.AddressApplied.Should().BeFalse();
r.Scheme.Should().BeNull();
}
[Fact]
public void UntrustedPeer_HeaderIgnored_EvenWithTrustListPresent()
{
// The peer is not in the list: nothing in the header was written by a proxy we trust.
var r = ForwardedHeaderResolver.Resolve(Peer, "203.0.113.7", "https", Trust("192.168.1.1"));
r.ClientAddress.Should().Be(Peer);
r.AddressApplied.Should().BeFalse();
r.Scheme.Should().BeNull();
}
[Fact]
public void NullPeer_NothingApplies()
{
var r = ForwardedHeaderResolver.Resolve(null, "203.0.113.7", "https", Trust("10.0.0.1"));
r.ClientAddress.Should().BeNull();
r.AddressApplied.Should().BeFalse();
}
// ── Walking the chain ──
[Fact]
public void TrustedPeer_SingleHop_RightmostIsClient()
{
var r = ForwardedHeaderResolver.Resolve(Peer, "203.0.113.7", null, Trust("10.0.0.1"));
r.ClientAddress.Should().Be(Client);
r.AddressApplied.Should().BeTrue();
r.TrustedHops.Should().Be(0);
}
[Fact]
public void TrustedPeer_TwoTrustedHops_SkipsProxyAndFindsClient()
{
// client -> edge (10.0.0.9) -> nginx (10.0.0.1, the socket peer) -> us.
// nginx appended the edge's address, so the right-most entry is a proxy, not the client.
var r = ForwardedHeaderResolver.Resolve(Peer, "203.0.113.7, 10.0.0.9", null, Trust("10.0.0.1", "10.0.0.9"));
r.ClientAddress.Should().Be(Client);
r.AddressApplied.Should().BeTrue();
r.TrustedHops.Should().Be(1);
}
[Fact]
public void TrustedPeer_ClientSpoofsTrustedAddressOnTheLeft_DoesNotWin()
{
// The client sent "1.2.3.4, 10.0.0.9" itself; the edge appended the client's real address.
// Walking from the right meets the real client before any client-supplied entry.
var r = ForwardedHeaderResolver.Resolve(Peer, "1.2.3.4, 10.0.0.9, 203.0.113.7", null, Trust("10.0.0.1", "10.0.0.9"));
r.ClientAddress.Should().Be(Client);
}
[Fact]
public void TrustedPeer_ChainEntirelyTrusted_KeepsSocketPeer()
{
var r = ForwardedHeaderResolver.Resolve(Peer, "10.0.0.9", "https", Trust("10.0.0.1", "10.0.0.9"));
r.ClientAddress.Should().Be(Peer);
r.AddressApplied.Should().BeFalse();
r.Scheme.Should().Be("https", "the scheme still comes from a trusted proxy");
}
[Fact]
public void TrustedPeer_UnparseableHop_StopsAndKeepsSocketPeer()
{
// "unknown" is a legal RFC 7239 identifier a proxy may emit. It must end the walk, not be
// skipped: skipping would reach "203.0.113.7", which here is client-supplied.
var r = ForwardedHeaderResolver.Resolve(Peer, "203.0.113.7, unknown", "https", Trust("10.0.0.1"));
r.ClientAddress.Should().Be(Peer);
r.AddressApplied.Should().BeFalse();
r.Scheme.Should().BeNull("a malformed chain is not trusted for anything");
}
[Fact]
public void TrustedPeer_EmptyHeader_KeepsSocketPeer()
{
var r = ForwardedHeaderResolver.Resolve(Peer, " ", null, Trust("10.0.0.1"));
r.ClientAddress.Should().Be(Peer);
r.AddressApplied.Should().BeFalse();
}
// ── Address forms ──
[Theory]
[InlineData("203.0.113.7:51234", "203.0.113.7")]
[InlineData("[2001:db8::1]:443", "2001:db8::1")]
[InlineData("2001:db8::1", "2001:db8::1")]
[InlineData("::ffff:203.0.113.7", "203.0.113.7")]
public void Hop_Forms_ParseToBareAddress(string hop, string expected)
{
var r = ForwardedHeaderResolver.Resolve(Peer, hop, null, Trust("10.0.0.1"));
r.ClientAddress.Should().Be(IPAddress.Parse(expected));
r.AddressApplied.Should().BeTrue();
}
[Fact]
public void Ipv4MappedPeer_MatchesIpv4TrustEntry()
{
// A dual-stack socket reports an IPv4 peer as ::ffff:a.b.c.d.
var mapped = IPAddress.Parse("::ffff:10.0.0.1");
var r = ForwardedHeaderResolver.Resolve(mapped, "203.0.113.7", null, Trust("10.0.0.1"));
r.ClientAddress.Should().Be(Client);
r.AddressApplied.Should().BeTrue();
}
[Fact]
public void KnownNetworks_CidrMatchesPeerAndHops()
{
var r = ForwardedHeaderResolver.Resolve(Peer, "203.0.113.7, 10.0.5.5", null, Trust("10.0.0.0/8"));
r.ClientAddress.Should().Be(Client);
r.TrustedHops.Should().Be(1);
}
// ── Scheme ──
[Fact]
public void Scheme_SingleValue_UsedAsIs()
{
var r = ForwardedHeaderResolver.Resolve(Peer, "203.0.113.7", "HTTPS", Trust("10.0.0.1"));
r.Scheme.Should().Be("https");
}
[Fact]
public void Scheme_ReadInStepWithTrustedHops()
{
// Edge terminated TLS and wrote "https"; nginx wrote its own inbound "http". With one
// trusted hop skipped, the scheme one position from the right is the edge's.
var r = ForwardedHeaderResolver.Resolve(Peer, "203.0.113.7, 10.0.0.9", "https, http", Trust("10.0.0.1", "10.0.0.9"));
r.Scheme.Should().Be("https");
}
[Fact]
public void Scheme_UnknownValue_Ignored()
{
var r = ForwardedHeaderResolver.Resolve(Peer, "203.0.113.7", "gopher", Trust("10.0.0.1"));
r.Scheme.Should().BeNull();
r.ClientAddress.Should().Be(Client, "an odd scheme does not invalidate the address");
}
// ── Options ──
[Fact]
public void Add_RejectsGarbage()
{
var t = new TrustedProxyOptions();
var act = () => t.Add("not-an-address");
act.Should().Throw();
t.IsEnabled.Should().BeFalse();
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpBuilderTests.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/tests/redb.Route.Tests.Http/HttpBuilderTests.cs
----
using redb.Route.Core;
using redb.Route.Expressions;
using HttpDsl = redb.Route.Http.Http;
using HttpsDsl = redb.Route.Http.Https;
namespace redb.Route.Tests.Http;
public class HttpBuilderTests
{
private static ConstantExpression C(string s) => new(s);
// ── Factory methods ─────────────────────────────────────────────
[Fact]
public void Get_SetsMethodParam()
{
var uri = HttpDsl.Get("api.example.com/users").Build();
uri.Should().Contain("method=GET");
}
[Fact]
public void Post_SetsMethodParam()
{
var uri = HttpDsl.Post("api.example.com/users").Build();
uri.Should().Contain("method=POST");
}
[Fact]
public void Put_SetsMethodParam()
{
var uri = HttpDsl.Put("api.example.com/users/1").Build();
uri.Should().Contain("method=PUT");
}
[Fact]
public void Delete_SetsMethodParam()
{
var uri = HttpDsl.Delete("api.example.com/users/1").Build();
uri.Should().Contain("method=DELETE");
}
[Fact]
public void Patch_SetsMethodParam()
{
var uri = HttpDsl.Patch("api.example.com/users/1").Build();
uri.Should().Contain("method=PATCH");
}
[Fact]
public void Listen_HasNoMethodParam()
{
var uri = HttpDsl.Listen("/webhook").Build();
uri.Should().NotContain("method=");
}
[Fact]
public void NullPath_Throws()
{
var act = () => HttpDsl.Get(null!);
act.Should().Throw();
}
// ── Scheme ──────────────────────────────────────────────────────
[Fact]
public void Http_StartsWithHttpScheme()
{
var uri = HttpDsl.Get("api.example.com").Build();
uri.Should().StartWith("http:");
}
[Fact]
public void Https_StartsWithHttpsScheme()
{
var uri = HttpsDsl.Get("api.example.com").Build();
uri.Should().StartWith("https:");
}
// ── Common params ───────────────────────────────────────────────
[Fact]
public void Timeout_SetsParam()
{
var uri = HttpDsl.Get("api.example.com").Timeout(5000).Build();
uri.Should().Contain("timeout=5000");
}
[Fact]
public void ContentType_SetsParam()
{
var uri = HttpDsl.Post("api.example.com").ContentType("text/xml").Build();
uri.Should().Contain("contentType=text%2Fxml");
}
// ── Producer params ─────────────────────────────────────────────
[Fact]
public void BasicAuth_SetsParams()
{
var uri = HttpDsl.Get("api.example.com").BasicAuth(C("user"), C("pass")).Build();
uri.Should().Contain("authScheme=Basic");
uri.Should().Contain("username=user");
uri.Should().Contain("password=pass");
}
[Fact]
public void BearerAuth_SetsScheme()
{
var uri = HttpDsl.Get("api.example.com").BearerAuth().Build();
uri.Should().Contain("authScheme=Bearer");
}
[Fact]
public void NoThrowOnError_SetsParam()
{
var uri = HttpDsl.Get("api.example.com").NoThrowOnError().Build();
uri.Should().Contain("throwOnError=false");
}
[Fact]
public void NoFollowRedirects_SetsParam()
{
var uri = HttpDsl.Get("api.example.com").NoFollowRedirects().Build();
uri.Should().Contain("followRedirects=false");
}
[Fact]
public void MaxRedirects_SetsParam()
{
var uri = HttpDsl.Get("api.example.com").MaxRedirects(10).Build();
uri.Should().Contain("maxRedirects=10");
}
[Fact]
public void PreserveHostHeader_SetsParam()
{
var uri = HttpDsl.Get("api.example.com").PreserveHostHeader().Build();
uri.Should().Contain("preserveHostHeader=true");
}
// ── Consumer params ─────────────────────────────────────────────
[Fact]
public void Host_SetsParam()
{
var uri = HttpDsl.Listen("/api").Host(C("127.0.0.1")).Build();
uri.Should().Contain("host=127.0.0.1");
}
[Fact]
public void Port_SetsParam()
{
var uri = HttpDsl.Listen("/api").Port(9090).Build();
uri.Should().Contain("port=9090");
}
[Fact]
public void Methods_SetsParam()
{
var uri = HttpDsl.Listen("/api").Methods("POST,PUT").Build();
uri.Should().Contain("methods=POST%2CPUT");
}
[Fact]
public void Cors_SetsParam()
{
var uri = HttpDsl.Listen("/api").Cors().Build();
uri.Should().Contain("cors=true");
}
[Fact]
public void CorsWithOrigins_SetsBothParams()
{
var uri = HttpDsl.Listen("/api").Cors("https://example.com").Build();
uri.Should().Contain("cors=true");
uri.Should().Contain("corsOrigins=");
}
[Fact]
public void SslCert_SetsParams()
{
var uri = HttpDsl.Listen("/api").SslCert(C("cert.pfx"), C("pass")).Build();
uri.Should().Contain("ssl=true");
uri.Should().Contain("sslCertPath=cert.pfx");
uri.Should().Contain("sslCertPassword=pass");
}
[Fact]
public void InOut_SetsParam()
{
var uri = HttpDsl.Listen("/api").InOut().Build();
uri.Should().Contain("inOut=true");
}
[Fact]
public void StreamRequest_SetsParam()
{
var uri = HttpDsl.Listen("/api").StreamRequest().Build();
uri.Should().Contain("streamRequest=true");
}
[Fact]
public void StreamResponse_SetsParam()
{
var uri = HttpDsl.Get("api.example.com/data").StreamResponse().Build();
uri.Should().Contain("streamResponse=true");
}
[Fact]
public void StreamResponse_RoundTrip()
{
var original = HttpDsl.Get("api.example.com/data").StreamResponse().Build();
var parsed = EndpointUriParser.Parse(original);
parsed.RawParameters["streamResponse"].Should().Be("true");
}
[Fact]
public void ResponseCode_SetsParam()
{
var uri = HttpDsl.Listen("/api").ResponseCode(202).Build();
uri.Should().Contain("responseCode=202");
}
// ── Conversion ──────────────────────────────────────────────────
[Fact]
public void ImplicitConversion_ReturnsUri()
{
string uri = HttpDsl.Post("api.example.com/data").Timeout(5000);
uri.Should().StartWith("http:api.example.com/data?");
}
[Fact]
public void ToString_ReturnsSameAsBuild()
{
var builder = HttpDsl.Get("api.example.com").BasicAuth(C("u"), C("p"));
builder.ToString().Should().Be(builder.Build());
}
// ── Full chains ─────────────────────────────────────────────────
[Fact]
public void FullProducerChain_BuildsCorrectUri()
{
var uri = HttpsDsl.Post("api.example.com/submit")
.ContentType("application/xml")
.Timeout(10000)
.BasicAuth(C("admin"), C("secret"))
.Build();
uri.Should().StartWith("https:api.example.com/submit?");
uri.Should().Contain("method=POST");
uri.Should().Contain("contentType=application%2Fxml");
uri.Should().Contain("timeout=10000");
uri.Should().Contain("authScheme=Basic");
}
[Fact]
public void FullConsumerChain_BuildsCorrectUri()
{
var uri = HttpDsl.Listen("/webhook")
.Port(8080)
.Cors("*")
.InOut()
.Build();
uri.Should().StartWith("http:/webhook?");
uri.Should().NotContain("method=");
uri.Should().Contain("port=8080");
uri.Should().Contain("cors=true");
uri.Should().Contain("inOut=true");
}
// ── Round-trip ──────────────────────────────────────────────────
[Fact]
public void RoundTrip_ParseAndReconstruct()
{
var original = HttpDsl.Get("api.example.com/data").Timeout(5000).Build();
var parsed = EndpointUriParser.Parse(original);
parsed.Scheme.Should().Be("http");
parsed.Path.Should().Be("api.example.com/data");
parsed.RawParameters["method"].Should().Be("GET");
parsed.RawParameters["timeout"].Should().Be("5000");
}
// ── Producer Host/Port ──────────────────────────────────────────
[Fact]
public void Producer_Host_EmbedsInUrl()
{
var uri = HttpDsl.Post("/orders").Host(C("api.example.com")).Build();
uri.Should().StartWith("http:api.example.com/orders?");
uri.Should().Contain("method=POST");
uri.Should().NotContain("host=");
}
[Fact]
public void Producer_HostAndPort_EmbedsInUrl()
{
var uri = HttpDsl.Post("/orders").Host(C("api.example.com")).Port(9090).Build();
uri.Should().StartWith("http:api.example.com:9090/orders?");
uri.Should().NotContain("host=");
uri.Should().NotContain("port=");
}
[Fact]
public void Producer_HostOnly_NoPortInUrl()
{
var uri = HttpDsl.Get("/status").Host(C("api.example.com")).Build();
uri.Should().StartWith("http:api.example.com/status?");
// No port segment between host and path
uri.Should().NotContain("api.example.com:/");
}
[Fact]
public void Producer_HostWithExpressionPort_EmbedsInUrl()
{
var uri = HttpDsl.Post("/orders").Host(C("api.example.com")).Port(C("${header.port}")).Build();
uri.Should().StartWith("http:api.example.com:${header.port}/orders?");
}
[Fact]
public void Producer_ExpressionHost_EmbedsInUrl()
{
var uri = HttpDsl.Put("/api/data").Host(C("${header.targetHost}")).Build();
uri.Should().StartWith("http:${header.targetHost}/api/data?");
}
[Fact]
public void Producer_ExpressionHostAndPort_EmbedsInUrl()
{
var uri = HttpDsl.Post("/api").Host(C("${property.host}")).Port(C("${property.port}")).Build();
uri.Should().StartWith("http:${property.host}:${property.port}/api?");
}
[Fact]
public void Producer_HostWithPathNoSlash_AddsSlash()
{
var uri = HttpDsl.Post("orders").Host(C("api.example.com")).Build();
uri.Should().StartWith("http:api.example.com/orders?");
}
[Fact]
public void Consumer_HostPort_StillQueryParams()
{
var uri = HttpDsl.Listen("/webhook").Host(C("0.0.0.0")).Port(8080).Build();
uri.Should().StartWith("http:/webhook?");
uri.Should().Contain("host=0.0.0.0");
uri.Should().Contain("port=8080");
}
[Fact]
public void Producer_HostPort_RoundTrip()
{
var original = HttpDsl.Post("/orders").Host(C("api.example.com")).Port(443).Build();
var parsed = EndpointUriParser.Parse(original);
parsed.Scheme.Should().Be("http");
parsed.Path.Should().Be("api.example.com:443/orders");
parsed.RawParameters["method"].Should().Be("POST");
}
[Fact]
public void Https_Producer_HostPort_EmbedsInUrl()
{
var uri = HttpsDsl.Post("/secure").Host(C("api.example.com")).Port(8443).Build();
uri.Should().StartWith("https:api.example.com:8443/secure?");
}
// ── Query Parameters (.Param) ──────────────────────────────────
[Fact]
public void Param_ConstantValue_SetsParamInUri()
{
var uri = HttpDsl.Post("api.example.com/users")
.Param("format", "json")
.Build();
uri.Should().Contain("param.format=json");
}
[Fact]
public void Param_WithExpression_SetsTemplateString()
{
var uri = HttpDsl.Post("api.example.com/users")
.Param("userId", new HeaderExpression("userId"))
.Build();
uri.Should().Contain("param.userId=%24%7Bheader.userId%7D");
}
[Fact]
public void Param_WithConstantExpression_SetsValue()
{
var uri = HttpDsl.Post("api.example.com/users")
.Param("limit", C("100"))
.Build();
uri.Should().Contain("param.limit=100");
}
[Fact]
public void Param_MultipleParams_AllPresent()
{
var uri = HttpDsl.Get("api.example.com/search")
.Param("q", "test")
.Param("page", 1)
.Param("sort", new HeaderExpression("sortField"))
.Build();
uri.Should().Contain("param.q=test");
uri.Should().Contain("param.page=1");
uri.Should().Contain("param.sort=%24%7Bheader.sortField%7D");
}
[Fact]
public void Param_NullValue_SetsEmptyString()
{
var uri = HttpDsl.Post("api.example.com/data")
.Param("key", (object?)null)
.Build();
uri.Should().Contain("param.key=");
}
[Fact]
public void Param_Chainable()
{
var builder = HttpDsl.Get("api.example.com/data");
var result = builder.Param("x", "1");
result.Should().BeSameAs(builder);
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpComponentTests.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/tests/redb.Route.Tests.Http/HttpComponentTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using HttpMethod = redb.Route.Http.HttpMethod;
using HttpDsl = redb.Route.Http.Http;
namespace redb.Route.Tests.Http;
public class HttpComponentTests
{
[Fact]
public void Scheme_ReturnsHttp()
{
var component = new HttpComponent();
component.Scheme.Should().Be("http");
}
[Fact]
public async Task AssemblyScan_RegistersHttp_AndHttps()
{
// The Tsak worker builds a module's components by this scan, through parameterless constructors.
await using var context = new RouteContext();
redb.Route.Extensions.RouteContextExtensions.AddComponents(context, typeof(HttpComponent).Assembly);
context.GetComponent("http").Should().NotBeNull().And.NotBeOfType();
context.GetComponent("https").Should().NotBeNull();
}
[Fact]
public void HttpsComponent_Scheme_ReturnsHttps()
{
var component = new HttpsComponent();
component.Scheme.Should().Be("https");
}
[Fact]
public void CreateEndpoint_ValidUri_ReturnsHttpEndpoint()
{
var component = new HttpComponent();
var parameters = new Dictionary();
var uri = new EndpointUri("http", "/api.example.com/orders", "http:api.example.com/orders", parameters);
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().BeOfType();
endpoint.Uri.Should().BeSameAs(uri);
endpoint.Component.Should().BeSameAs(component);
}
[Fact]
public void CreateEndpoint_NullUri_Throws()
{
var component = new HttpComponent();
var act = () => component.CreateEndpoint(null!);
act.Should().Throw();
}
[Fact]
public void CreateEndpoint_WithOptions_BindsCorrectly()
{
var component = new HttpComponent();
var parameters = new Dictionary
{
["method"] = "POST",
["timeout"] = "60000",
["throwOnError"] = "false",
["contentType"] = "text/xml",
["skipRequestHeaders"] = "true"
};
var uri = new EndpointUri("http", "/api.example.com/data", "http:api.example.com/data", parameters);
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Method.Should().Be(HttpMethod.POST);
endpoint.EndpointOptions.Timeout.Should().Be(60000);
endpoint.EndpointOptions.ThrowOnError.Should().BeFalse();
endpoint.EndpointOptions.ContentType.Should().Be("text/xml");
endpoint.EndpointOptions.SkipRequestHeaders.Should().BeTrue();
}
[Fact]
public void CreateEndpoint_ConsumerOptions_BindsCorrectly()
{
var component = new HttpComponent();
var parameters = new Dictionary
{
["host"] = "127.0.0.1",
["port"] = "9090",
["methods"] = "POST,PUT",
["cors"] = "true",
["corsOrigins"] = "https://example.com",
["inOut"] = "true",
["responseCode"] = "201",
["maxRequestBodySize"] = "1048576"
};
var uri = new EndpointUri("http", "/0.0.0.0:9090/webhook", "http:0.0.0.0:9090/webhook", parameters);
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Host.Should().Be("127.0.0.1");
endpoint.EndpointOptions.Port.Should().Be(9090);
endpoint.EndpointOptions.Methods.Should().Be("POST,PUT");
endpoint.EndpointOptions.Cors.Should().BeTrue();
endpoint.EndpointOptions.CorsOrigins.Should().Be("https://example.com");
endpoint.EndpointOptions.InOut.Should().BeTrue();
endpoint.EndpointOptions.ResponseCode.Should().Be(201);
endpoint.EndpointOptions.MaxRequestBodySize.Should().Be(1048576);
}
[Fact]
public void CreateEndpoint_AuthOptions_BindsCorrectly()
{
var component = new HttpComponent();
var parameters = new Dictionary
{
["authScheme"] = "Basic",
["username"] = "admin",
["password"] = "secret",
["followRedirects"] = "false",
["maxRedirects"] = "5",
["skipResponseHeaders"] = "true"
};
var uri = new EndpointUri("http", "/api.example.com/secure", "http:api.example.com/secure", parameters);
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.AuthScheme.Should().Be(HttpAuthScheme.Basic);
endpoint.EndpointOptions.Username.Should().Be("admin");
endpoint.EndpointOptions.Password.Should().Be("secret");
endpoint.EndpointOptions.FollowRedirects.Should().BeFalse();
endpoint.EndpointOptions.MaxRedirects.Should().Be(5);
endpoint.EndpointOptions.SkipResponseHeaders.Should().BeTrue();
}
[Fact]
public void CreateProducer_ReturnsHttpProducer()
{
var component = new HttpComponent();
var uri = new EndpointUri("http", "/api.example.com/test", "http:api.example.com/test", new Dictionary());
var endpoint = component.CreateEndpoint(uri);
var producer = endpoint.CreateProducer();
producer.Should().BeOfType();
}
[Fact]
public void CreateConsumer_ReturnsHttpConsumer()
{
var component = new HttpComponent();
component.ServerManager = new SharedHttpServerManager();
var uri = new EndpointUri("http", "/0.0.0.0:8080/webhook", "http:0.0.0.0:8080/webhook", new Dictionary());
var endpoint = component.CreateEndpoint(uri);
var processor = Substitute.For();
var consumer = endpoint.CreateConsumer(processor);
consumer.Should().BeOfType();
}
[Fact]
public void CreateConsumer_NullProcessor_Throws()
{
var component = new HttpComponent();
var uri = new EndpointUri("http", "/0.0.0.0:8080/webhook", "http:0.0.0.0:8080/webhook", new Dictionary());
var endpoint = component.CreateEndpoint(uri);
var act = () => endpoint.CreateConsumer(null!);
act.Should().Throw();
}
[Fact]
public void HttpEndpoint_IsHttps_ReturnsFalseForHttp()
{
var component = new HttpComponent();
var uri = new EndpointUri("http", "/api.example.com/test", "http:api.example.com/test", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.IsHttps.Should().BeFalse();
endpoint.SchemePrefix.Should().Be("http://");
}
[Fact]
public void HttpEndpoint_IsHttps_ReturnsTrueForHttps()
{
var component = new HttpsComponent();
var uri = new EndpointUri("https", "/api.example.com/test", "https:api.example.com/test", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.IsHttps.Should().BeTrue();
endpoint.SchemePrefix.Should().Be("https://");
}
[Fact]
public void HttpEndpoint_BuildProducerUrl_IncludesScheme()
{
var component = new HttpComponent();
var uri = new EndpointUri("http", "/api.example.com/orders", "http:api.example.com/orders", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.BuildProducerUrl().Should().Be("http://api.example.com/orders");
}
[Fact]
public void HttpEndpoint_BuildProducerUrl_Https()
{
var component = new HttpsComponent();
var uri = new EndpointUri("https", "/api.example.com/orders", "https:api.example.com/orders", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.BuildProducerUrl().Should().Be("https://api.example.com/orders");
}
[Theory]
[InlineData("/0.0.0.0:8080/webhook", "/webhook")]
[InlineData("/0.0.0.0:8080", "/")]
[InlineData("/localhost:9090/api/v1", "/api/v1")]
[InlineData("localhost:9090/api/v1", "/api/v1")]
[InlineData("0.0.0.0:8080", "/")]
public void HttpEndpoint_ConsumerPath_VariousFormats(string path, string expected)
{
var component = new HttpComponent();
var uri = new EndpointUri("http", path, $"http:{path}", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.ConsumerPath.Should().Be(expected);
}
[Theory]
[InlineData("/api/honest/echo", "/api/honest/echo")]
[InlineData("/api", "/api")]
[InlineData("/webhook", "/webhook")]
[InlineData("/", "/")]
public void ConsumerPath_FluentListenWithHostPort_KeepsFullRoutePath(string listenPath, string expected)
{
// Regression: Http.Listen("/api/honest/echo").Host(..).Port(..) must register the FULL path,
// not drop the first segment. The fluent DSL puts host/port in the query string
// ("http:/api/honest/echo?host=0.0.0.0&port=5092"), so the whole leading-slash path is the route.
var uri = EndpointUriParser.Parse(HttpDsl.Listen(listenPath).Host("0.0.0.0").Port(5092));
var endpoint = (HttpEndpoint)new HttpComponent().CreateEndpoint(uri);
endpoint.ConsumerPath.Should().Be(expected);
endpoint.EndpointOptions.Host.Should().Be("0.0.0.0");
endpoint.EndpointOptions.Port.Should().Be(5092);
}
[Fact]
public void ConsumerPath_FluentListenPortOnly_KeepsFullRoutePath()
{
// Port-only (host defaulted) still puts port in the query, so the path stays the route.
var uri = EndpointUriParser.Parse(HttpDsl.Listen("/api/orders").Port(8080));
var endpoint = (HttpEndpoint)new HttpComponent().CreateEndpoint(uri);
endpoint.ConsumerPath.Should().Be("/api/orders");
}
// ── DefaultCors (component-level CORS) ──
[Fact]
public void DefaultCors_Disabled_ByDefault()
{
var component = new HttpComponent();
component.DefaultCors.Enabled.Should().BeFalse();
component.DefaultCors.Origins.Should().BeNull();
component.DefaultCors.Credentials.Should().BeFalse();
}
[Fact]
public void DefaultCors_AppliedWhenEndpointOmitsCors()
{
var component = new HttpComponent();
component.DefaultCors.Enabled = true;
component.DefaultCors.Origins = "https://example.com";
component.DefaultCors.Credentials = true;
// No cors params in URI
var uri = new EndpointUri("http", "/0.0.0.0:8080/webhook", "http:0.0.0.0:8080/webhook", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Cors.Should().BeTrue();
endpoint.EndpointOptions.CorsOrigins.Should().Be("https://example.com");
endpoint.EndpointOptions.CorsCredentials.Should().BeTrue();
}
[Fact]
public void DefaultCors_EndpointOverridesGlobal()
{
var component = new HttpComponent();
component.DefaultCors.Enabled = true;
component.DefaultCors.Origins = "https://global.com";
component.DefaultCors.Credentials = true;
// Endpoint explicitly sets different values
var uri = new EndpointUri("http", "/0.0.0.0:8080/webhook", "http:0.0.0.0:8080/webhook",
new Dictionary
{
["cors"] = "true",
["corsOrigins"] = "https://override.com",
["corsCredentials"] = "false"
});
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.CorsOrigins.Should().Be("https://override.com");
endpoint.EndpointOptions.CorsCredentials.Should().BeFalse();
}
[Fact]
public void DefaultCors_EndpointDisablesCors_GlobalEnabled()
{
var component = new HttpComponent();
component.DefaultCors.Enabled = true;
var uri = new EndpointUri("http", "/0.0.0.0:8080/internal", "http:0.0.0.0:8080/internal",
new Dictionary { ["cors"] = "false" });
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Cors.Should().BeFalse();
}
[Fact]
public void DefaultCors_EndpointEnablesCors_GlobalDisabled()
{
var component = new HttpComponent();
// DefaultCors.Enabled is false by default
// The strict-CORS contract requires an explicit origin policy when Cors=true.
// Endpoints that opt in via the URI must therefore also supply corsOrigins (or a resolver).
var uri = new EndpointUri("http", "/0.0.0.0:8080/webhook", "http:0.0.0.0:8080/webhook",
new Dictionary { ["cors"] = "true", ["corsOrigins"] = "*" });
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Cors.Should().BeTrue();
}
// ── Method prefix shorthand (http:GET:/path) ──
[Fact]
public void CreateEndpoint_MethodPrefix_SetsMethodAndMethods()
{
var component = new HttpComponent();
var uri = new EndpointUri("http", "POST:/connect/token", "http://POST:/connect/token", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Method.Should().Be(HttpMethod.POST);
endpoint.EndpointOptions.Methods.Should().Be("POST");
endpoint.ConsumerPath.Should().Be("/connect/token");
}
[Fact]
public void CreateEndpoint_MethodPrefix_Get_SetsConsumerPath()
{
var component = new HttpComponent();
var uri = new EndpointUri("http", "GET:/.well-known/openid-configuration", "http://GET:/.well-known/openid-configuration", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Methods.Should().Be("GET");
endpoint.ConsumerPath.Should().Be("/.well-known/openid-configuration");
}
[Fact]
public void CreateEndpoint_MethodPrefix_WithHostPort()
{
var component = new HttpComponent();
var uri = new EndpointUri("http", "POST:0.0.0.0:8080/api/orders", "http://POST:0.0.0.0:8080/api/orders", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Method.Should().Be(HttpMethod.POST);
endpoint.EndpointOptions.Methods.Should().Be("POST");
endpoint.EndpointOptions.Host.Should().Be("0.0.0.0");
endpoint.EndpointOptions.Port.Should().Be(8080);
endpoint.ConsumerPath.Should().Be("/api/orders");
}
[Fact]
public void CreateEndpoint_MethodPrefix_CaseInsensitive()
{
var component = new HttpComponent();
var uri = new EndpointUri("http", "get:/test", "http://get:/test", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Method.Should().Be(HttpMethod.GET);
endpoint.EndpointOptions.Methods.Should().Be("GET");
}
[Fact]
public void CreateEndpoint_MethodPrefix_QueryParamsTakePriority()
{
var component = new HttpComponent();
var parameters = new Dictionary { ["methods"] = "POST,PUT" };
var uri = new EndpointUri("http", "GET:/test", "http://GET:/test?methods=POST,PUT", parameters);
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
// Query param wins over prefix
endpoint.EndpointOptions.Methods.Should().Be("POST,PUT");
}
[Fact]
public void CreateEndpoint_NoMethodPrefix_WorksAsUsual()
{
var component = new HttpComponent();
var uri = new EndpointUri("http", "0.0.0.0:8080/webhook", "http://0.0.0.0:8080/webhook", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Host.Should().Be("0.0.0.0");
endpoint.EndpointOptions.Port.Should().Be(8080);
endpoint.ConsumerPath.Should().Be("/webhook");
}
[Fact]
public void CreateEndpoint_HostnameLikeMethod_NotConfused()
{
// "getdata" should NOT be parsed as "GET" — must be exact match
var component = new HttpComponent();
var uri = new EndpointUri("http", "getdata.example.com/api", "http://getdata.example.com/api", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Methods.Should().BeNull();
endpoint.ConsumerPath.Should().Be("/api");
}
[Theory]
[InlineData("DELETE:/resource/{id}", "DELETE", "/resource/{id}")]
[InlineData("PATCH:/users/123", "PATCH", "/users/123")]
[InlineData("PUT:/items", "PUT", "/items")]
public void CreateEndpoint_MethodPrefix_AllMethods(string path, string expectedMethod, string expectedConsumerPath)
{
var component = new HttpComponent();
var uri = new EndpointUri("http", path, $"http://{path}", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Methods.Should().Be(expectedMethod);
endpoint.ConsumerPath.Should().Be(expectedConsumerPath);
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpConcurrencyLimitTests.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/tests/redb.Route.Tests.Http/HttpConcurrencyLimitTests.cs
----
using System.Net;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using HttpDsl = redb.Route.Http.Http;
namespace redb.Route.Tests.Http;
///
/// E2e for the per-endpoint admission limit:
/// a consumer with maxConcurrentRequests runs at most that many pipelines, sheds the
/// overflow with 429 + Retry-After BEFORE the pipeline, and counts each shed request in the
/// endpoint's Rejected — MessagesIn/Errors stay untouched.
///
[Collection("HttpServer")]
public class HttpConcurrencyLimitTests : IAsyncLifetime
{
private HttpConsumer? _consumer;
private int _port;
private SharedHttpServerManager? _serverManager;
public Task InitializeAsync()
{
_port = GetFreePort();
_serverManager = new SharedHttpServerManager();
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
if (_consumer is not null) await _consumer.Stop();
if (_serverManager is not null) await _serverManager.DisposeAsync();
}
private (HttpConsumer Consumer, HttpEndpoint Endpoint) CreateConsumer(
Dictionary extra, Func onProcess)
{
var parameters = new Dictionary
{
["host"] = "127.0.0.1",
["port"] = _port.ToString(),
};
foreach (var (k, v) in extra) parameters[k] = v;
var path = $"/127.0.0.1:{_port}/limited";
var uri = new EndpointUri("http", path, $"http:{path}", parameters);
var endpoint = (HttpEndpoint)new HttpComponent().CreateEndpoint(uri);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci => onProcess(ci.Arg()));
_consumer = new HttpConsumer(endpoint, processor, endpoint.EndpointOptions, _serverManager!);
return (_consumer, endpoint);
}
[Fact]
public async Task OverLimit_IsShedWith429_AndCountedAsRejected()
{
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var processed = 0;
var (consumer, endpoint) = CreateConsumer(
new Dictionary { ["maxConcurrentRequests"] = "1" },
async _ =>
{
Interlocked.Increment(ref processed);
entered.TrySetResult();
await gate.Task;
});
await consumer.Start();
using var client = new HttpClient();
var first = client.PostAsync($"http://127.0.0.1:{_port}/limited", new StringContent("a"));
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); // the single permit is held
var second = await client.PostAsync($"http://127.0.0.1:{_port}/limited", new StringContent("b"));
second.StatusCode.Should().Be(HttpStatusCode.TooManyRequests,
"over the limit - an immediate rejection before the pipeline");
second.Headers.RetryAfter.Should().NotBeNull();
second.Headers.RetryAfter!.Delta.Should().Be(TimeSpan.FromSeconds(1));
gate.SetResult();
(await first).IsSuccessStatusCode.Should().BeTrue();
processed.Should().Be(1, "a rejected request must not touch the pipeline");
endpoint.Rejected.Should().Be(1, "every rejection is counted exactly once");
endpoint.Errors.Should().Be(0, "a rejection is not a processing error");
}
[Fact]
public async Task WithQueue_TheOverflowWaits_AndCapHolds()
{
var current = 0;
var max = 0;
var (consumer, endpoint) = CreateConsumer(
new Dictionary
{
["maxConcurrentRequests"] = "2",
["requestQueueLimit"] = "100",
},
async _ =>
{
var now = Interlocked.Increment(ref current);
int seen;
do { seen = Volatile.Read(ref max); }
while (now > seen && Interlocked.CompareExchange(ref max, now, seen) != seen);
await Task.Delay(250);
Interlocked.Decrement(ref current);
});
await consumer.Start();
using var client = new HttpClient();
var responses = await Task.WhenAll(Enumerable.Range(0, 8)
.Select(_ => client.PostAsync($"http://127.0.0.1:{_port}/limited", new StringContent("x"))));
responses.Should().OnlyContain(r => r.IsSuccessStatusCode,
"with a large enough queue nobody is rejected");
Volatile.Read(ref max).Should().BeLessThanOrEqualTo(2,
"without the limit Kestrel would run all 8 at once");
endpoint.Rejected.Should().Be(0);
}
[Fact]
public void UriAndDsl_CarryTheOptions()
{
var built = HttpDsl.Listen("/api")
.Port(8080)
.MaxConcurrentRequests(4, queue: 16)
.RejectStatusCode(503)
.RetryAfterSeconds(0)
.Build();
built.Should().Contain("maxConcurrentRequests=4")
.And.Contain("requestQueueLimit=16")
.And.Contain("rejectStatusCode=503")
.And.Contain("retryAfterSeconds=0");
var endpoint = (HttpEndpoint)new HttpComponent().CreateEndpoint(EndpointUriParser.Parse(built));
endpoint.EndpointOptions.MaxConcurrentRequests.Should().Be(4);
endpoint.EndpointOptions.RequestQueueLimit.Should().Be(16);
endpoint.EndpointOptions.RejectStatusCode.Should().Be(503);
endpoint.EndpointOptions.RetryAfterSeconds.Should().Be(0);
}
[Fact]
public void QueueWithoutLimit_FailsLoud()
{
var uri = EndpointUriParser.Parse($"http:/127.0.0.1:{_port}/x?requestQueueLimit=5");
var act = () => new HttpComponent().CreateEndpoint(uri);
act.Should().Throw().WithMessage("*requestQueueLimit*maxConcurrentRequests*");
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpConnectionFactoryTests.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/tests/redb.Route.Tests.Http/HttpConnectionFactoryTests.cs
----
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// Basic/Bearer credentials and the TLS certificate password must be able to live in the registry
/// instead of the endpoint URI, so they never reach logs, telemetry, or the dashboard.
///
public sealed class HttpConnectionFactoryTests
{
private const string Secret = "b3arer-T0PSECRET";
private static HttpComponent Wire(string name, HttpConnectionFactory factory)
{
var context = new RouteContext();
var component = new HttpComponent();
context.AddComponent(component);
context.AddToRegistry(name, factory);
return component;
}
[Fact]
public void Factory_SuppliesBasicCredentials_WhenUriCarriesNone()
{
var component = Wire("billing-api", new HttpConnectionFactory
{
AuthScheme = HttpAuthScheme.Basic,
Username = "svc",
Password = Secret
});
// Validate() requires Username+Password when AuthScheme=Basic — this throws
// if the factory is not applied first.
var uri = EndpointUriParser.Parse("http://billing.corp.local/invoices?connectionFactory=billing-api");
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().NotBeNull();
uri.ToUriString().Should().NotContain(Secret);
uri.ToString().Should().NotContain(Secret);
}
[Fact]
public void Factory_SuppliesBearerToken()
{
var component = Wire("api", new HttpConnectionFactory
{
AuthScheme = HttpAuthScheme.Bearer,
AuthToken = Secret
});
var uri = EndpointUriParser.Parse("http://api.corp.local/v1?connectionFactory=api");
component.CreateEndpoint(uri).Should().NotBeNull();
uri.ToUriString().Should().NotContain(Secret);
}
[Fact]
public void FactoryAuthToken_SupportsExpressions_LikeTheUriForm()
{
// A ${...} token from the factory must become a per-request expression, exactly as
// BindFromUri does for authToken=${...} — not a literal.
var component = Wire("api", new HttpConnectionFactory
{
AuthScheme = HttpAuthScheme.Bearer,
AuthToken = "${header.jwt}"
});
var uri = EndpointUriParser.Parse("http://api.corp.local/v1?connectionFactory=api");
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
var token = endpoint.EndpointOptions.AuthToken;
token.HasValue.Should().BeTrue();
token!.Value.IsDynamic.Should().BeTrue("a ${...} factory token must resolve per request");
}
[Fact]
public void ExplicitUriValue_WinsOverFactory()
{
var component = Wire("f", new HttpConnectionFactory
{
AuthScheme = HttpAuthScheme.Basic,
Username = "factory-user",
Password = "factory-pw"
});
var uri = EndpointUriParser.Parse(
"http://api.corp.local/v1?connectionFactory=f&username=uri-user&password=uri-pw");
component.CreateEndpoint(uri).Should().NotBeNull();
uri.RawParameters["username"].Should().Be("uri-user");
}
[Fact]
public void MissingFactory_FailsLoud()
{
var context = new RouteContext();
var component = new HttpComponent();
context.AddComponent(component);
var uri = EndpointUriParser.Parse("http://api.corp.local/v1?connectionFactory=absent");
var act = () => component.CreateEndpoint(uri);
// A typo in connectionFactory must fail loud, not fall back silently
act.Should().Throw()
.Which.Message.Should().Contain("absent");
}
[Fact]
public void Dsl_EmitsConnectionFactory()
{
// fully qualified: the test namespace itself is ...Tests.Http, which shadows the DSL class
var uri = redb.Route.Http.Http.Get("http://api.corp.local/v1")
.ConnectionFactory("billing-api").Build();
uri.Should().Contain("connectionFactory=billing-api");
uri.Should().NotContain("password=");
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpConsumerIgnoredAuthTests.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/tests/redb.Route.Tests.Http/HttpConsumerIgnoredAuthTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Processors;
namespace redb.Route.Tests.Http;
///
/// authScheme, username and password are the credentials an http:
/// producer sends. They live in the options class the consumer shares, so
/// from("http://0.0.0.0:8080/api?authScheme=basic&username=admin&password=…") bound
/// without a word, passed validation — which even demanded a non-empty user and password — and
/// started a route that checked nothing. Its author believed the endpoint was closed, and the password
/// sat in the route key besides. Found while planning inbound authentication, 2026-09-25.
///
/// Refused now, until the consumer has a real inbound check of its own. Only parameters written on
/// the consumer's own URI count: a named connection factory may legitimately carry producer
/// credentials alongside the TLS material a consumer reuses it for.
///
///
[Collection("HttpServer")]
public class HttpConsumerIgnoredAuthTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
private static RouteContext Context()
{
var context = new RouteContext();
context.AddComponent(new HttpComponent { ServerManager = new SharedHttpServerManager() });
return context;
}
[Theory]
[InlineData("authScheme=basic&username=admin&password=s3cret-value")]
[InlineData("username=admin&password=s3cret-value")]
[InlineData("authScheme=bearer")]
[InlineData("authScheme=bearer&authToken=s3cret-value")]
public async Task Inbound_credentials_on_a_consumer_are_refused_rather_than_ignored(string query)
{
await using var context = Context();
var port = FreePort();
var act = () => context.GetEndpoint($"http://127.0.0.1:{port}/api?{query}")
.CreateConsumer(new DelegateProcessor(_ => { }));
var error = act.Should().Throw().Which;
error.Message.Should().Contain("does not check", "the reader must learn the endpoint is not protected");
error.Message.Should().NotContain("s3cret-value", "a refusal must never echo a secret into a log");
}
[Fact]
public async Task A_connection_factory_carrying_producer_credentials_does_not_block_a_consumer()
{
await using var context = Context();
context.AddToRegistry("partner", new HttpConnectionFactory
{
AuthScheme = HttpAuthScheme.Basic,
Username = "svc",
Password = "factory-secret",
});
var port = FreePort();
var act = () => context.GetEndpoint($"http://127.0.0.1:{port}/api?connectionFactory=partner")
.CreateConsumer(new DelegateProcessor(_ => { }));
act.Should().NotThrow("a factory is shared with producers; only what the consumer wrote itself is intent");
}
[Fact]
public async Task The_producer_keeps_its_credentials()
{
await using var context = Context();
var act = () => context.GetEndpoint("http://example.invalid/api?authScheme=basic&username=u&password=p")
.CreateProducer();
act.Should().NotThrow("these options are exactly what a producer is for");
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpConsumerStartRetryTests.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/tests/redb.Route.Tests.Http/HttpConsumerStartRetryTests.cs
----
using System.Net;
using System.Net.Sockets;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// An HTTP consumer whose port is still taken when the context starts (an old process not gone yet) is started again
/// by the context's consumer start retry: the route is Errored while the port is taken, Started once it is free, and
/// then answers. The failed starts leave nothing behind on the shared listener: after the context stops the port is
/// free and one request reaches the route once.
///
[Collection("HttpServer")]
public sealed class HttpConsumerStartRetryTests : IAsyncLifetime
{
private readonly SharedHttpServerManager _servers = new();
private readonly HttpClient _client = new() { Timeout = TimeSpan.FromSeconds(10) };
private readonly int _port = global::redb.Route.Tests.Shared.TestPorts.Next();
private readonly RouteContext _ctx = new(options: new RouteEngineOptions
{
ShutdownTimeout = TimeSpan.FromSeconds(2),
ConsumerStartRetry = new ConsumerStartRetryOptions
{
Delay = TimeSpan.FromMilliseconds(100),
Multiplier = 1.0,
MaxDelay = TimeSpan.FromMilliseconds(100),
},
});
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
_client.Dispose();
await _ctx.DisposeAsync();
await _servers.DisposeAsync();
}
[Fact]
public async Task A_listener_whose_port_was_taken_starts_once_the_port_is_free()
{
var calls = 0;
_ctx.AddComponent(new HttpComponent { ServerManager = _servers });
_ctx.AddRoutes(r => r.From($"http://127.0.0.1:{_port}/ping?inOut=true").RouteId("late-port").Process(e =>
{
Interlocked.Increment(ref calls);
e.In.Body = "pong";
}));
var squatter = new TcpListener(IPAddress.Loopback, _port);
squatter.Start();
try
{
await _ctx.Start();
_ctx.GetRoute("late-port")!.Status.Should().Be(RouteStatus.Errored, "the port is taken");
// A few failed retries while the port stays taken.
await Task.Delay(400);
_ctx.GetRoute("late-port")!.Status.Should().Be(RouteStatus.Errored);
}
finally
{
squatter.Stop();
}
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (_ctx.GetRoute("late-port")!.Status != RouteStatus.Started)
{
DateTime.UtcNow.Should().BeBefore(deadline, "the retry starts the listener once the port is free");
await Task.Delay(50);
}
(await _client.GetStringAsync($"http://127.0.0.1:{_port}/ping")).Should().Be("pong");
Volatile.Read(ref calls).Should().Be(1, "one registration of the route, not one per failed start");
await _ctx.Stop();
var stopped = () => _client.GetAsync($"http://127.0.0.1:{_port}/ping");
await stopped.Should().ThrowAsync("the stopped context gives the port back");
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpConsumerTests.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/tests/redb.Route.Tests.Http/HttpConsumerTests.cs
----
using System.Net;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// Tests for HttpConsumer (Kestrel-based).
/// Each test starts a real embedded HTTP server, sends requests via HttpClient, and verifies the exchange pipeline.
///
[Collection("HttpServer")]
public class HttpConsumerTests : IAsyncLifetime
{
private HttpConsumer? _consumer;
private HttpClient? _client;
private int _port;
private SharedHttpServerManager? _serverManager;
// Captured exchange from processor
private IExchange? _lastExchange;
private readonly List _capturedExchanges = new();
// Configurable processor behavior
private Func? _processorAction;
public Task InitializeAsync()
{
_port = GetFreePort();
_client = new HttpClient();
_serverManager = new SharedHttpServerManager();
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
_client?.Dispose();
if (_consumer is not null)
{
await _consumer.Stop();
}
if (_serverManager is not null) await _serverManager.DisposeAsync();
}
private HttpConsumer CreateConsumer(
string path = "/webhook",
Dictionary? extraParams = null)
{
var component = new HttpComponent();
var parameters = new Dictionary
{
["host"] = "127.0.0.1",
["port"] = _port.ToString()
};
if (extraParams is not null)
{
foreach (var (key, value) in extraParams)
parameters[key] = value;
}
var uriPath = $"/127.0.0.1:{_port}{path}";
var uri = new EndpointUri("http", uriPath, $"http:{uriPath}", parameters);
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(async ci =>
{
var ex = ci.Arg();
_lastExchange = ex;
_capturedExchanges.Add(ex);
if (_processorAction is not null)
await _processorAction(ex);
});
_consumer = new HttpConsumer(endpoint, processor, endpoint.EndpointOptions, _serverManager!);
return _consumer;
}
// ── Basic request handling ──
[Fact]
public async Task Consumer_POST_ReceivesRequest()
{
var consumer = CreateConsumer();
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("""{"order":"123"}""", Encoding.UTF8, "application/json"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
_lastExchange.Should().NotBeNull();
var body = Encoding.UTF8.GetString((byte[])_lastExchange!.In.Body!);
body.Should().Be("""{"order":"123"}""");
}
[Fact]
public async Task Consumer_GET_ReceivesRequest()
{
var consumer = CreateConsumer();
await consumer.Start();
var response = await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
response.StatusCode.Should().Be(HttpStatusCode.OK);
_lastExchange.Should().NotBeNull();
_lastExchange!.In.Headers[HttpHeaders.Method].Should().Be("GET");
}
[Fact]
public async Task Consumer_PopulatesAllHeaders()
{
var consumer = CreateConsumer();
await consumer.Start();
_client!.DefaultRequestHeaders.Add("X-Custom-Test", "hello");
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook?param=value",
new StringContent("body", Encoding.UTF8, "text/plain"));
_lastExchange.Should().NotBeNull();
_lastExchange!.In.Headers[HttpHeaders.Method].Should().Be("POST");
_lastExchange!.In.Headers[HttpHeaders.Path].Should().Be("/webhook");
_lastExchange!.In.Headers.Should().ContainKey(HttpHeaders.Url);
_lastExchange!.In.Headers[HttpHeaders.Query].Should().Be("param=value");
_lastExchange!.In.Headers.Should().ContainKey(HttpHeaders.RemoteAddress);
_lastExchange!.In.Headers.Should().ContainKey("X-Custom-Test");
_lastExchange!.In.Headers["X-Custom-Test"]!.ToString().Should().Be("hello");
}
// ── Method filtering ──
[Fact]
public async Task Consumer_MethodFilter_RejectsDisallowedMethod()
{
var consumer = CreateConsumer(extraParams: new Dictionary
{
["methods"] = "POST"
});
await consumer.Start();
var response = await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
response.StatusCode.Should().Be(HttpStatusCode.MethodNotAllowed);
_lastExchange.Should().BeNull();
}
[Fact]
public async Task Consumer_MethodFilter_AcceptsAllowedMethod()
{
var consumer = CreateConsumer(extraParams: new Dictionary
{
["methods"] = "POST,PUT"
});
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("data", Encoding.UTF8, "text/plain"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
_lastExchange.Should().NotBeNull();
}
// ── CORS ──
[Fact]
public async Task Consumer_Cors_Enabled_SetsCorsHeaders()
{
var consumer = CreateConsumer(extraParams: new Dictionary
{
["cors"] = "true",
["corsOrigins"] = "*"
});
await consumer.Start();
var response = await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
response.Headers.Contains("Access-Control-Allow-Origin").Should().BeTrue();
response.Headers.GetValues("Access-Control-Allow-Origin").First().Should().Be("*");
}
[Fact]
public async Task Consumer_Cors_CustomOrigins()
{
var consumer = CreateConsumer(extraParams: new Dictionary
{
["cors"] = "true",
["corsOrigins"] = "https://example.com"
});
await consumer.Start();
// Browsers always send Origin on cross-origin requests; the new dispatch middleware
// echoes a single matching origin from the whitelist instead of returning the raw CSV
// (which browsers cannot consume in Access-Control-Allow-Origin).
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/webhook");
request.Headers.Add("Origin", "https://example.com");
var response = await _client!.SendAsync(request);
response.Headers.GetValues("Access-Control-Allow-Origin").First().Should().Be("https://example.com");
response.Headers.GetValues("Vary").Should().Contain(v => v.Contains("Origin"));
}
[Fact]
public async Task Consumer_Cors_Credentials_SetsHeader()
{
var consumer = CreateConsumer(extraParams: new Dictionary
{
["cors"] = "true",
["corsOrigins"] = "https://example.com",
["corsCredentials"] = "true"
});
await consumer.Start();
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/webhook");
request.Headers.Add("Origin", "https://example.com");
var response = await _client!.SendAsync(request);
response.Headers.GetValues("Access-Control-Allow-Credentials").First().Should().Be("true");
response.Headers.GetValues("Access-Control-Allow-Origin").First().Should().Be("https://example.com");
}
[Fact]
public async Task Consumer_Cors_WithoutCredentials_NoCredentialsHeader()
{
var consumer = CreateConsumer(extraParams: new Dictionary
{
["cors"] = "true",
["corsOrigins"] = "*"
});
await consumer.Start();
var response = await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
response.Headers.Contains("Access-Control-Allow-Credentials").Should().BeFalse();
}
[Fact]
public async Task Consumer_Cors_OptionsRequest_Returns204()
{
var consumer = CreateConsumer(extraParams: new Dictionary
{
["cors"] = "true",
["corsOrigins"] = "*"
});
await consumer.Start();
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Options, $"http://127.0.0.1:{_port}/webhook");
request.Headers.Add("Origin", "https://example.com");
request.Headers.Add("Access-Control-Request-Method", "POST");
var response = await _client!.SendAsync(request);
response.StatusCode.Should().Be(HttpStatusCode.NoContent);
}
// ── InOut pattern ──
[Fact]
public async Task Consumer_InOut_ReturnsResponseBody()
{
_processorAction = ex =>
{
ex.Out = new Message("""{"response":"processed"}""");
return Task.CompletedTask;
};
var consumer = CreateConsumer(extraParams: new Dictionary
{
["inOut"] = "true"
});
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("""{"input":"data"}""", Encoding.UTF8, "application/json"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseBody = await response.Content.ReadAsStringAsync();
responseBody.Should().Be("""{"response":"processed"}""");
}
[Fact]
public async Task Consumer_InOut_ReturnsResponseBodyAsBytes()
{
var responseBytes = new byte[] { 0x01, 0x02, 0x03 };
_processorAction = ex =>
{
ex.Out = new Message(responseBytes);
return Task.CompletedTask;
};
var consumer = CreateConsumer(extraParams: new Dictionary
{
["inOut"] = "true"
});
await consumer.Start();
var response = await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
var body = await response.Content.ReadAsByteArrayAsync();
body.Should().BeEquivalentTo(responseBytes);
}
[Fact]
public async Task Consumer_InOnly_ReturnsEmptyBody()
{
_processorAction = ex =>
{
ex.Out = new Message("this should not be returned");
return Task.CompletedTask;
};
var consumer = CreateConsumer(); // inOut defaults to false
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("data", Encoding.UTF8, "text/plain"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseBody = await response.Content.ReadAsStringAsync();
responseBody.Should().BeEmpty();
}
// ── Custom response code ──
[Fact]
public async Task Consumer_CustomResponseCode()
{
var consumer = CreateConsumer(extraParams: new Dictionary
{
["responseCode"] = "202"
});
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("data", Encoding.UTF8, "text/plain"));
response.StatusCode.Should().Be(HttpStatusCode.Accepted);
}
[Fact]
public async Task Consumer_ResponseCode_OverriddenByHeader()
{
_processorAction = ex =>
{
ex.Out = new Message("created");
ex.Out.Headers[HttpHeaders.ResponseCode] = 201;
return Task.CompletedTask;
};
var consumer = CreateConsumer(extraParams: new Dictionary
{
["inOut"] = "true"
});
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("data", Encoding.UTF8, "text/plain"));
response.StatusCode.Should().Be(HttpStatusCode.Created);
}
// ── Exception handling ──
[Fact]
public async Task Consumer_ProcessorException_Returns500()
{
_processorAction = _ => throw new InvalidOperationException("Processing failed");
var consumer = CreateConsumer();
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("data", Encoding.UTF8, "text/plain"));
// Route pipeline exceptions are put on exchange.Exception
// The consumer checks exchange.Exception and returns 500
// NSubstitute can't easily simulate this, so we check the processor was invoked
_lastExchange.Should().NotBeNull();
}
[Fact]
public async Task Consumer_ExchangeException_UnhandledReturns500()
{
_processorAction = ex =>
{
ex.Exception = new InvalidOperationException("test error");
return Task.CompletedTask;
};
var consumer = CreateConsumer();
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("data", Encoding.UTF8, "text/plain"));
response.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
var body = await response.Content.ReadAsStringAsync();
// BR-4: the exception's own text stays in the log; the caller gets a reference to quote.
body.Should().NotContain("test error").And.Contain("ref: ");
}
[Fact]
public async Task Consumer_ExchangeException_HandledReturnsOk()
{
_processorAction = ex =>
{
ex.Exception = new InvalidOperationException("handled error");
ex.ExceptionHandled = true;
return Task.CompletedTask;
};
var consumer = CreateConsumer();
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("data", Encoding.UTF8, "text/plain"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
// ── ProcessedCount ──
[Fact]
public async Task Consumer_ProcessedCount_Increments()
{
var consumer = CreateConsumer();
await consumer.Start();
consumer.ProcessedCount.Should().Be(0);
await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
consumer.ProcessedCount.Should().Be(1);
await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
consumer.ProcessedCount.Should().Be(2);
}
// ── BaseUrl ──
[Fact]
public async Task Consumer_BaseUrl_AvailableAfterStart()
{
var consumer = CreateConsumer();
consumer.BaseUrl.Should().BeNull();
await consumer.Start();
consumer.BaseUrl.Should().NotBeNullOrEmpty();
consumer.BaseUrl.Should().Contain(_port.ToString());
}
// ── Lifecycle ──
[Fact]
public async Task Consumer_StartStop_Lifecycle()
{
var consumer = CreateConsumer();
await consumer.Start();
await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook"); // works
await consumer.Stop();
// After stop, requests should fail
var act = async () => await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
await act.Should().ThrowAsync();
}
// ── Exchange pattern ──
[Fact]
public async Task Consumer_InOut_SetsExchangePattern()
{
_processorAction = ex =>
{
ex.Pattern.Should().Be(ExchangePattern.InOut);
return Task.CompletedTask;
};
var consumer = CreateConsumer(extraParams: new Dictionary { ["inOut"] = "true" });
await consumer.Start();
await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
}
[Fact]
public async Task Consumer_InOnly_SetsExchangePattern()
{
_processorAction = ex =>
{
ex.Pattern.Should().Be(ExchangePattern.InOnly);
return Task.CompletedTask;
};
var consumer = CreateConsumer();
await consumer.Start();
await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
}
// ── ResponseContentType ──
[Fact]
public async Task Consumer_InOut_ResponseContentType_Override()
{
_processorAction = ex =>
{
ex.Out = new Message("result");
ex.Out.Headers[HttpHeaders.ResponseContentType] = "text/xml";
return Task.CompletedTask;
};
var consumer = CreateConsumer(extraParams: new Dictionary { ["inOut"] = "true" });
await consumer.Start();
var response = await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
response.Content.Headers.ContentType?.MediaType.Should().Be("text/xml");
}
// ── Non-matching path returns 404 ──
[Fact]
public async Task Consumer_WrongPath_Returns404()
{
var consumer = CreateConsumer(path: "/webhook");
await consumer.Start();
var response = await _client!.GetAsync($"http://127.0.0.1:{_port}/other");
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
_lastExchange.Should().BeNull();
}
// ── Multiple concurrent requests ──
[Fact]
public async Task Consumer_MultipleConcurrentRequests()
{
var consumer = CreateConsumer();
await consumer.Start();
var tasks = Enumerable.Range(0, 10).Select(i =>
_client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent($"request-{i}", Encoding.UTF8, "text/plain")));
var responses = await Task.WhenAll(tasks);
responses.Should().AllSatisfy(r => r.StatusCode.Should().Be(HttpStatusCode.OK));
consumer.ProcessedCount.Should().Be(10);
}
// ── StreamRequest ──
[Fact]
public async Task Consumer_StreamRequest_BodyIsStream()
{
Type? bodyType = null;
_processorAction = ex =>
{
bodyType = ex.In.Body?.GetType();
return Task.CompletedTask;
};
var consumer = CreateConsumer(extraParams: new Dictionary
{
["streamRequest"] = "true"
});
await consumer.Start();
await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("stream-test", Encoding.UTF8, "text/plain"));
bodyType.Should().NotBeNull();
bodyType!.Should().BeAssignableTo(typeof(Stream));
}
[Fact]
public async Task Consumer_StreamRequest_StreamContainsCorrectData()
{
string? captured = null;
_processorAction = async ex =>
{
var stream = (Stream)ex.In.Body!;
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
captured = await reader.ReadToEndAsync();
};
var consumer = CreateConsumer(extraParams: new Dictionary
{
["streamRequest"] = "true"
});
await consumer.Start();
await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("hello-stream", Encoding.UTF8, "text/plain"));
captured.Should().Be("hello-stream");
}
[Fact]
public async Task Consumer_StreamRequest_HeadersStillPopulated()
{
_processorAction = ex =>
{
ex.In.Headers[HttpHeaders.Method].Should().Be("POST");
ex.In.Headers[HttpHeaders.Path].Should().Be("/webhook");
return Task.CompletedTask;
};
var consumer = CreateConsumer(extraParams: new Dictionary
{
["streamRequest"] = "true"
});
await consumer.Start();
await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("data", Encoding.UTF8, "text/plain"));
_lastExchange.Should().NotBeNull();
}
[Fact]
public async Task Consumer_StreamRequest_False_BodyIsByteArray()
{
Type? bodyType = null;
_processorAction = ex =>
{
bodyType = ex.In.Body?.GetType();
return Task.CompletedTask;
};
var consumer = CreateConsumer(); // streamRequest defaults to false
await consumer.Start();
await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("test", Encoding.UTF8, "text/plain"));
bodyType.Should().Be(typeof(byte[]));
}
[Fact]
public async Task Consumer_StreamRequest_InOut_ReturnsResponseAfterStreamRead()
{
_processorAction = async ex =>
{
var stream = (Stream)ex.In.Body!;
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
var content = await reader.ReadToEndAsync();
ex.Out = new Message($"echo:{content}");
};
var consumer = CreateConsumer(extraParams: new Dictionary
{
["streamRequest"] = "true",
["inOut"] = "true"
});
await consumer.Start();
var response = await _client!.PostAsync(
$"http://127.0.0.1:{_port}/webhook",
new StringContent("streamed-payload", Encoding.UTF8, "text/plain"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
body.Should().Be("echo:streamed-payload");
}
// ── status.code fallback ──
[Fact]
public async Task Consumer_StatusCodeFallback_ReadsStatusDotCode()
{
_processorAction = ex =>
{
ex.Out = new Message("not found");
// Set only "status.code" — simulates old dispatcher behavior
ex.Out.Headers["status.code"] = 404;
return Task.CompletedTask;
};
var consumer = CreateConsumer(extraParams: new Dictionary { ["inOut"] = "true" });
await consumer.Start();
var response = await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
response.StatusCode.Should().Be(HttpStatusCode.NotFound,
"HttpConsumer should fall back to 'status.code' when 'redbHttp.ResponseCode' is absent");
}
[Fact]
public async Task Consumer_ResponseCode_TakesPrecedenceOverStatusCode()
{
_processorAction = ex =>
{
ex.Out = new Message("created");
ex.Out.Headers["status.code"] = 404;
ex.Out.Headers[HttpHeaders.ResponseCode] = 201;
return Task.CompletedTask;
};
var consumer = CreateConsumer(extraParams: new Dictionary { ["inOut"] = "true" });
await consumer.Start();
var response = await _client!.GetAsync($"http://127.0.0.1:{_port}/webhook");
response.StatusCode.Should().Be(HttpStatusCode.Created,
"redbHttp.ResponseCode should take precedence over status.code");
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpEndpointOptionsTests.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/tests/redb.Route.Tests.Http/HttpEndpointOptionsTests.cs
----
using redb.Route.Http;
using HttpMethod = redb.Route.Http.HttpMethod;
namespace redb.Route.Tests.Http;
public class HttpEndpointOptionsTests
{
[Fact]
public void CorsCredentials_WithoutOrigins_ThrowsOnValidation()
{
var options = new HttpEndpointOptions
{
Cors = true,
CorsCredentials = true
};
// The strict Cors-without-origins check fires first, which subsumes the credentials
// case: any combination of Cors=true with no whitelist and no resolver is rejected.
var act = () => options.Validate();
act.Should().Throw().WithMessage("*Cors=true requires CorsOrigins*");
}
[Fact]
public void CorsCredentials_WithOrigins_PassesValidation()
{
var options = new HttpEndpointOptions
{
Cors = true,
CorsCredentials = true,
CorsOrigins = "https://example.com"
};
var act = () => options.Validate();
act.Should().NotThrow();
}
[Fact]
public void Defaults_AreCorrect()
{
var options = new HttpEndpointOptions();
options.Method.Should().Be(HttpMethod.GET);
options.Timeout.Should().Be(30_000);
options.ContentType.Should().Be("application/json");
options.ThrowOnError.Should().BeTrue();
options.SkipRequestHeaders.Should().BeFalse();
options.AuthScheme.Should().Be(HttpAuthScheme.None);
options.FollowRedirects.Should().BeTrue();
options.MaxRedirects.Should().Be(50);
options.SkipResponseHeaders.Should().BeFalse();
options.PreserveHostHeader.Should().BeFalse();
options.Host.Should().Be("0.0.0.0");
options.Port.Should().Be(8080);
options.Cors.Should().BeFalse();
options.MaxRequestBodySize.Should().Be(10 * 1024 * 1024);
options.Ssl.Should().BeFalse();
options.ResponseCode.Should().Be(200);
options.InOut.Should().BeFalse();
options.StreamRequest.Should().BeFalse();
}
[Fact]
public void Validate_ValidOptions_NoException()
{
var options = new HttpEndpointOptions();
var act = () => options.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_NegativeTimeout_Throws()
{
var options = new HttpEndpointOptions { Timeout = -1 };
var act = () => options.Validate();
act.Should().Throw().WithMessage("*Timeout*");
}
[Fact]
public void Validate_InvalidPort_Negative_Throws()
{
var options = new HttpEndpointOptions { Port = -1 };
var act = () => options.Validate();
act.Should().Throw().WithMessage("*Port*");
}
[Fact]
public void Validate_InvalidPort_TooHigh_Throws()
{
var options = new HttpEndpointOptions { Port = 70000 };
var act = () => options.Validate();
act.Should().Throw().WithMessage("*Port*");
}
[Fact]
public void Validate_NegativeMaxRedirects_Throws()
{
var options = new HttpEndpointOptions { MaxRedirects = -1 };
var act = () => options.Validate();
act.Should().Throw().WithMessage("*MaxRedirects*");
}
[Fact]
public void Validate_NegativeMaxRequestBodySize_Throws()
{
var options = new HttpEndpointOptions { MaxRequestBodySize = -1 };
var act = () => options.Validate();
act.Should().Throw().WithMessage("*MaxRequestBodySize*");
}
[Fact]
public void Validate_ResponseCode_TooLow_Throws()
{
var options = new HttpEndpointOptions { ResponseCode = 99 };
var act = () => options.Validate();
act.Should().Throw().WithMessage("*ResponseCode*");
}
[Fact]
public void Validate_ResponseCode_TooHigh_Throws()
{
var options = new HttpEndpointOptions { ResponseCode = 600 };
var act = () => options.Validate();
act.Should().Throw().WithMessage("*ResponseCode*");
}
[Fact]
public void Validate_BasicAuth_WithoutUsername_Throws()
{
var options = new HttpEndpointOptions
{
AuthScheme = HttpAuthScheme.Basic,
Password = "pass"
};
var act = () => options.Validate();
act.Should().Throw().WithMessage("*Username*");
}
[Fact]
public void Validate_BasicAuth_WithoutPassword_Throws()
{
var options = new HttpEndpointOptions
{
AuthScheme = HttpAuthScheme.Basic,
Username = "user"
};
var act = () => options.Validate();
act.Should().Throw().WithMessage("*Password*");
}
[Fact]
public void Validate_BasicAuth_WithCredentials_NoException()
{
var options = new HttpEndpointOptions
{
AuthScheme = HttpAuthScheme.Basic,
Username = "user",
Password = "pass"
};
var act = () => options.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_Ssl_WithoutCertPath_DefersToTheBind()
{
// The certificate may legitimately arrive from a named connection factory or from the host
// default (HttpHostingOptions.Tls), neither of which the options object can see. So this is
// no longer an endpoint-level error; "TLS asked for and nothing resolves" is enforced once,
// at the bind, by SharedHttpServerManager — see SharedHostTlsTests, which asserts that a
// listener in exactly this state refuses to open rather than serving plaintext.
var options = new HttpEndpointOptions { Ssl = true };
var act = () => options.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_Ssl_WithCertPath_NoException()
{
var options = new HttpEndpointOptions
{
Ssl = true,
SslCertPath = "/path/to/cert.pfx"
};
var act = () => options.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_ValidBoundaryValues()
{
var options = new HttpEndpointOptions
{
Timeout = 0,
Port = 0,
MaxRedirects = 0,
MaxRequestBodySize = 0,
ResponseCode = 100
};
var act = () => options.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_ResponseCode_599_NoException()
{
var options = new HttpEndpointOptions { ResponseCode = 599 };
var act = () => options.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_Port_65535_NoException()
{
var options = new HttpEndpointOptions { Port = 65535 };
var act = () => options.Validate();
act.Should().NotThrow();
}
// ── ExplicitParameters ──────────────────────────────────────────
[Fact]
public void ExplicitParameters_ExtractsParamPrefix()
{
var options = new HttpEndpointOptions();
options.BindFromUri(new Dictionary
{
["param.userId"] = "123",
["param.format"] = "json",
["method"] = "POST"
});
options.ExplicitParameters.Should().HaveCount(2);
options.ExplicitParameters["userId"].Should().Be("123");
options.ExplicitParameters["format"].Should().Be("json");
}
[Fact]
public void ExplicitParameters_Empty_WhenNoParamPrefix()
{
var options = new HttpEndpointOptions();
options.BindFromUri(new Dictionary
{
["method"] = "POST",
["timeout"] = "5000"
});
options.ExplicitParameters.Should().BeEmpty();
}
[Fact]
public void ExplicitParameters_PreservesExpressionValues()
{
var options = new HttpEndpointOptions();
options.BindFromUri(new Dictionary
{
["param.userId"] = "${header.userId}",
["param.status"] = "active"
});
options.ExplicitParameters["userId"].Should().Be("${header.userId}");
options.ExplicitParameters["status"].Should().Be("active");
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpHeaderFilterStrategyTests.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/tests/redb.Route.Tests.Http/HttpHeaderFilterStrategyTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// headerFilterStrategy=#name on HTTP endpoints, and the options around it: a strategy replaces the component's
/// default on every point of the endpoint; the protocol fields and, on a consumer, received redbHttp.* and
/// response-only fields stay out whatever the strategy says; skipControlHeaders keeps the exchange's control
/// headers from steering the request; the options renamed to Apache Camel's names explain themselves.
///
[Collection("HttpServer")]
public sealed class HttpHeaderFilterStrategyTests : IAsyncLifetime
{
private int _port;
private RouteContext _ctx = null!;
private SharedHttpServerManager _servers = null!;
private readonly TaskCompletionSource> _received = new(TaskCreationOptions.RunContinuationsAsynchronously);
public async Task InitializeAsync()
{
_port = global::redb.Route.Tests.Shared.TestPorts.Next();
_servers = new SharedHttpServerManager();
_ctx = new RouteContext();
_ctx.AddComponent(new HttpComponent { ServerManager = _servers });
_ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false });
_ctx.AddToRegistry("everything", new DefaultHeaderFilterStrategy { AllowNullValues = true });
_ctx.AddToRegistry("noServerHeader", new DefaultHeaderFilterStrategy { InFilter = ["X-Server"] });
var port = _port;
_ctx.AddRoutes(r => r.From($"http://127.0.0.1:{port}/plain?inOut=true&methods=GET,POST,DELETE").Process(e =>
{
_received.TrySetResult(new Dictionary(e.In.Headers, StringComparer.OrdinalIgnoreCase));
e.In.Headers["X-Server"] = "s1";
e.In.Headers["X-Reply"] = "r1";
e.In.Body = "reply";
}));
_ctx.AddRoutes(r => r.From($"http://127.0.0.1:{port}/guarded?inOut=true&methods=POST&headerFilterStrategy=#everything")
.Process(e =>
{
_received.TrySetResult(new Dictionary(e.In.Headers, StringComparer.OrdinalIgnoreCase));
e.In.Headers["redbInternal"] = "with the default it stays home";
e.In.Body = "reply";
}));
await _ctx.Start();
}
public async Task DisposeAsync()
{
await _ctx.DisposeAsync();
await _servers.DisposeAsync();
}
private async Task Send(string path, string options, Action headers)
{
var producer = _ctx.GetEndpoint($"http://127.0.0.1:{_port}/{path}?{options}").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("body"));
headers(exchange);
await producer.Process(exchange);
await producer.Stop();
return exchange;
}
private Task> Received() => _received.Task.WaitAsync(TimeSpan.FromSeconds(10));
[Fact]
public async Task AWhitelist_SendsOnlyTheNamedHeader()
{
await Send("plain", "method=POST&headerFilterStrategy=#correlationOnly", e =>
{
e.In.Headers["Correlation-ID"] = "c-42";
e.In.Headers["X-Corr"] = "c1";
e.In.Headers["Authorization"] = "Bearer secret";
});
var request = await Received();
request["Correlation-ID"].Should().Be("c-42");
request.Should().NotContainKey("X-Corr");
request.Should().NotContainKey("Authorization", "the whitelist does not name it");
}
[Fact]
public async Task AStrategy_ReplacesTheDefault_ButNotTheProtocolFields()
{
// 'everything' lets every header through, the control headers the default keeps back included.
await Send("plain", "method=POST&headerFilterStrategy=#everything", e =>
{
e.In.Headers[HttpHeaders.Url] = "http://elsewhere/";
e.In.Headers["Connection"] = "close-me";
e.In.Headers["Host"] = "elsewhere.example.com";
});
var request = await Received();
request.Should().NotContainKey("Connection", "a protocol field is the transport's");
request[HttpHeaders.Url].Should().NotBe("http://elsewhere/",
"it went out under the strategy, but the consumer sets its own redbHttp.Url and never takes a received one");
}
[Fact]
public async Task OnAProducer_TheStrategyAlsoFiltersTheResponse()
{
var sent = await Send("plain", "method=POST&headerFilterStrategy=#noServerHeader", _ => { });
var response = (sent.HasOut ? sent.Out! : sent.In).Headers;
response["X-Reply"].Should().Be("r1");
response.Should().NotContainKey("X-Server", "the incoming filter of the producer's strategy names it");
}
[Fact]
public async Task OnAConsumer_AStrategyNeverLetsInAReceivedRedbHttpHeader()
{
// The guard against a caller posing as the transport (redbHttp.RemoteAddress drives rate limiting) holds
// under a strategy that lets everything through.
await Send("guarded", "method=POST&headerFilterStrategy=#everything", e =>
{
e.In.Headers[HttpHeaders.RemoteAddress] = "10.0.0.1";
e.In.Headers["Set-Cookie"] = "planted=1";
e.In.Headers["X-Corr"] = "c1";
});
var request = await Received();
request["X-Corr"].Should().Be("c1");
request[HttpHeaders.RemoteAddress].Should().Be("127.0.0.1", "the socket address, not the caller's header");
request.Should().NotContainKey("Set-Cookie", "a response-only field never comes in from a request");
}
[Fact]
public async Task OnAConsumer_TheStrategyDecidesTheResponseHeaders()
{
var sent = await Send("guarded", "method=POST", _ => { });
var response = (sent.HasOut ? sent.Out! : sent.In).Headers;
response["redbInternal"].Should().Be("with the default it stays home",
"'everything' lets out what the default keeps back (redb*)");
}
[Fact]
public async Task SkipControlHeaders_TheEndpointDecidesTheMethodAndQuery()
{
await Send("plain", "method=POST&skipControlHeaders=true", e =>
{
e.In.Headers[HttpHeaders.Method] = "DELETE";
e.In.Headers[HttpHeaders.Query] = "injected=1";
});
var request = await Received();
request[HttpHeaders.Method].Should().Be("POST", "the control header from the exchange is ignored");
request.Should().NotContainKey(HttpHeaders.QueryParamPrefix + "injected");
}
[Fact]
public async Task AStrategyTheRegistryDoesNotHold_FailsWhenTheProducerIsBuilt()
{
var act = () => _ctx.GetEndpoint($"http://127.0.0.1:{_port}/plain?method=POST&headerFilterStrategy=#nope").CreateProducer();
act.Should().Throw().WithMessage("*'#nope'*");
}
[Theory]
[InlineData("bridgeHeaders", "skipRequestHeaders")]
[InlineData("copyResponseHeaders", "skipResponseHeaders")]
public void ARenamedOption_NamesItsCamelName(string old, string renamed)
{
var act = () => _ctx.GetEndpoint($"http://127.0.0.1:{_port}/plain?method=POST&{old}=false");
act.Should().Throw().WithMessage($"*'{old}'*'{renamed}'*");
}
[Fact]
public void TheDsl_WritesTheCamelNames()
{
var uri = redb.Route.Http.Http.Post("http://example.com/x")
.SkipRequestHeaders().SkipResponseHeaders().SkipControlHeaders().HeaderFilterStrategy("correlationOnly")
.Build();
uri.Should().Contain("skipRequestHeaders=true").And.Contain("skipResponseHeaders=true")
.And.Contain("skipControlHeaders=true").And.Contain("headerFilterStrategy=correlationOnly");
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpHeaderMappingCharacterizationTests.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/tests/redb.Route.Tests.Http/HttpHeaderMappingCharacterizationTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// What crosses an HTTP request and its response today, all four points: pinned before the header filter strategy
/// takes the rule over, so the transport's default keeps it exactly.
///
/// - producer, request: every exchange header but the control and protocol headers and empty values; skipRequestHeaders=true
/// sends none;
/// - consumer, request: every request header but HTTP/2 pseudo-headers, redbHttp.* and response-only
/// fields;
/// - consumer, response: every exchange header but the non-bridged ones, redb*/Camel* and the values
/// the request brought;
/// - producer, response: every response header (unless skipResponseHeaders=true).
///
/// Plus what the inventory found: a redbHttp.* header the list does not name crosses as a request header
/// (finding 3.3), and a redbHttp.Method on the exchange, wherever it came from, sets the method (finding 3.1).
///
[Collection("HttpServer")]
public sealed class HttpHeaderMappingCharacterizationTests : IAsyncLifetime
{
private int _port;
private RouteContext _ctx = null!;
private SharedHttpServerManager _servers = null!;
private readonly TaskCompletionSource> _received = new(TaskCreationOptions.RunContinuationsAsynchronously);
public async Task InitializeAsync()
{
_port = global::redb.Route.Tests.Shared.TestPorts.Next();
_servers = new SharedHttpServerManager();
_ctx = new RouteContext();
_ctx.AddComponent(new HttpComponent { ServerManager = _servers });
var port = _port;
_ctx.AddRoutes(r => r.From($"http://127.0.0.1:{port}/hdr?inOut=true&methods=GET,POST,DELETE").Process(e =>
{
_received.TrySetResult(new Dictionary(e.In.Headers, StringComparer.OrdinalIgnoreCase));
e.In.Headers.Clear();
e.In.Headers["X-Reply"] = "r1";
e.In.Headers["X-Int"] = 7;
e.In.Headers["X-Null"] = null;
e.In.Headers["redbInternal"] = "never";
e.In.Headers["CamelSomething"] = "never";
e.In.Body = "reply";
}));
_ctx.AddRoutes(r => r.From($"http://127.0.0.1:{port}/echo?inOut=true&methods=POST").Process(e =>
{
e.In.Headers["X-Reply"] = "r1";
e.In.Body = "reply";
}));
await _ctx.Start();
}
public async Task DisposeAsync()
{
await _ctx.DisposeAsync();
await _servers.DisposeAsync();
}
private async Task Send(Action headers, string? extra = null)
{
var producer = _ctx.GetEndpoint($"http://127.0.0.1:{_port}/hdr?{extra ?? "method=POST"}").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("body"));
headers(exchange);
await producer.Process(exchange);
await producer.Stop();
return exchange;
}
[Fact]
public async Task RequestAndResponse_TheHeadersThatCross()
{
var sent = await Send(e =>
{
e.In.Headers["X-Corr"] = "c1";
e.In.Headers["X-Int"] = 42;
e.In.Headers["X-Null"] = null;
e.In.Headers["Authorization"] = "Bearer secret";
e.In.Headers["Connection"] = "close-me";
e.In.Headers[HttpHeaders.QueryParamPrefix + "sort"] = "asc";
});
var request = await _received.Task.WaitAsync(TimeSpan.FromSeconds(10));
request["X-Corr"].Should().Be("c1");
request["X-Int"].Should().Be("42", "a value crosses as its text");
request.Should().NotContainKey("X-Null", "a null value is skipped");
request["Authorization"].Should().Be("Bearer secret", "nothing filters a credential (Camel does not either)");
request.Should().NotContainKey("Connection", "a hop-by-hop header is not bridged");
request.Should().NotContainKey(HttpHeaders.QueryParamPrefix + "sort",
"the consumer drops every redbHttp.* it receives (the producer sent it: see finding 3.3)");
var response = (sent.HasOut ? sent.Out! : sent.In).Headers;
response["X-Reply"].Should().Be("r1");
response["X-Int"].Should().Be("7");
response.Should().NotContainKey("X-Null");
response.Should().NotContainKey("redbInternal", "the consumer does not answer with redb* headers");
response.Should().NotContainKey("CamelSomething", "nor with Camel* ones");
}
[Fact]
public async Task ARedbHttpHeaderTheListDoesNotName_CrossesAsARequestHeader()
{
// Finding 3.3: on the wire under its own name; the consumer then drops it as a redbHttp.* header, so it is
// seen on the wire only. Pinned on the producer side through the request the server received.
string? onTheWire = null;
await using var ctx = new RouteContext();
await using var servers = new SharedHttpServerManager();
ctx.AddComponent(new HttpComponent { ServerManager = servers });
var probePort = global::redb.Route.Tests.Shared.TestPorts.Next();
using var listener = new System.Net.HttpListener();
listener.Prefixes.Add($"http://127.0.0.1:{probePort}/");
listener.Start();
var serve = Task.Run(async () =>
{
var context = await listener.GetContextAsync();
onTheWire = context.Request.Headers[HttpHeaders.QueryParamPrefix + "sort"];
context.Response.StatusCode = 200;
context.Response.Close();
});
await ctx.Start();
var producer = ctx.GetEndpoint($"http://127.0.0.1:{probePort}/probe?method=GET").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message());
exchange.In.Headers[HttpHeaders.QueryParamPrefix + "sort"] = "asc";
await producer.Process(exchange);
await producer.Stop();
await serve.WaitAsync(TimeSpan.FromSeconds(10));
onTheWire.Should().Be("asc", "the producer's list names only some redbHttp.* headers");
}
[Fact]
public async Task ARedbHttpMethodHeaderOnTheExchange_SetsTheMethod()
{
// Finding 3.1: whatever put it there (a broker message's headers cross into the exchange whole).
await Send(e => e.In.Headers[HttpHeaders.Method] = "DELETE");
var request = await _received.Task.WaitAsync(TimeSpan.FromSeconds(10));
request[HttpHeaders.Method].Should().Be("DELETE", "the endpoint said POST; the header won");
}
[Fact]
public async Task TheResponse_DoesNotEchoTheRequestHeaders()
{
var producer = _ctx.GetEndpoint($"http://127.0.0.1:{_port}/echo?method=POST").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("body"));
exchange.In.Headers["X-Corr"] = "c1";
await producer.Process(exchange);
await producer.Stop();
var response = (exchange.HasOut ? exchange.Out! : exchange.In).Headers;
response["X-Reply"].Should().Be("r1");
response.Should().NotContainKey("X-Corr", "the consumer does not answer with a value the request brought");
}
[Fact]
public async Task SkipRequestHeaders_SendsNoExchangeHeader()
{
await Send(e => e.In.Headers["X-Corr"] = "c1", "method=POST&skipRequestHeaders=true");
var request = await _received.Task.WaitAsync(TimeSpan.FromSeconds(10));
request.Should().NotContainKey("X-Corr");
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpInboundAuthTests.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/tests/redb.Route.Tests.Http/HttpInboundAuthTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Http.Rest;
namespace redb.Route.Tests.Http;
///
/// Inbound authentication on an http: consumer and on a REST declaration: Basic against configured credentials,
/// Bearer through a registered . A refused request gets 401 with
/// WWW-Authenticate and never reaches the route; an accepted one reaches it with the principal on the exchange
/// and without the Authorization header.
///
[Collection("HttpServer")]
public class HttpInboundAuthTests : IAsyncLifetime
{
private sealed class TokenValidator : IHttpTokenValidator
{
public Task ValidateAsync(string token, CancellationToken ct)
=> Task.FromResult(token == "good-token"
? new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name, "svc-orders")], "Bearer"))
: null);
}
/// What the route saw: the principal and whether an Authorization header was still there.
private sealed record Seen(string? User, bool AuthorizationHeader);
private readonly List _seen = [];
private int _port;
private HttpClient _client = null!;
private RouteContext _ctx = null!;
private SharedHttpServerManager _servers = null!;
public async Task InitializeAsync()
{
_port = global::redb.Route.Tests.Shared.TestPorts.Next();
_client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{_port}") };
_servers = new SharedHttpServerManager();
_ctx = new RouteContext();
_ctx.AddComponent(new HttpComponent { ServerManager = _servers });
_ctx.AddToRegistry("tokens", new TokenValidator());
var port = _port;
_ctx.AddRoutes(r =>
{
r.From($"http://127.0.0.1:{port}/basic?inboundAuth=basic&inboundUsername=admin&inboundPassword=s3cret&inboundRealm=orders")
.Process(Remember).SetBody("ok");
// "admin:s3cret1" is 13 bytes: its base64 ends in "==", so the last character has 4 unused bits.
r.From($"http://127.0.0.1:{port}/padded?inboundAuth=basic&inboundUsername=admin&inboundPassword=s3cret1")
.Process(Remember).SetBody("ok");
r.From($"http://127.0.0.1:{port}/bearer?inboundAuth=bearer&tokenValidator=#tokens")
.Process(Remember).SetBody("ok");
r.Rest("/api", o =>
{
o.Host = "127.0.0.1"; o.Port = port; o.OpenApi = false;
o.InboundAuth = HttpAuthScheme.Bearer; o.TokenValidator = "#tokens";
}).Get("/orders").Route().Process(Remember).SetBody("orders");
});
await _ctx.Start();
}
private void Remember(IExchange exchange)
{
lock (_seen)
_seen.Add(new Seen(ExchangePrincipal.Get(exchange)?.Identity?.Name, exchange.In.Headers.ContainsKey("Authorization")));
}
public async Task DisposeAsync()
{
_client.Dispose();
await _ctx.DisposeAsync();
await _servers.DisposeAsync();
}
private Task Get(string path, AuthenticationHeaderValue? auth)
{
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, path);
request.Headers.Authorization = auth;
return _client.SendAsync(request);
}
private static AuthenticationHeaderValue Basic(string user, string password)
=> new("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{password}")));
// ── Basic ────────────────────────────────────────────────────────────────
[Fact]
public async Task Basic_without_credentials_is_401_with_the_challenge()
{
var response = await Get("/basic", null);
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
response.Headers.WwwAuthenticate.ToString().Should().Be("Basic realm=\"orders\", charset=\"UTF-8\"");
_seen.Should().BeEmpty("a refused request never reaches the route");
}
[Theory]
[InlineData("admin", "wrong")]
[InlineData("root", "s3cret")]
[InlineData("admin", "")]
public async Task Basic_with_wrong_credentials_is_401(string user, string password)
{
(await Get("/basic", Basic(user, password))).StatusCode.Should().Be(HttpStatusCode.Unauthorized);
_seen.Should().BeEmpty();
}
[Fact]
public async Task Basic_that_is_not_base64_is_401()
{
(await Get("/basic", new AuthenticationHeaderValue("Basic", "***"))).StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Basic_with_the_right_credentials_reaches_the_route_with_the_principal_and_without_the_header()
{
var response = await Get("/basic", Basic("admin", "s3cret"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
_seen.Should().ContainSingle().Which.Should().Be(new Seen("admin", AuthorizationHeader: false));
}
[Fact]
public async Task Basic_with_non_zero_unused_bits_in_the_last_character_is_401_on_every_runtime()
{
var canonical = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:s3cret1"));
canonical.Should().EndWith("==");
(await Get("/padded", new AuthenticationHeaderValue("Basic", canonical))).StatusCode.Should().Be(HttpStatusCode.OK);
// .NET 10 Convert decodes the last character with its unused bits set to the same bytes, .NET 11 refuses it;
// a credential has one spelling, so the consumer refuses it on both.
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var chars = canonical.ToCharArray();
var last = canonical.Length - 3;
chars[last] = alphabet[alphabet.IndexOf(chars[last], StringComparison.Ordinal) | 0b1];
var response = await Get("/padded", new AuthenticationHeaderValue("Basic", new string(chars)));
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Basic_does_not_accept_a_bearer_token()
{
(await Get("/basic", new AuthenticationHeaderValue("Bearer", "good-token"))).StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
// ── Bearer ───────────────────────────────────────────────────────────────
[Fact]
public async Task Bearer_without_a_token_is_401_with_the_challenge()
{
var response = await Get("/bearer", null);
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
response.Headers.WwwAuthenticate.ToString().Should().StartWith("Bearer realm=");
}
[Fact]
public async Task Bearer_refused_by_the_validator_is_401_invalid_token()
{
var response = await Get("/bearer", new AuthenticationHeaderValue("Bearer", "forged"));
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
response.Headers.WwwAuthenticate.ToString().Should().Contain("error=\"invalid_token\"");
_seen.Should().BeEmpty();
}
[Fact]
public async Task Bearer_accepted_by_the_validator_reaches_the_route_with_its_principal()
{
(await Get("/bearer", new AuthenticationHeaderValue("Bearer", "good-token"))).StatusCode.Should().Be(HttpStatusCode.OK);
_seen.Should().ContainSingle().Which.Should().Be(new Seen("svc-orders", AuthorizationHeader: false));
}
[Fact]
public async Task A_rest_declaration_protects_its_verbs()
{
(await Get("/api/orders", null)).StatusCode.Should().Be(HttpStatusCode.Unauthorized);
(await Get("/api/orders", new AuthenticationHeaderValue("Bearer", "good-token"))).StatusCode.Should().Be(HttpStatusCode.OK);
}
// ── Declaration errors ───────────────────────────────────────────────────
private static async Task StartWith(string uri, Action? arrange = null)
{
await using var servers = new SharedHttpServerManager();
await using var ctx = new RouteContext();
ctx.AddComponent(new HttpComponent { ServerManager = servers });
arrange?.Invoke(ctx);
ctx.AddRoutes(r => r.From(uri).SetBody("x"));
return await Record.ExceptionAsync(() => ctx.Start());
}
private static string Uri(string query)
{
var port = global::redb.Route.Tests.Shared.TestPorts.Next();
return $"http://127.0.0.1:{port}/x?{query}";
}
[Fact]
public async Task An_unregistered_token_validator_stops_the_start()
=> (await StartWith(Uri("inboundAuth=bearer&tokenValidator=#nobody")))!.ToString().Should().Contain("nobody");
[Theory]
[InlineData("inboundAuth=basic&inboundUsername=admin", "inboundPassword")]
[InlineData("inboundAuth=bearer", "tokenValidator")]
[InlineData("inboundUsername=admin&inboundPassword=x", "inboundAuth")]
[InlineData("tokenValidator=#tokens", "inboundAuth")]
[InlineData("inboundAuth=basic&inboundUsername=a&inboundPassword=b&tokenValidator=#tokens", "tokenValidator")]
[InlineData("inboundAuth=basic&inboundUsername=a&inboundPassword=b&inboundRealm=a\"b", "inboundRealm")]
public async Task An_incomplete_or_contradictory_declaration_stops_the_start(string query, string named)
=> (await StartWith(Uri(query)))!.ToString().Should().Contain(named);
[Fact]
public async Task Inbound_options_on_a_producer_are_refused()
{
await using var ctx = new RouteContext();
ctx.AddComponent(new HttpComponent());
var endpoint = ctx.GetEndpoint("http://127.0.0.1:1/x?inboundAuth=basic&inboundUsername=a&inboundPassword=b");
var act = () => endpoint.CreateProducer();
act.Should().Throw().WithMessage("*inboundAuth*consumer*")
.Which.Message.Should().NotContain("inboundPassword=b");
}
}
/// The side-only options of the http: endpoint carry their role as a declaration tooling can read.
public class HttpEndpointRoleDeclarationTests
{
[Theory]
[InlineData(nameof(HttpEndpointOptions.AuthScheme), EndpointRole.Producer)]
[InlineData(nameof(HttpEndpointOptions.Username), EndpointRole.Producer)]
[InlineData(nameof(HttpEndpointOptions.Password), EndpointRole.Producer)]
[InlineData(nameof(HttpEndpointOptions.AuthToken), EndpointRole.Producer)]
[InlineData(nameof(HttpEndpointOptions.InboundAuth), EndpointRole.Consumer)]
[InlineData(nameof(HttpEndpointOptions.InboundUsername), EndpointRole.Consumer)]
[InlineData(nameof(HttpEndpointOptions.InboundPassword), EndpointRole.Consumer)]
[InlineData(nameof(HttpEndpointOptions.InboundRealm), EndpointRole.Consumer)]
[InlineData(nameof(HttpEndpointOptions.TokenValidator), EndpointRole.Consumer)]
public void The_option_declares_its_role(string property, EndpointRole role)
=> EndpointOptions.RoleOf(typeof(HttpEndpointOptions).GetProperty(property)!).Should().Be(role);
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpIntegrationTests.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/tests/redb.Route.Tests.Http/HttpIntegrationTests.cs
----
using System.Net;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// End-to-end integration tests: HttpProducer sending to HttpConsumer on the same machine.
/// Verifies the full roundtrip through real HTTP with Kestrel.
///
[Collection("HttpServer")]
public class HttpIntegrationTests : IAsyncLifetime
{
private HttpConsumer? _consumer;
private HttpProducer? _producer;
private int _port;
private IExchange? _receivedExchange;
private SharedHttpServerManager? _serverManager;
public Task InitializeAsync()
{
_port = GetFreePort();
_serverManager = new SharedHttpServerManager();
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
if (_producer is not null) await _producer.Stop();
if (_consumer is not null) await _consumer.Stop();
if (_serverManager is not null) await _serverManager.DisposeAsync();
}
private (HttpConsumer consumer, HttpProducer producer) CreatePair(
string route = "/webhook",
bool inOut = false,
Dictionary? consumerExtra = null,
Dictionary? producerExtra = null,
Func? onProcess = null)
{
// Consumer
var consumerComponent = new HttpComponent();
var consumerParams = new Dictionary
{
["host"] = "127.0.0.1",
["port"] = _port.ToString(),
["inOut"] = inOut.ToString().ToLower()
};
if (consumerExtra is not null)
foreach (var (k, v) in consumerExtra)
consumerParams[k] = v;
var consumerPath = $"/127.0.0.1:{_port}{route}";
var consumerUri = new EndpointUri("http", consumerPath, $"http:{consumerPath}", consumerParams);
var consumerEndpoint = (HttpEndpoint)consumerComponent.CreateEndpoint(consumerUri);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(async ci =>
{
var ex = ci.Arg();
_receivedExchange = ex;
if (onProcess is not null)
await onProcess(ex);
});
_consumer = new HttpConsumer(consumerEndpoint, processor, consumerEndpoint.EndpointOptions, _serverManager!);
// Producer
var producerComponent = new HttpComponent();
var producerParams = new Dictionary
{
["method"] = "POST"
};
if (producerExtra is not null)
foreach (var (k, v) in producerExtra)
producerParams[k] = v;
var producerPath = $"/127.0.0.1:{_port}{route}";
var producerUri = new EndpointUri("http", producerPath, $"http:{producerPath}", producerParams);
var producerEndpoint = (HttpEndpoint)producerComponent.CreateEndpoint(producerUri);
_producer = new HttpProducer(producerEndpoint, producerEndpoint.EndpointOptions);
return (_consumer, _producer);
}
[Fact]
public async Task Integration_Producer_To_Consumer_InOnly()
{
var (consumer, producer) = CreatePair();
await consumer.Start();
await producer.Start();
var exchange = new Exchange(new Message("""{"order":"O-123","total":99.99}"""));
exchange.In.Headers["X-Request-Id"] = "integration-test-001";
await producer.Process(exchange);
// Verify consumer received the request
_receivedExchange.Should().NotBeNull();
var receivedBody = Encoding.UTF8.GetString((byte[])_receivedExchange!.In.Body!);
receivedBody.Should().Be("""{"order":"O-123","total":99.99}""");
_receivedExchange.In.Headers.Should().ContainKey("X-Request-Id");
// Verify producer got 200 response
exchange.Out!.Headers[HttpHeaders.StatusCode].Should().Be(200);
}
[Fact]
public async Task Integration_Producer_To_Consumer_InOut()
{
var (consumer, producer) = CreatePair(inOut: true, onProcess: ex =>
{
// Echo back with transformation
var inputBody = Encoding.UTF8.GetString((byte[])ex.In.Body!);
ex.Out = new Message($"PROCESSED: {inputBody}");
return Task.CompletedTask;
});
await consumer.Start();
await producer.Start();
var exchange = new Exchange(new Message("hello"));
await producer.Process(exchange);
// Verify producer received the processed response
var responseBody = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
responseBody.Should().Be("PROCESSED: hello");
exchange.Out!.Headers[HttpHeaders.StatusCode].Should().Be(200);
}
[Fact]
public async Task Integration_MultipleRequests()
{
var (consumer, producer) = CreatePair();
await consumer.Start();
await producer.Start();
for (var i = 0; i < 5; i++)
{
var exchange = new Exchange(new Message($"message-{i}"));
await producer.Process(exchange);
exchange.Out!.Headers[HttpHeaders.StatusCode].Should().Be(200);
}
consumer.ProcessedCount.Should().Be(5);
}
[Fact]
public async Task Integration_CustomHeaders_Roundtrip()
{
var (consumer, producer) = CreatePair(inOut: true, onProcess: ex =>
{
// Read custom header, echo it back
var requestId = ex.In.Headers["X-Trace-Id"]?.ToString();
ex.Out = new Message($"trace:{requestId}");
return Task.CompletedTask;
});
await consumer.Start();
await producer.Start();
var exchange = new Exchange(new Message("trace-test"));
exchange.In.Headers["X-Trace-Id"] = "TRACE-42";
await producer.Process(exchange);
var responseBody = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
responseBody.Should().Be("trace:TRACE-42");
}
// ── StreamRequest integration tests ──
[Fact]
public async Task Integration_StreamRequest_ConsumerReceivesStream()
{
Type? bodyType = null;
string? bodyContent = null;
var (consumer, producer) = CreatePair(
consumerExtra: new Dictionary { ["streamRequest"] = "true" },
onProcess: async ex =>
{
bodyType = ex.In.Body?.GetType();
var stream = (Stream)ex.In.Body!;
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
bodyContent = await reader.ReadToEndAsync();
});
await consumer.Start();
await producer.Start();
var exchange = new Exchange(new Message("streamed-payload"));
await producer.Process(exchange);
bodyType.Should().BeAssignableTo(typeof(Stream));
bodyContent.Should().Be("streamed-payload");
}
[Fact]
public async Task Integration_StreamRequest_InOut_EchoRoundtrip()
{
var (consumer, producer) = CreatePair(
inOut: true,
consumerExtra: new Dictionary { ["streamRequest"] = "true" },
onProcess: async ex =>
{
var stream = (Stream)ex.In.Body!;
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
var content = await reader.ReadToEndAsync();
ex.Out = new Message($"ECHO:{content}");
});
await consumer.Start();
await producer.Start();
var exchange = new Exchange(new Message("stream-inout-test"));
await producer.Process(exchange);
var responseBody = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
responseBody.Should().Be("ECHO:stream-inout-test");
}
// ── StreamResponse integration tests ──
[Fact]
public async Task Integration_StreamResponse_ProducerGetsStream()
{
var (consumer, producer) = CreatePair(
inOut: true,
producerExtra: new Dictionary { ["streamResponse"] = "true" },
onProcess: ex =>
{
ex.Out = new Message("response-as-stream");
return Task.CompletedTask;
});
await consumer.Start();
await producer.Start();
var exchange = new Exchange(new Message("trigger"));
await producer.Process(exchange);
exchange.Out!.Body.Should().BeAssignableTo();
var stream = (Stream)exchange.Out!.Body!;
using var reader = new StreamReader(stream, Encoding.UTF8);
var content = await reader.ReadToEndAsync();
content.Should().Be("response-as-stream");
}
// ── Both StreamRequest + StreamResponse ──
[Fact]
public async Task Integration_StreamRequest_And_StreamResponse_FullStreaming()
{
var (consumer, producer) = CreatePair(
inOut: true,
consumerExtra: new Dictionary { ["streamRequest"] = "true" },
producerExtra: new Dictionary { ["streamResponse"] = "true" },
onProcess: async ex =>
{
var stream = (Stream)ex.In.Body!;
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
var content = await reader.ReadToEndAsync();
ex.Out = new Message($"STREAMED:{content}");
});
await consumer.Start();
await producer.Start();
var exchange = new Exchange(new Message("full-stream-test"));
await producer.Process(exchange);
exchange.Out!.Body.Should().BeAssignableTo();
var outStream = (Stream)exchange.Out!.Body!;
using var outReader = new StreamReader(outStream, Encoding.UTF8);
var result = await outReader.ReadToEndAsync();
result.Should().Be("STREAMED:full-stream-test");
}
[Fact]
public async Task Integration_StreamRequest_LargePayload_NoBuffering()
{
string? capturedContent = null;
var (consumer, producer) = CreatePair(
consumerExtra: new Dictionary { ["streamRequest"] = "true" },
onProcess: async ex =>
{
var stream = (Stream)ex.In.Body!;
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
capturedContent = await reader.ReadToEndAsync();
});
await consumer.Start();
await producer.Start();
// 100KB payload
var largePayload = new string('X', 100 * 1024);
var exchange = new Exchange(new Message(largePayload));
await producer.Process(exchange);
capturedContent.Should().HaveLength(100 * 1024);
capturedContent.Should().Be(largePayload);
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpMimeMultipartTests.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/tests/redb.Route.Tests.Http/HttpMimeMultipartTests.cs
----
using System.Net;
using AwesomeAssertions;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.DataFormats.Mime;
using redb.Route.Http;
using redb.Route.Serialization;
namespace redb.Route.Tests.Http;
///
/// A form with files over real HTTP: posted by to an http: consumer and read by the MIME
/// multipart format, and a form the format writes read by ASP.NET Core's own multipart reader, so the wire matches what
/// both sides of the ecosystem produce and accept.
///
[Collection("HttpServer")]
public class HttpMimeMultipartTests
{
private static readonly byte[] Pdf = [0x25, 0x50, 0x44, 0x46, 0x00, 0xFF, 0x0D, 0x0A, 0x2D, 0x2D, 0x00];
private static readonly byte[] Jpeg = [0xFF, 0xD8, 0xFF, 0x00, 0x0D, 0x0A, 0xFF, 0xD9];
[Fact]
public async Task A_form_posted_over_http_reads_as_two_fields_and_two_files_byte_for_byte()
{
var port = global::redb.Route.Tests.Shared.TestPorts.Next();
await using var context = new RouteContext($"http-mime-{Guid.NewGuid():N}");
context.AddComponent(new HttpComponent { ServerManager = new SharedHttpServerManager() });
context.AddMimeMultipartDataFormat();
// Read while the exchange is alive: a spooled attachment is released with it, like a stream body.
var seen = new TaskCompletionSource<(FormBody Fields, List<(string Name, string Type, byte[] Bytes)> Files)>(
TaskCreationOptions.RunContinuationsAsynchronously);
context.AddRoutes(r => r.From($"http://127.0.0.1:{port}/claims")
.ConvertBody()
.Process(e => seen.TrySetResult(((FormBody)e.In.Body!,
e.In.Attachments.Select(a => (a.Name, a.ContentType, a.Content.ReadAllBytes())).ToList()))));
await context.Start();
using var client = new HttpClient();
using var form = new MultipartFormDataContent();
form.Add(new StringContent("12345"), "claim");
form.Add(new StringContent("претензия"), "theme");
form.Add(File(Pdf, "application/pdf"), "docs", "акт.pdf");
form.Add(File(Jpeg, "image/jpeg"), "docs", "photo.jpg");
var response = await client.PostAsync($"http://127.0.0.1:{port}/claims", form);
response.StatusCode.Should().Be(HttpStatusCode.OK);
var (fields, files) = await seen.Task.WaitAsync(TimeSpan.FromSeconds(10));
fields.Get("claim").Should().Be("12345");
fields.Get("theme").Should().Be("претензия");
files.Select(f => f.Name).Should().Equal("акт.pdf", "photo.jpg");
files[0].Type.Should().Be("application/pdf");
files[0].Bytes.Should().Equal(Pdf);
files[1].Bytes.Should().Equal(Jpeg);
}
[Fact]
public async Task A_form_the_format_writes_is_read_by_ASP_NET_Core()
{
var exchange = new Exchange(new Message(new FormBody().Add("claim", "7").Add("theme", "претензия")));
exchange.In.Attachments.Add(new Attachment
{
Name = "акт.pdf", FileName = "акт.pdf", ContentType = "application/pdf", Content = AttachmentContent.FromBytes(Pdf)
});
await new MimeMultipartDataFormat().MarshalAsync(exchange);
var boundary = HeaderUtilities.RemoveQuotes(
Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse(exchange.In.ContentType).Boundary).Value!;
var body = (Stream)exchange.In.Body!;
body.Position = 0;
var reader = new MultipartReader(boundary, body);
var parts = new List<(string? Name, string? FileName, byte[] Content)>();
while (await reader.ReadNextSectionAsync() is { } section)
{
ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var disposition).Should().BeTrue();
using var content = new MemoryStream();
await section.Body.CopyToAsync(content);
parts.Add((HeaderUtilities.RemoveQuotes(disposition!.Name).Value,
HeaderUtilities.RemoveQuotes(disposition.FileName).Value,
content.ToArray()));
}
parts.Select(p => p.Name).Should().Equal("claim", "theme", "акт.pdf");
System.Text.Encoding.UTF8.GetString(parts[1].Content).Should().Be("претензия");
parts[2].FileName.Should().Be("акт.pdf");
parts[2].Content.Should().Equal(Pdf);
}
private static ByteArrayContent File(byte[] bytes, string type)
{
var content = new ByteArrayContent(bytes);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(type);
return content;
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpProducerTests.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/tests/redb.Route.Tests.Http/HttpProducerTests.cs
----
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using HttpMethod = redb.Route.Http.HttpMethod;
namespace redb.Route.Tests.Http;
///
/// Tests for HttpProducer using a real embedded HTTP test server.
/// Each test starts a lightweight Kestrel server, sends real HTTP requests, and verifies the results.
///
[Collection("HttpServer")]
public class HttpProducerTests : IAsyncLifetime
{
private WebApplication? _server;
private int _port;
private string _baseUrl = null!;
// Captures from test server
private string? _lastRequestMethod;
private string? _lastRequestPath;
private string? _lastRequestBody;
private string? _lastRequestContentType;
private Dictionary _lastRequestHeaders = new(StringComparer.OrdinalIgnoreCase);
// Configurable response from test server
private int _responseStatusCode = 200;
private string _responseBody = """{"result":"ok"}""";
private string _responseContentType = "application/json";
private Dictionary _responseHeaders = new();
public async Task InitializeAsync()
{
_port = GetFreePort();
_baseUrl = $"http://localhost:{_port}";
var builder = WebApplication.CreateSlimBuilder();
builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, _port));
builder.Logging.ClearProviders();
_server = builder.Build();
_server.Map("/{**catch}", HandleTestRequest);
await _server.StartAsync();
}
public async Task DisposeAsync()
{
if (_server is not null)
{
await _server.StopAsync();
await _server.DisposeAsync();
}
}
private async Task HandleTestRequest(Microsoft.AspNetCore.Http.HttpContext ctx)
{
_lastRequestMethod = ctx.Request.Method;
_lastRequestPath = ctx.Request.Path + ctx.Request.QueryString;
_lastRequestContentType = ctx.Request.ContentType;
_lastRequestHeaders.Clear();
foreach (var h in ctx.Request.Headers)
{
_lastRequestHeaders[h.Key] = h.Value.ToString();
}
if (ctx.Request.ContentLength > 0 || ctx.Request.ContentType is not null)
{
using var reader = new StreamReader(ctx.Request.Body, Encoding.UTF8);
_lastRequestBody = await reader.ReadToEndAsync();
}
else
{
_lastRequestBody = null;
}
ctx.Response.StatusCode = _responseStatusCode;
ctx.Response.ContentType = _responseContentType;
foreach (var (key, value) in _responseHeaders)
{
ctx.Response.Headers.Append(key, value);
}
await ctx.Response.WriteAsync(_responseBody);
}
private HttpEndpoint CreateEndpoint(Dictionary? parameters = null)
{
var component = new HttpComponent();
var pars = parameters ?? new Dictionary();
var path = $"/localhost:{_port}";
var uri = new EndpointUri("http", path, $"http:{path}", pars);
return (HttpEndpoint)component.CreateEndpoint(uri);
}
private HttpEndpoint CreateEndpointWithPath(string route, Dictionary? parameters = null)
{
var component = new HttpComponent();
var pars = parameters ?? new Dictionary();
var path = $"/localhost:{_port}{route}";
var uri = new EndpointUri("http", path, $"http:{path}", pars);
return (HttpEndpoint)component.CreateEndpoint(uri);
}
private HttpEndpoint CreateEndpointWithFullPath(string fullPath, Dictionary? parameters = null)
{
var component = new HttpComponent();
var pars = parameters ?? new Dictionary();
var uri = new EndpointUri("http", fullPath, $"http:{fullPath}", pars);
return (HttpEndpoint)component.CreateEndpoint(uri);
}
private static Exchange CreateExchange(object? body = null)
{
var message = new Message(body);
return new Exchange(message);
}
// ── Basic GET ──
[Fact]
public async Task Producer_GET_SendsRequest_ReceivesResponse()
{
var endpoint = CreateEndpointWithPath("/api/test");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
_lastRequestMethod.Should().Be("GET");
_lastRequestPath.Should().Be("/api/test");
exchange.Out.Should().NotBeNull();
exchange.Out!.Headers[HttpHeaders.StatusCode].Should().Be(200);
await producer.Stop();
}
// ── POST with body ──
[Fact]
public async Task Producer_POST_SendsBodyAsString()
{
var endpoint = CreateEndpointWithPath("/api/data", new Dictionary
{
["method"] = "POST"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange("""{"name":"test"}""");
await producer.Process(exchange);
_lastRequestMethod.Should().Be("POST");
_lastRequestBody.Should().Be("""{"name":"test"}""");
_lastRequestContentType.Should().Contain("application/json");
await producer.Stop();
}
[Fact]
public async Task Producer_POST_SendsBodyAsBytes()
{
var endpoint = CreateEndpointWithPath("/api/binary", new Dictionary
{
["method"] = "POST",
["contentType"] = "application/octet-stream"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var bytes = new byte[] { 0x01, 0x02, 0x03, 0xFF };
var exchange = CreateExchange(bytes);
await producer.Process(exchange);
_lastRequestMethod.Should().Be("POST");
await producer.Stop();
}
[Fact]
public async Task Producer_POST_SendsBodyAsStream()
{
var endpoint = CreateEndpointWithPath("/api/stream", new Dictionary
{
["method"] = "POST"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var stream = new MemoryStream(Encoding.UTF8.GetBytes("stream-data"));
var exchange = CreateExchange(stream);
await producer.Process(exchange);
_lastRequestMethod.Should().Be("POST");
_lastRequestBody.Should().Be("stream-data");
await producer.Stop();
}
// ── PUT and DELETE ──
[Fact]
public async Task Producer_PUT_SendsRequest()
{
var endpoint = CreateEndpointWithPath("/api/update", new Dictionary
{
["method"] = "PUT"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange("""{"update":true}""");
await producer.Process(exchange);
_lastRequestMethod.Should().Be("PUT");
_lastRequestBody.Should().Be("""{"update":true}""");
await producer.Stop();
}
[Fact]
public async Task Producer_DELETE_SendsRequest()
{
var endpoint = CreateEndpointWithPath("/api/resource/42", new Dictionary
{
["method"] = "DELETE"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
_lastRequestMethod.Should().Be("DELETE");
_lastRequestPath.Should().Be("/api/resource/42");
await producer.Stop();
}
[Fact]
public async Task Producer_PATCH_SendsRequest()
{
var endpoint = CreateEndpointWithPath("/api/patch", new Dictionary
{
["method"] = "PATCH"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange("""{"field":"value"}""");
await producer.Process(exchange);
_lastRequestMethod.Should().Be("PATCH");
await producer.Stop();
}
[Fact]
public async Task Producer_HEAD_SendsRequest()
{
var endpoint = CreateEndpointWithPath("/api/status", new Dictionary
{
["method"] = "HEAD"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
_lastRequestMethod.Should().Be("HEAD");
await producer.Stop();
}
// ── Method override from exchange header ──
[Fact]
public async Task Producer_MethodOverride_FromHeader()
{
var endpoint = CreateEndpointWithPath("/api/test"); // default GET
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange("""{"data":1}""");
exchange.In.Headers[HttpHeaders.Method] = "POST";
await producer.Process(exchange);
_lastRequestMethod.Should().Be("POST");
await producer.Stop();
}
// ── Query parameters from header ──
[Fact]
public async Task Producer_QueryParameters_FromHeader()
{
var endpoint = CreateEndpointWithPath("/api/search");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
exchange.In.Headers[HttpHeaders.Query] = "q=test&page=1";
await producer.Process(exchange);
_lastRequestPath.Should().Be("/api/search?q=test&page=1");
await producer.Stop();
}
// ── Response handling ──
[Fact]
public async Task Producer_ResponseBody_MappedToOutMessage()
{
_responseBody = """{"result":"success","count":42}""";
_responseContentType = "application/json";
var endpoint = CreateEndpointWithPath("/api/test");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
body.Should().Be("""{"result":"success","count":42}""");
await producer.Stop();
}
[Fact]
public async Task Producer_ResponseHeaders_MappedToOutHeaders()
{
_responseHeaders["X-Custom-Header"] = "test-value";
var endpoint = CreateEndpointWithPath("/api/test");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
exchange.Out!.Headers[HttpHeaders.StatusCode].Should().Be(200);
exchange.Out!.Headers.Should().ContainKey(HttpHeaders.StatusText);
exchange.Out!.Headers.Should().ContainKey("X-Custom-Header");
exchange.Out!.Headers["X-Custom-Header"].Should().Be("test-value");
await producer.Stop();
}
[Fact]
public async Task Producer_SkipResponseHeaders_SkipsHeaders()
{
_responseHeaders["X-Custom-Header"] = "test-value";
var endpoint = CreateEndpointWithPath("/api/test", new Dictionary
{
["skipResponseHeaders"] = "true"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
// StatusCode is always set, but custom headers are not copied
exchange.Out!.Headers[HttpHeaders.StatusCode].Should().Be(200);
exchange.Out!.Headers.Should().NotContainKey("X-Custom-Header");
await producer.Stop();
}
// ── Error handling ──
[Fact]
public async Task Producer_ThrowOnError_True_ThrowsOn4xx()
{
_responseStatusCode = 404;
_responseBody = "Not Found";
var endpoint = CreateEndpointWithPath("/api/missing");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync();
await producer.Stop();
}
[Fact]
public async Task Producer_ThrowOnError_True_ThrowsOn5xx()
{
_responseStatusCode = 500;
_responseBody = "Internal Server Error";
var endpoint = CreateEndpointWithPath("/api/fail");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync();
await producer.Stop();
}
[Fact]
public async Task Producer_ThrowOnError_False_DoesNotThrow()
{
_responseStatusCode = 500;
_responseBody = "Error";
var endpoint = CreateEndpointWithPath("/api/fail", new Dictionary
{
["throwOnError"] = "false"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange); // should not throw
exchange.Out!.Headers[HttpHeaders.StatusCode].Should().Be(500);
await producer.Stop();
}
// ── Authentication ──
[Fact]
public async Task Producer_BasicAuth_SetsAuthorizationHeader()
{
var endpoint = CreateEndpointWithPath("/api/secure", new Dictionary
{
["authScheme"] = "Basic",
["username"] = "admin",
["password"] = "secret"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
_lastRequestHeaders.Should().ContainKey("Authorization");
var authHeader = _lastRequestHeaders["Authorization"];
authHeader.Should().StartWith("Basic ");
var decoded = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader["Basic ".Length..]));
decoded.Should().Be("admin:secret");
await producer.Stop();
}
[Fact]
public async Task Producer_BearerAuth_SetsAuthorizationHeader()
{
var endpoint = CreateEndpointWithPath("/api/secure", new Dictionary
{
["authScheme"] = "Bearer",
["authToken"] = "my-secret-token-123"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
_lastRequestHeaders.Should().ContainKey("Authorization");
_lastRequestHeaders["Authorization"].Should().Be("Bearer my-secret-token-123");
await producer.Stop();
}
// ── Header bridging ──
[Fact]
public async Task Producer_ByDefault_SendsExchangeHeaders()
{
var endpoint = CreateEndpointWithPath("/api/test");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
exchange.In.Headers["X-Request-Id"] = "req-123";
exchange.In.Headers["X-Correlation-Id"] = "corr-456";
await producer.Process(exchange);
_lastRequestHeaders.Should().ContainKey("X-Request-Id");
_lastRequestHeaders["X-Request-Id"].Should().Be("req-123");
_lastRequestHeaders.Should().ContainKey("X-Correlation-Id");
_lastRequestHeaders["X-Correlation-Id"].Should().Be("corr-456");
await producer.Stop();
}
[Fact]
public async Task Producer_SkipRequestHeaders_DoesNotSendExchangeHeaders()
{
var endpoint = CreateEndpointWithPath("/api/test", new Dictionary
{
["skipRequestHeaders"] = "true"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
exchange.In.Headers["X-Request-Id"] = "req-123";
await producer.Process(exchange);
_lastRequestHeaders.Should().NotContainKey("X-Request-Id");
await producer.Stop();
}
// ── ContentType override from exchange header ──
[Fact]
public async Task Producer_ContentType_OverriddenFromExchangeHeader()
{
var endpoint = CreateEndpointWithPath("/api/data", new Dictionary
{
["method"] = "POST"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange("data");
exchange.In.Headers[HttpHeaders.ContentType] = "text/xml";
await producer.Process(exchange);
_lastRequestContentType.Should().Contain("text/xml");
await producer.Stop();
}
// ── Lifecycle ──
[Fact]
public async Task Producer_Process_BeforeStart_Throws()
{
var endpoint = CreateEndpointWithPath("/api/test");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
var exchange = CreateExchange();
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync()
.WithMessage("*not been started*");
}
[Fact]
public async Task Producer_StartStop_Lifecycle()
{
var endpoint = CreateEndpointWithPath("/api/test");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
await producer.Process(CreateExchange()); // should work
await producer.Stop();
}
// ── Timeout ──
[Fact]
public async Task Producer_Timeout_Zero_InfiniteTimeout()
{
var endpoint = CreateEndpointWithPath("/api/test", new Dictionary
{
["timeout"] = "0"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
// Should not throw — infinite timeout
await producer.Process(CreateExchange());
await producer.Stop();
}
// ── Null body for GET ──
[Fact]
public async Task Producer_GET_NullBody_NoRequestBody()
{
var endpoint = CreateEndpointWithPath("/api/test");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange(null);
await producer.Process(exchange);
_lastRequestBody.Should().BeNull();
await producer.Stop();
}
// ── Named Parameters {name} ──
[Fact]
public async Task Producer_NamedParam_ConstantValue_ReplacedInPath()
{
var endpoint = CreateEndpointWithFullPath(
$"/localhost:{_port}/api/users/{{userId}}/orders",
new Dictionary
{
["method"] = "GET",
["param.userId"] = "42"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
_lastRequestPath.Should().Be("/api/users/42/orders");
await producer.Stop();
}
[Fact]
public async Task Producer_NamedParam_ExpressionValue_ResolvedFromHeader()
{
var endpoint = CreateEndpointWithFullPath(
$"/localhost:{_port}/api/users/{{userId}}/profile",
new Dictionary
{
["method"] = "GET",
["param.userId"] = "${header.userId}"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
exchange.In.Headers["userId"] = "99";
await producer.Process(exchange);
_lastRequestPath.Should().Be("/api/users/99/profile");
await producer.Stop();
}
[Fact]
public async Task Producer_NamedParam_MultipleParams_AllReplaced()
{
var endpoint = CreateEndpointWithFullPath(
$"/localhost:{_port}/api/{{version}}/users/{{userId}}",
new Dictionary
{
["method"] = "GET",
["param.version"] = "v2",
["param.userId"] = "${header.uid}"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
exchange.In.Headers["uid"] = "777";
await producer.Process(exchange);
_lastRequestPath.Should().Be("/api/v2/users/777");
await producer.Stop();
}
[Fact]
public async Task Producer_NamedParam_InQueryString_ReplacedInUrl()
{
var endpoint = CreateEndpointWithFullPath(
$"/localhost:{_port}/api/search?q={{query}}&limit={{limit}}",
new Dictionary
{
["method"] = "GET",
["param.query"] = "${header.q}",
["param.limit"] = "10"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
exchange.In.Headers["q"] = "test";
await producer.Process(exchange);
_lastRequestPath.Should().Be("/api/search?q=test&limit=10");
await producer.Stop();
}
// ── StreamResponse ──
[Fact]
public async Task Producer_StreamResponse_BodyIsStream()
{
_responseBody = """{"data":"streamed"}""";
_responseContentType = "application/json";
var endpoint = CreateEndpointWithPath("/api/test", new Dictionary
{
["streamResponse"] = "true"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.Body.Should().BeAssignableTo();
// Read the stream to verify data
var stream = (Stream)exchange.Out!.Body!;
using var reader = new StreamReader(stream, Encoding.UTF8);
var content = await reader.ReadToEndAsync();
content.Should().Be("""{"data":"streamed"}""");
await producer.Stop();
}
[Fact]
public async Task Producer_StreamResponse_False_BodyIsByteArray()
{
_responseBody = "bytes-response";
var endpoint = CreateEndpointWithPath("/api/test");
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
exchange.Out!.Body.Should().BeOfType();
await producer.Stop();
}
[Fact]
public async Task Producer_StreamResponse_HeadersStillMapped()
{
_responseHeaders["X-Custom"] = "val";
var endpoint = CreateEndpointWithPath("/api/test", new Dictionary
{
["streamResponse"] = "true"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
exchange.Out!.Headers[HttpHeaders.StatusCode].Should().Be(200);
exchange.Out!.Headers.Should().ContainKey("X-Custom");
await producer.Stop();
}
[Fact]
public async Task Producer_StreamResponse_BinaryData_Preserved()
{
// Use a test server that returns binary
_responseBody = "binary-test";
_responseContentType = "application/octet-stream";
var endpoint = CreateEndpointWithPath("/api/binary", new Dictionary
{
["streamResponse"] = "true"
});
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
var exchange = CreateExchange();
await producer.Process(exchange);
var stream = (Stream)exchange.Out!.Body!;
using var ms = new MemoryStream();
await stream.CopyToAsync(ms);
var text = Encoding.UTF8.GetString(ms.ToArray());
text.Should().Be("binary-test");
await producer.Stop();
}
// ── The options sweep: preserveHostHeader ─────────────────────────────────────
[Fact]
public async Task Default_ProxiedRequest_CarriesTheTargetHost()
{
// A proxy route (From(http) -> To(http)) copies inbound request headers into the message,
// Host included, and BridgeExchangeHeaders pushed it into the outgoing request - so the
// ORIGINAL host leaked to the target unconditionally while preserveHostHeader (default
// false) was read by nothing. The default contract: the target sees its own host.
var endpoint = CreateEndpointWithPath("/api/proxied");
var producer = (HttpProducer)endpoint.CreateProducer();
await producer.Start();
var msg = new Message("data");
msg.Headers["Host"] = "upstream.example.com";
await producer.Process(new Exchange(msg));
await producer.Stop();
_lastRequestHeaders.Should().ContainKey("Host")
.WhoseValue.Should().Be($"localhost:{_port}",
"by default the outgoing request must carry the TARGET's host, not the original's");
}
[Fact]
public async Task PreserveHostHeader_KeepsTheOriginalHost()
{
var endpoint = CreateEndpointWithPath("/api/proxied", new Dictionary
{
["preserveHostHeader"] = "true",
});
var producer = (HttpProducer)endpoint.CreateProducer();
await producer.Start();
var msg = new Message("data");
msg.Headers["Host"] = "upstream.example.com";
await producer.Process(new Exchange(msg));
await producer.Stop();
_lastRequestHeaders.Should().ContainKey("Host")
.WhoseValue.Should().Be("upstream.example.com",
"reverse proxy case: the target must see the host of the original request");
}
[Fact]
public void ProducerName_MasksUserInfoPassword()
{
// The name is logged as "producer started". A [Sensitive] option name covers a secret that
// travels as a query parameter; a userinfo password lives in the authority, where no
// attribute can reach it, so the name goes through EndpointUri.Sanitize instead.
var component = new HttpComponent();
var uri = EndpointUriParser.Parse("http://user:s3cr3t@api.example.com:8080/orders");
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
var producer = (HttpProducer)endpoint.CreateProducer();
producer.DiagnosticName.Should().NotContain("s3cr3t");
}
[Fact]
public async Task PreserveHostHeader_WorksWithoutHeaderBridging()
{
// The explicit Host set used to live inside the header-bridging block, so
// skipping the request headers silently killed the just-revived option. The two options are
// independent in camel-http and must be independent here.
var endpoint = CreateEndpointWithPath("/api/proxied", new Dictionary
{
["preserveHostHeader"] = "true",
["skipRequestHeaders"] = "true",
});
var producer = (HttpProducer)endpoint.CreateProducer();
await producer.Start();
var msg = new Message("data");
msg.Headers["Host"] = "upstream.example.com";
await producer.Process(new Exchange(msg));
await producer.Stop();
_lastRequestHeaders.Should().ContainKey("Host")
.WhoseValue.Should().Be("upstream.example.com",
"preserveHostHeader does not depend on skipRequestHeaders");
}
[Fact]
public async Task FailedRequest_ErrorLogDoesNotLeakThePassword()
{
// ProducerName goes through Sanitize, but the per-request error log used to print the
// raw resolved URL - userinfo password included - on EVERY failed send.
var capture = new CapturingLoggerProvider();
using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(capture));
await using var context = new RouteContext(loggerFactory: loggerFactory);
var component = new HttpComponent();
context.AddComponent(component);
// A .invalid host fails DNS resolution fast with HttpRequestException - the error-log
// path. (A dead port would time out instead, and a timeout is an OperationCanceledException,
// which that catch deliberately does not log.)
var path = "/user:s3cr3t@host.invalid/orders";
var uri = new EndpointUri("http", path, $"http:{path}", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
var producer = (HttpProducer)endpoint.CreateProducer();
await producer.Start();
Func act = () => producer.Process(CreateExchange("data"));
await act.Should().ThrowAsync();
await producer.Stop();
capture.Entries.Should().Contain(e => e.Level == LogLevel.Error,
"a request failure must be logged");
capture.Entries.Select(e => e.Message).Should()
.NotContain(m => m.Contains("s3cr3t"), "the userinfo password must not leak into the error log");
}
/// Captures every log entry for assertions on emitted messages.
private sealed class CapturingLoggerProvider : ILoggerProvider
{
public System.Collections.Concurrent.ConcurrentBag<(string Category, LogLevel Level, string Message)> Entries { get; } = new();
public ILogger CreateLogger(string categoryName) => new Logger(this, categoryName);
public void Dispose() { }
private sealed class Logger(CapturingLoggerProvider owner, string category) : ILogger
{
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state,
Exception? exception, Func formatter)
=> owner.Entries.Add((category, logLevel, formatter(state, exception)));
}
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpProducerTimeoutTests.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/tests/redb.Route.Tests.Http/HttpProducerTimeoutTests.cs
----
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Processors;
namespace redb.Route.Tests.Http;
///
/// A timeout of the HTTP producer's own — the receiver stayed
/// silent past timeout= — is a connection failure the route can handle, not a cancellation. It used
/// to surface as a bare , which every EIP handler treats as cancellation
/// and passes through, so neither TryCatch/Catch nor OnException could see it and the exchange
/// failed whole. A caller's cancellation must keep passing through untouched.
///
[Collection("HttpServer")]
public class HttpProducerTimeoutTests : IAsyncLifetime
{
private WebApplication? _server;
private int _port;
public async Task InitializeAsync()
{
_port = global::redb.Route.Tests.Shared.TestPorts.Next();
var builder = WebApplication.CreateSlimBuilder();
builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, _port));
builder.Logging.ClearProviders();
_server = builder.Build();
// The receiver is alive but silent: it never answers, so only the client's timeout ends the call.
_server.Map("/slow", async ctx =>
{
try { await Task.Delay(Timeout.Infinite, ctx.RequestAborted); }
catch (OperationCanceledException) { /* the client timed out / was cancelled and left */ }
});
await _server.StartAsync();
}
public async Task DisposeAsync()
{
if (_server is not null)
{
await _server.StopAsync();
await _server.DisposeAsync();
}
}
private HttpEndpoint Endpoint(int timeoutMs, string authority = "")
{
var component = new HttpComponent();
var path = $"/{authority}localhost:{_port}/slow";
var uri = new EndpointUri("http", path, $"http:{path}", new Dictionary
{
["method"] = "POST",
["timeout"] = timeoutMs.ToString(),
});
return (HttpEndpoint)component.CreateEndpoint(uri);
}
private static Exchange CreateExchange(string body) => new(new Message(body));
[Fact]
public async Task ProducerTimeout_IsCaughtByCatchTimeoutException_WithTaskCanceledInner()
{
var endpoint = Endpoint(timeoutMs: 300);
var producer = (HttpProducer)endpoint.CreateProducer();
await producer.Start();
Exception? caught = null;
var tryCatch = new TryCatchProcessor(producer)
.Catch(new DelegateProcessor(ex => caught = ex.Exception));
var exchange = CreateExchange("body");
await tryCatch.Process(exchange);
caught.Should().BeOfType(
"a client timeout reaches Catch instead of passing through as cancellation");
caught!.InnerException.Should().BeOfType(
"the original HttpClient timeout is kept as the cause");
exchange.ExceptionHandled.Should().BeTrue();
await producer.Stop();
}
[Fact]
public async Task ProducerTimeout_IsHandledByOnException()
{
var endpoint = Endpoint(timeoutMs: 300);
var producer = (HttpProducer)endpoint.CreateProducer();
await producer.Start();
var handled = false;
var onException = new OnExceptionProcessor(producer)
.Handle(new DelegateProcessor(_ => handled = true), handled: true);
var exchange = CreateExchange("body");
await onException.Process(exchange);
handled.Should().BeTrue("OnException().Handled(true) sees the producer timeout");
exchange.ExceptionHandled.Should().BeTrue();
await producer.Stop();
}
[Fact]
public async Task CallerCancellation_StaysOperationCanceled_AndBypassesEveryHandler()
{
var endpoint = Endpoint(timeoutMs: 30_000); // a long timeout: the caller cancels first
var producer = (HttpProducer)endpoint.CreateProducer();
await producer.Start();
var handled = false;
var tryCatch = new TryCatchProcessor(producer)
.Catch(new DelegateProcessor(_ => handled = true));
var onException = new OnExceptionProcessor(tryCatch)
.Handle(new DelegateProcessor(_ => handled = true), handled: true);
using var cts = new CancellationTokenSource();
var exchange = CreateExchange("body");
var task = onException.Process(exchange, cts.Token);
cts.CancelAfter(150);
Func act = () => task;
await act.Should().ThrowAsync(
"a caller's cancellation is not a failure the route handles");
handled.Should().BeFalse("neither TryCatch nor OnException may swallow cancellation");
exchange.ExceptionHandled.Should().BeFalse();
await producer.Stop();
}
[Fact]
public async Task ProducerTimeout_MessageCarriesSanitizedUrlOnly()
{
var endpoint = Endpoint(timeoutMs: 300, authority: "user:s3cr3t@");
var producer = (HttpProducer)endpoint.CreateProducer();
await producer.Start();
const string secretBody = "card=4111111111111111";
Exception? caught = null;
var tryCatch = new TryCatchProcessor(producer)
.Catch(new DelegateProcessor(ex => caught = ex.Exception));
await tryCatch.Process(CreateExchange(secretBody));
await producer.Stop();
caught.Should().BeOfType();
caught!.Message.Should().Contain("timed out after 300 ms");
caught.Message.Should().NotContain("s3cr3t", "the userinfo password must be masked (BR-4)");
caught.Message.Should().NotContain(secretBody, "the request body must not reach the error text (BR-4)");
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpReservedHeaderTests.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/tests/redb.Route.Tests.Http/HttpReservedHeaderTests.cs
----
using System.Net;
using System.Net.Http;
using NetHttpMethod = System.Net.Http.HttpMethod;
using System.Net.Sockets;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// A caller must not be able to set the transport's own headers. redbHttp.RemoteAddress is the
/// input to per-IP rate limiting, brute-force lockout and audit records; the consumer takes it from the
/// connection, and the copy of the request headers runs afterwards — so without a guard a header
/// literally named redbHttp.RemoteAddress (a valid HTTP token) would overwrite it and let a caller
/// choose its own throttle bucket.
///
public sealed class HttpReservedHeaderTests : IAsyncLifetime
{
private readonly SharedHttpServerManager _server = new();
private HttpConsumer? _consumer;
private int _port;
public Task InitializeAsync()
{
_port = GetFreePort();
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
if (_consumer is not null) await _consumer.Stop();
await _server.DisposeAsync();
}
[Fact]
public async Task Caller_cannot_override_the_transport_remote_address()
{
IExchange? seen = null;
var component = new HttpComponent { ServerManager = _server };
var parameters = new Dictionary
{
["host"] = "127.0.0.1",
["port"] = _port.ToString(),
};
var uri = new EndpointUri("http", $"/127.0.0.1:{_port}/hook",
$"http:127.0.0.1:{_port}/hook", parameters);
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci => { seen = ci.Arg(); return Task.CompletedTask; });
_consumer = (HttpConsumer)endpoint.CreateConsumer(processor);
await _consumer.Start();
using var client = new HttpClient();
using var request = new HttpRequestMessage(NetHttpMethod.Post, $"http://127.0.0.1:{_port}/hook")
{
Content = new StringContent("payload"),
};
request.Headers.TryAddWithoutValidation("redbHttp.RemoteAddress", "203.0.113.7");
request.Headers.TryAddWithoutValidation("X-Tenant", "acme");
await client.SendAsync(request);
seen.Should().NotBeNull();
seen!.In.GetHeader(HttpHeaders.RemoteAddress).Should().Be("127.0.0.1");
// Ordinary caller headers are untouched — only the transport's own namespace is protected.
seen.In.GetHeader("X-Tenant").Should().Be("acme");
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpResponseHeaderOverrideTests.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/tests/redb.Route.Tests.Http/HttpResponseHeaderOverrideTests.cs
----
using System.Net;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// The consumer does not echo the request's headers back, but a header the route wrote goes out even when the
/// client sent one with the same name. Filtering by name let a client suppress the route's headers: sending
/// Cache-Control in the request removed Cache-Control: no-store from a token response.
///
[Collection("HttpServer")]
public class HttpResponseHeaderOverrideTests : IAsyncLifetime
{
private int _port;
private HttpClient _client = null!;
private RouteContext _ctx = null!;
private SharedHttpServerManager _servers = null!;
public async Task InitializeAsync()
{
_port = global::redb.Route.Tests.Shared.TestPorts.Next();
_client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{_port}") };
_servers = new SharedHttpServerManager();
_ctx = new RouteContext();
_ctx.AddComponent(new HttpComponent { ServerManager = _servers });
var port = _port;
_ctx.AddRoutes(r =>
{
r.From($"http://127.0.0.1:{port}/token?inOut=true")
.Process(e =>
{
e.In.Headers["Cache-Control"] = "no-store";
e.In.Headers["X-Route"] = "route";
})
.SetBody("{\"access_token\":\"t\"}");
r.From($"http://127.0.0.1:{port}/seen?inOut=true")
.Process(e => e.In.Body = string.Join(",", ResponseOnly.Where(e.In.Headers.ContainsKey)));
});
await _ctx.Start();
}
public async Task DisposeAsync()
{
_client.Dispose();
await _ctx.DisposeAsync();
await _servers.DisposeAsync();
}
private static readonly string[] ResponseOnly =
["Set-Cookie", "Location", "WWW-Authenticate", "Proxy-Authenticate", "Authentication-Info", "Retry-After", "Server", "ETag", "Vary"];
[Fact]
public async Task Response_only_headers_in_a_request_never_reach_the_route_nor_the_response()
{
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "/seen");
foreach (var name in ResponseOnly)
request.Headers.TryAddWithoutValidation(name, name == "Set-Cookie" ? "session=attacker" : "x");
var response = await _client.SendAsync(request);
(await response.Content.ReadAsStringAsync()).Should().BeEmpty("a request has no business carrying response fields");
response.Headers.Contains("Set-Cookie").Should().BeFalse();
response.Headers.Location.Should().BeNull();
}
private Task Get(params (string Name, string Value)[] headers) => Send("/token", headers);
private async Task Send(string path, params (string Name, string Value)[] headers)
{
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, path);
foreach (var (name, value) in headers)
request.Headers.TryAddWithoutValidation(name, value);
return await _client.SendAsync(request);
}
[Fact]
public async Task A_header_the_route_wrote_goes_out_although_the_client_sent_its_name()
{
var response = await Get(("Cache-Control", "max-age=3600"), ("X-Route", "client"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Headers.CacheControl!.NoStore.Should().BeTrue("the client must not be able to switch off no-store");
response.Headers.GetValues("X-Route").Should().Equal("route");
}
[Fact]
public async Task A_header_the_route_wrote_with_the_clients_value_still_goes_out()
{
var response = await Get(("Cache-Control", "no-store"));
response.Headers.CacheControl!.NoStore.Should().BeTrue();
}
[Fact]
public async Task A_request_header_the_route_left_alone_is_not_echoed()
{
var response = await Get(("X-Client-Only", "secret-ish"));
response.Headers.Contains("X-Client-Only").Should().BeFalse();
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpRestartTests.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/tests/redb.Route.Tests.Http/HttpRestartTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// An HTTP consumer and producer keep working after Stop() and Start() of the same route context: the stop
/// gives the port back, the start takes it again, and the producer's client of the cached endpoint still sends.
///
[Collection("HttpServer")]
public sealed class HttpRestartTests : IAsyncLifetime
{
private readonly SharedHttpServerManager _servers = new();
private readonly RouteContext _ctx = new();
private readonly HttpClient _client = new();
private readonly int _port = global::redb.Route.Tests.Shared.TestPorts.Next();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
_client.Dispose();
await _ctx.DisposeAsync();
await _servers.DisposeAsync();
}
[Fact]
public async Task Consumer_and_producer_work_after_the_context_is_stopped_and_started_again()
{
var port = _port;
var calls = 0;
_ctx.AddComponent(new HttpComponent { ServerManager = _servers });
_ctx.AddRoutes(r => r.From($"http://127.0.0.1:{port}/ping?inOut=true").Process(e =>
{
Interlocked.Increment(ref calls);
e.In.Body = "pong";
}));
_ctx.AddRoutes(r => r.From("direct://call").To($"http://127.0.0.1:{port}/ping"));
async Task CheckAsync(int round)
{
(await _client.GetStringAsync($"http://127.0.0.1:{port}/ping")).Should().Be("pong",
"the HTTP receiver replies after a restart");
var producer = _ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("x"));
await producer.Process(exchange);
exchange.Exception.Should().BeNull("an HTTP send after a restart arrives");
Volatile.Read(ref calls).Should().Be(round * 2);
}
await _ctx.Start();
await CheckAsync(1);
await _ctx.Stop();
var stopped = () => _client.GetAsync($"http://127.0.0.1:{port}/ping");
await stopped.Should().ThrowAsync("a stopped context releases the port");
await _ctx.Start();
await CheckAsync(2);
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpServerCollection.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/tests/redb.Route.Tests.Http/HttpServerCollection.cs
----
namespace redb.Route.Tests.Http;
[CollectionDefinition("HttpServer")]
public class HttpServerCollection;
Path: redb-route/tests/redb.Route.Tests.Http/HttpSharedHostFromDiTests.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/tests/redb.Route.Tests.Http/HttpSharedHostFromDiTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Processors;
namespace redb.Route.Tests.Http;
///
/// Where an http: consumer looks for the shared Kestrel host: explicitly assigned, then the
/// context's DI container, then the refusal. The middle step is what a module host needs — it adds
/// components by scanning, so ServerManager is never assigned, while the one shared manager
/// sits in DI. Requested by the Tsak agent 2026-09-24, whose module routes failed at start with
/// "SharedHttpServerManager is not configured" although the manager was right there in the container;
/// gRPC and AS2 already resolved in this order.
///
public class HttpSharedHostFromDiTests
{
private static IServiceProvider ProviderWith(SharedHttpServerManager manager)
=> new ServiceCollection().AddSingleton(manager).BuildServiceProvider();
private static IConsumer CreateConsumer(RouteContext context, HttpComponent component)
{
context.AddComponent(component);
var endpoint = context.GetEndpoint("http://localhost:18321/orders");
return endpoint.CreateConsumer(new DelegateProcessor(_ => { }));
}
[Fact]
public void The_manager_in_the_contexts_container_serves_the_consumer()
{
var shared = new SharedHttpServerManager();
using var context = new RouteContext();
context.SetServiceProvider(ProviderWith(shared));
var act = () => CreateConsumer(context, new HttpComponent());
act.Should().NotThrow("the shared host is in the container the context was given");
}
[Fact]
public void An_assigned_manager_wins_over_the_container()
{
var assigned = new SharedHttpServerManager();
using var context = new RouteContext();
context.SetServiceProvider(ProviderWith(new SharedHttpServerManager()));
var component = new HttpComponent { ServerManager = assigned };
var act = () => CreateConsumer(context, component);
act.Should().NotThrow();
component.ServerManager.Should().BeSameAs(assigned);
}
[Fact]
public void A_manager_set_as_a_context_service_serves_the_consumer_too()
{
var shared = new SharedHttpServerManager();
using var context = new RouteContext();
context.AddService(typeof(SharedHttpServerManager), shared);
var act = () => CreateConsumer(context, new HttpComponent());
// Both places a host can leave it are read in one order, the context services first:
// a host without a DI container has AddService and nothing else.
act.Should().NotThrow();
}
[Fact]
public void With_neither_the_refusal_still_names_the_registration_call()
{
using var context = new RouteContext();
var act = () => CreateConsumer(context, new HttpComponent());
// No silent private listener here: an http: consumer binds a port, and which port it binds
// is the host's decision, so the missing host stays a loud failure.
act.Should().Throw().WithMessage("*AddRedbRouteHttp*");
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpStopDrainsInflightTests.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/tests/redb.Route.Tests.Http/HttpStopDrainsInflightTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Processors;
namespace redb.Route.Tests.Http;
///
/// Stopping one route on a shared listener must wait for the requests it is already serving. Until
/// now it only unregistered the route and asked the listener to stop when empty — and when another
/// route still holds the port, the listener stays up, so nobody waits: a deploy that removes one
/// route cuts its in-flight requests mid-pipeline while the port keeps serving. Reported by the AS4
/// agent 2026-09-25; the drain itself is the engine's , already used
/// by every broker consumer and by SignalR and WebSocket.
///
public class HttpStopDrainsInflightTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
[Fact]
public async Task Stop_waits_for_a_request_already_in_the_pipeline_while_the_port_stays_busy()
{
var port = FreePort();
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var finished = false;
await using var context = new RouteContext();
context.AddComponent(new HttpComponent { ServerManager = new SharedHttpServerManager() });
// Two routes on one port: stopping the first leaves the listener up, which is exactly the
// case where nothing used to wait.
var slow = (HttpConsumer)context.GetEndpoint($"http://127.0.0.1:{port}/slow")
.CreateConsumer(new DelegateProcessor(async (e, ct) =>
{
entered.TrySetResult();
await release.Task;
finished = true;
e.In.Body = "done";
}));
var other = context.GetEndpoint($"http://127.0.0.1:{port}/other")
.CreateConsumer(new DelegateProcessor(_ => { }));
await slow.Start();
await other.Start();
using var client = new HttpClient();
var call = client.GetAsync($"http://127.0.0.1:{port}/slow");
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5));
var stop = slow.Stop();
var stoppedEarly = await Task.WhenAny(stop, Task.Delay(500)) == stop;
stoppedEarly.Should().BeFalse("Stop must not return while a request of this route is still running");
release.TrySetResult();
await stop.WaitAsync(TimeSpan.FromSeconds(10));
finished.Should().BeTrue("the request finished before Stop returned");
(await call).StatusCode.Should().Be(HttpStatusCode.OK);
await other.Stop();
}
[Fact]
public async Task Stop_returns_promptly_when_nothing_is_in_flight()
{
var port = FreePort();
await using var context = new RouteContext();
context.AddComponent(new HttpComponent { ServerManager = new SharedHttpServerManager() });
var consumer = context.GetEndpoint($"http://127.0.0.1:{port}/idle")
.CreateConsumer(new DelegateProcessor(_ => { }));
await consumer.Start();
var stop = consumer.Stop();
var completed = await Task.WhenAny(stop, Task.Delay(TimeSpan.FromSeconds(5))) == stop;
completed.Should().BeTrue("an idle route has nothing to wait for");
await stop;
}
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpStreamingTests.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/tests/redb.Route.Tests.Http/HttpStreamingTests.cs
----
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// Wire-level tests for when the route puts an
/// of into
/// ..
///
/// Covers the two encodings the consumer picks based on Content-Type:
///
/// - text/event-stream → SSE framing
/// (data: … per chunk plus a terminal event: done with the
/// JSON trailer of late-bound headers).
/// - anything else → chunked plain text, one flush per
/// yield.
///
/// Also covers the streaming-headers contract
/// (Cache-Control: no-cache, no-transform, X-Accel-Buffering: no)
/// and cancellation propagation when the client closes the response stream
/// mid-flight (server-side enumerator observes ).
///
///
[Collection("HttpServer")]
public class HttpStreamingTests : IAsyncLifetime
{
private SharedHttpServerManager _serverManager = null!;
private HttpClient _client = null!;
private int _port;
private HttpConsumer? _consumer;
public Task InitializeAsync()
{
_port = GetFreePort();
_serverManager = new SharedHttpServerManager();
// PooledConnectionLifetime tiny so a disposed response gives the server
// an immediate Kestrel-side RequestAborted (cancellation test).
_client = new HttpClient(new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromSeconds(1)
});
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
_client.Dispose();
if (_consumer is not null) await _consumer.Stop();
await _serverManager.DisposeAsync();
}
///
/// Builds a consumer wired to the shared server. The processor runs
/// which is expected to populate
/// with a streaming body.
///
private HttpConsumer CreateStreamingConsumer(string path, Func onProcess)
{
var component = new HttpComponent { ServerManager = _serverManager };
var parameters = new Dictionary
{
["host"] = "127.0.0.1",
["port"] = _port.ToString(),
["inOut"] = "true"
};
var uriPath = $"/127.0.0.1:{_port}{path}";
var uri = new EndpointUri("http", uriPath, $"http:{uriPath}", parameters);
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci => onProcess(ci.Arg()));
_consumer = new HttpConsumer(endpoint, processor, endpoint.EndpointOptions, _serverManager);
return _consumer;
}
///
/// Iterator helper. Yields with a small delay
/// between them so the test can verify per-chunk flushing on the wire.
/// When iteration completes (or is cancelled) writes late-bound headers
/// onto so the SSE done trailer can
/// pick them up — matches the contract LlmProducer follows.
///
private static async IAsyncEnumerable ScriptedChunksAsync(
string[] chunks,
IMessage responseMsg,
TaskCompletionSource? observedCancellation = null,
int delayMs = 30,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct = default)
{
try
{
foreach (var c in chunks)
{
await Task.Delay(delayMs, ct).ConfigureAwait(false);
yield return c;
}
// Late-bound summary headers — read by the SSE trailer builder.
responseMsg.Headers["llm.tokens.in"] = 7;
responseMsg.Headers["llm.tokens.out"] = chunks.Length;
responseMsg.Headers["llm.stop_reason"] = "EndTurn";
}
finally
{
if (ct.IsCancellationRequested)
observedCancellation?.TrySetResult();
}
}
[Fact]
public async Task Sse_PerChunkFlush_AndDoneTrailer()
{
var consumer = CreateStreamingConsumer("/sse", ex =>
{
ex.Out = ex.In.Clone();
ex.Out.ContentType = "text/event-stream";
ex.Out.Body = ScriptedChunksAsync(["alpha", "beta", "gamma"], ex.Out);
return Task.CompletedTask;
});
await consumer.Start();
using var resp = await _client.GetAsync(
$"http://127.0.0.1:{_port}/sse",
HttpCompletionOption.ResponseHeadersRead);
resp.StatusCode.Should().Be(HttpStatusCode.OK);
resp.Content.Headers.ContentType!.MediaType.Should().Be("text/event-stream");
// Streaming-headers contract.
resp.Headers.TryGetValues("Cache-Control", out var cc).Should().BeTrue();
string.Join(',', cc!).Should().Contain("no-cache").And.Contain("no-transform");
resp.Headers.TryGetValues("X-Accel-Buffering", out var xab).Should().BeTrue();
string.Join(',', xab!).Should().Be("no");
// Chunked, no Content-Length up front.
resp.Content.Headers.ContentLength.Should().BeNull();
var body = await resp.Content.ReadAsStringAsync();
body.Should().Contain("data: alpha\n");
body.Should().Contain("data: beta\n");
body.Should().Contain("data: gamma\n");
body.Should().Contain("event: done\n");
// Trailer JSON carries late-bound headers.
var trailerIdx = body.IndexOf("event: done", StringComparison.Ordinal);
var trailer = body[trailerIdx..];
trailer.Should().Contain("\"llm.tokens.in\"");
trailer.Should().Contain("\"llm.tokens.out\"");
trailer.Should().Contain("\"llm.stop_reason\"");
// Confirm the JSON payload after 'data: ' on the done event parses.
var dataPrefix = "data: ";
var dataLine = trailer
.Split('\n')
.First(l => l.StartsWith(dataPrefix, StringComparison.Ordinal));
using var json = JsonDocument.Parse(dataLine[dataPrefix.Length..]);
// A count is a JSON number, as the Llm documentation shows it — this used to assert the
// string "3", which pinned the defect rather than the contract.
json.RootElement.GetProperty("llm.tokens.out").GetInt32().Should().Be(3);
json.RootElement.GetProperty("llm.stop_reason").GetString().Should().Be("EndTurn");
}
[Fact]
public async Task ChunkedPlain_NoSseFraming_NoTrailer()
{
var consumer = CreateStreamingConsumer("/chunked", ex =>
{
ex.Out = ex.In.Clone();
ex.Out.ContentType = "text/plain";
ex.Out.Body = ScriptedChunksAsync(["foo-", "bar-", "baz"], ex.Out);
return Task.CompletedTask;
});
await consumer.Start();
using var resp = await _client.GetAsync(
$"http://127.0.0.1:{_port}/chunked",
HttpCompletionOption.ResponseHeadersRead);
resp.StatusCode.Should().Be(HttpStatusCode.OK);
resp.Content.Headers.ContentType!.MediaType.Should().Be("text/plain");
resp.Content.Headers.ContentLength.Should().BeNull(); // chunked
var body = await resp.Content.ReadAsStringAsync();
body.Should().Be("foo-bar-baz"); // pure concatenation
body.Should().NotContain("data: "); // no SSE framing
body.Should().NotContain("event: done");
}
[Fact]
public async Task ChunksArriveProgressively_NotBuffered()
{
// 6 chunks with 80 ms spacing → no way the whole body could be buffered
// and delivered as one read. We assert that the first chunk lands well
// before the last yield happens.
var consumer = CreateStreamingConsumer("/progress", ex =>
{
ex.Out = ex.In.Clone();
ex.Out.ContentType = "text/plain";
ex.Out.Body = ScriptedChunksAsync(
["c0", "c1", "c2", "c3", "c4", "c5"], ex.Out, delayMs: 80);
return Task.CompletedTask;
});
await consumer.Start();
using var resp = await _client.GetAsync(
$"http://127.0.0.1:{_port}/progress",
HttpCompletionOption.ResponseHeadersRead);
var stream = await resp.Content.ReadAsStreamAsync();
var buffer = new byte[256];
var start = DateTime.UtcNow;
var firstReadAt = TimeSpan.Zero;
var total = new StringBuilder();
while (true)
{
var n = await stream.ReadAsync(buffer);
if (n == 0) break;
if (firstReadAt == TimeSpan.Zero) firstReadAt = DateTime.UtcNow - start;
total.Append(Encoding.UTF8.GetString(buffer, 0, n));
}
var totalElapsed = DateTime.UtcNow - start;
total.ToString().Should().Be("c0c1c2c3c4c5");
// The full enumeration takes ~480 ms (6 × 80 ms). The first chunk must
// arrive a healthy margin before the whole thing finishes — proving
// the consumer is not buffering. Allow generous CI slack.
firstReadAt.Should().BeLessThan(totalElapsed - TimeSpan.FromMilliseconds(150),
"first byte should arrive well before the last yield");
}
[Fact]
public async Task ClientCancel_PropagatesToEnumerator()
{
var cancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var consumer = CreateStreamingConsumer("/cancel", ex =>
{
ex.Out = ex.In.Clone();
ex.Out.ContentType = "text/event-stream";
// 100 chunks, 100 ms apart (~10 s of scripted yields). The enumerator must still be
// running when cancellation propagates — with a short script it can simply run to
// completion first, leaving ct uncancelled and the assertion below failing for a
// reason unrelated to cancellation.
ex.Out.Body = ScriptedChunksAsync(
Enumerable.Range(0, 100).Select(i => $"c{i}").ToArray(),
ex.Out,
observedCancellation: cancelled,
delayMs: 100);
return Task.CompletedTask;
});
await consumer.Start();
using var abort = new CancellationTokenSource();
using (var resp = await _client.GetAsync(
$"http://127.0.0.1:{_port}/cancel",
HttpCompletionOption.ResponseHeadersRead,
abort.Token))
{
var stream = await resp.Content.ReadAsStreamAsync();
var buffer = new byte[64];
// Read at least one chunk so the server is actively yielding…
(await stream.ReadAsync(buffer)).Should().BeGreaterThan(0);
// …then bail. Cancelling the token aborts the request on the wire
// and Kestrel raises RequestAborted on the consumer.
abort.Cancel();
}
// Server-side enumerator must observe cancellation. The budget is generous on purpose:
// the happy path completes as soon as the TCS fires (~hundreds of ms), and the long
// ceiling only applies on failure — it stops thread-pool starvation under parallel test
// load (or a busy CI box) from turning a working propagation path into a red test.
var observed = await Task.WhenAny(cancelled.Task, Task.Delay(10_000));
observed.Should().BeSameAs(cancelled.Task,
"server-side enumerator should observe client cancellation");
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpTelemetrySmokeTests.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/tests/redb.Route.Tests.Http/HttpTelemetrySmokeTests.cs
----
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using OpenTelemetry;
using OpenTelemetry.Trace;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Telemetry;
using redb.Route.Tests.Telemetry;
namespace redb.Route.Tests.Http;
///
/// Smoke test: verifies opens a transport span on
/// with the OpenTelemetry semantic
/// HTTP attributes after P1 telemetry instrumentation.
///
public sealed class HttpTelemetrySmokeTests : IAsyncLifetime
{
private WebApplication? _server;
private int _port;
public async Task InitializeAsync()
{
_port = GetFreePort();
var builder = WebApplication.CreateSlimBuilder();
builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, _port));
builder.Logging.ClearProviders();
_server = builder.Build();
_server.Map("/{**catch}", static async ctx =>
{
ctx.Response.StatusCode = 200;
await ctx.Response.WriteAsync("ok");
});
await _server.StartAsync();
}
public async Task DisposeAsync()
{
if (_server is not null)
{
await _server.StopAsync();
await _server.DisposeAsync();
}
}
[Fact]
public async Task HttpProducer_EmitsTransportSpanWithHttpSemantics()
{
// Filtered to this test's own endpoint: the exporter is process state, so a plain
// AddSource(...) collects the spans of every route the other tests are running right now, and
// the Single() below then fails on somebody else's span. The producer span carries
// redb.route.endpoint; this test owns a port nobody else has.
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_port}/");
var component = new HttpComponent();
var path = $"/localhost:{_port}/smoke";
var uri = new EndpointUri("http", path, $"http:{path}", new Dictionary());
var endpoint = (HttpEndpoint)component.CreateEndpoint(uri);
var producer = new HttpProducer(endpoint, endpoint.EndpointOptions);
await producer.Start();
try
{
await producer.Process(new Exchange(new Message(null)));
}
finally
{
await producer.Stop();
}
probe.Activities.Should().NotBeEmpty("HttpProducer.Process must open a transport span");
var activity = probe.Activities.Single();
activity.Source.Name.Should().Be(RouteActivitySource.SourceName);
activity.Kind.Should().Be(ActivityKind.Client);
activity.GetTagItem("http.method").Should().Be("GET");
activity.GetTagItem("redb.route.endpoint").Should().NotBeNull();
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/HttpTracePropagationTests.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/tests/redb.Route.Tests.Http/HttpTracePropagationTests.cs
----
using System.Diagnostics;
using System.Net;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Expressions;
using redb.Route.Http;
using redb.Route.Telemetry;
using redb.Route.Tests.Telemetry;
namespace redb.Route.Tests.Http;
///
/// An HTTP request is inbound traffic like a broker message: the consumer opens a server span with the endpoint on it,
/// continues the caller's trace from traceparent and puts the caller's baggage back; the route's own spans sit
/// under it; a proxying producer sends the context of its own span on, not the caller's header it copied; a failed
/// route marks the server span red; and EnableTelemetry=false opens none of these spans, while the caller's
/// context still reaches the next hop.
///
[Collection("HttpServer")]
public sealed class HttpTracePropagationTests : IAsyncLifetime
{
private int _port;
private int _offPort;
private HttpClient _client = null!;
private RouteContext _ctx = null!;
private RouteContext _offCtx = null!;
private SharedHttpServerManager _servers = null!;
public async Task InitializeAsync()
{
_port = global::redb.Route.Tests.Shared.TestPorts.Next();
_offPort = global::redb.Route.Tests.Shared.TestPorts.Next();
_client = new HttpClient();
_servers = new SharedHttpServerManager();
var port = _port;
_ctx = new RouteContext();
_ctx.AddComponent(new HttpComponent { ServerManager = _servers });
_ctx.AddRoutes(r =>
{
r.From($"http://127.0.0.1:{port}/traced?inOut=true").RouteId($"trace-{port}-traced").SetBody("ok");
r.From($"http://127.0.0.1:{port}/fails?inOut=true").RouteId($"trace-{port}-fails")
.Process(_ => throw new InvalidOperationException("route failed"));
r.From($"http://127.0.0.1:{port}/baggage?inOut=true").RouteId($"trace-{port}-baggage")
.Process(e => e.In.Body = Activity.Current?.GetBaggageItem("tenant") ?? "");
r.From($"http://127.0.0.1:{port}/proxy?inOut=true").RouteId($"trace-{port}-proxy")
.To($"http://127.0.0.1:{port}/echo");
r.From($"http://127.0.0.1:{port}/cancelled?inOut=true").RouteId($"trace-{port}-cancelled")
.Process(_ => throw new TaskCanceledException("a call inside the route timed out"));
r.From($"http://127.0.0.1:{port}/timeout?inOut=true").RouteId($"trace-{port}-timeout")
.To($"http://127.0.0.1:{port}/slow?timeout=200");
r.From($"http://127.0.0.1:{port}/slow?inOut=true").RouteId($"trace-{port}-slow")
.Process(async (_, ct) => await Task.Delay(3000, ct));
r.From($"http://127.0.0.1:{port}/echo?inOut=true").RouteId($"trace-{port}-echo")
.Process(e => e.In.Body = e.In.Headers.TryGetValue("traceparent", out var tp) ? tp?.ToString() : "");
r.From($"http://127.0.0.1:{port}/tagged?inOut=true").RouteId($"trace-{port}-tagged")
.SpanTag("shop.order.id", new HeaderExpression("X-Order"), SpanTarget.Inbound)
.SetBody("ok");
});
// A builder of its own: its OnException applies to its routes only.
_ctx.AddRoutes(r =>
{
r.OnException().Handled(true)
.SpanTag("shop.order.id", new PropertyExpression("orderNo"), SpanTarget.Inbound)
.SetHeader(HttpHeaders.ResponseCode, 500)
.SetBody("failed");
r.From($"http://127.0.0.1:{port}/tagged-failure?inOut=true").RouteId($"trace-{port}-tagged-failure")
.Process(e =>
{
e.Properties["orderNo"] = "A-500";
throw new InvalidOperationException("the order could not be taken");
});
});
await _ctx.Start();
var offPort = _offPort;
_offCtx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false });
_offCtx.AddComponent(new HttpComponent { ServerManager = _servers });
_offCtx.AddRoutes(r =>
{
r.From($"http://127.0.0.1:{offPort}/proxy?inOut=true").To($"http://127.0.0.1:{offPort}/echo");
r.From($"http://127.0.0.1:{offPort}/echo?inOut=true")
.Process(e => e.In.Body = e.In.Headers.TryGetValue("traceparent", out var tp) ? tp?.ToString() : "");
});
await _offCtx.Start();
}
public async Task DisposeAsync()
{
_client.Dispose();
await _ctx.DisposeAsync();
await _offCtx.DisposeAsync();
await _servers.DisposeAsync();
}
private static (ActivityTraceId TraceId, ActivitySpanId SpanId, string Header) Caller()
{
var traceId = ActivityTraceId.CreateRandom();
var spanId = ActivitySpanId.CreateRandom();
return (traceId, spanId, $"00-{traceId}-{spanId}-01");
}
private async Task Get(int port, string path, params (string Name, string Value)[] headers)
{
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{port}{path}");
foreach (var (name, value) in headers)
request.Headers.TryAddWithoutValidation(name, value);
return await _client.SendAsync(request);
}
private static Activity ServerSpan(RouteTelemetryProbe probe, string path)
=> probe.Activities.Single(a => a.Kind == ActivityKind.Server
&& RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)!.Contains(path, StringComparison.Ordinal));
[Fact]
public async Task A_request_opens_a_server_span_that_continues_the_callers_trace()
{
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_port}/traced");
using var routes = RouteTelemetryProbe.ForRouteIdPrefix($"trace-{_port}-traced");
var caller = Caller();
var response = await Get(_port, "/traced", ("traceparent", caller.Header));
response.StatusCode.Should().Be(HttpStatusCode.OK);
var server = ServerSpan(probe, "/traced");
server.TraceId.Should().Be(caller.TraceId);
server.ParentSpanId.Should().Be(caller.SpanId);
server.Source.Name.Should().Be(RouteActivitySource.SourceName);
server.GetTagItem("http.response.status_code").Should().Be(200);
var route = routes.Activities.Should().ContainSingle().Subject;
route.ParentSpanId.Should().Be(server.SpanId, "the route runs inside the request");
}
[Fact]
public async Task SpanTag_Inbound_puts_the_business_key_on_the_server_span_of_the_request()
{
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_port}/tagged");
using var routes = RouteTelemetryProbe.ForRouteIdPrefix($"trace-{_port}-tagged");
var response = await Get(_port, "/tagged", ("X-Order", "A-42"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
ServerSpan(probe, "/tagged").GetTagItem("shop.order.id").Should().Be("A-42");
routes.Activities.Should().ContainSingle()
.Which.GetTagItem("shop.order.id").Should().BeNull("the inbound target is the request's span, not the route's");
}
[Fact]
public async Task SpanTag_Inbound_in_an_OnException_body_tags_the_server_span_of_the_failed_request()
{
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_port}/tagged-failure");
var response = await Get(_port, "/tagged-failure");
response.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
(await response.Content.ReadAsStringAsync()).Should().Be("failed", "the handler answered, not the consumer's default");
ServerSpan(probe, "/tagged-failure").GetTagItem("shop.order.id").Should().Be("A-500",
"a request answered with 500 is found by its business key too");
}
[Fact]
public async Task The_callers_baggage_reaches_the_route()
{
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_port}/baggage");
var headers = new Dictionary();
using (var send = new Activity("caller").Start())
{
send.AddBaggage("tenant", "t1");
RouteTelemetryExtensions.InjectTraceContext(send, headers,
static (h, name, value) => h[name] = value);
}
var response = await Get(_port, "/baggage", headers.Select(h => (h.Key, h.Value)).ToArray());
(await response.Content.ReadAsStringAsync()).Should().Be("t1");
}
[Fact]
public async Task A_failed_route_marks_the_server_span_red()
{
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_port}/fails");
var response = await Get(_port, "/fails");
response.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
var server = ServerSpan(probe, "/fails");
server.Status.Should().Be(ActivityStatusCode.Error);
server.GetTagItem("http.response.status_code").Should().Be(500);
}
[Fact]
public async Task A_call_timed_out_by_HttpClient_marks_the_send_span_red()
{
// HttpClient reports its own timeout as a TaskCanceledException, an OperationCanceledException: only a
// cancellation by the caller's token is a stop rather than a failure.
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_port}/slow");
var response = await Get(_port, "/timeout");
response.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
var send = probe.Activities.Single(a => a.Kind == ActivityKind.Client);
send.Status.Should().Be(ActivityStatusCode.Error);
send.Events.Should().Contain(e => e.Name == "exception");
}
[Fact]
public async Task A_cancellation_the_caller_did_not_ask_for_fails_the_request_and_its_span()
{
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_port}/cancelled");
var response = await Get(_port, "/cancelled");
response.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
ServerSpan(probe, "/cancelled").Status.Should().Be(ActivityStatusCode.Error);
}
[Fact]
public async Task A_proxy_sends_the_context_of_its_own_span_not_the_copied_caller_header()
{
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_port}/echo");
var caller = Caller();
var response = await Get(_port, "/proxy", ("traceparent", caller.Header));
var received = await response.Content.ReadAsStringAsync();
var send = probe.Activities.Single(a => a.Kind == ActivityKind.Client);
received.Should().Be($"00-{caller.TraceId}-{send.SpanId}-{(int)send.ActivityTraceFlags:x2}",
"the next hop is a child of the send, in the caller's trace");
}
[Fact]
public async Task Tracing_off_opens_no_span_and_still_passes_the_callers_context_on()
{
using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_offPort}/");
var caller = Caller();
var response = await Get(_offPort, "/proxy", ("traceparent", caller.Header));
(await response.Content.ReadAsStringAsync()).Should().Contain(caller.TraceId.ToString());
probe.Activities.Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.Http/ListenerFailedStartTests.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/tests/redb.Route.Tests.Http/ListenerFailedStartTests.cs
----
using System.Net;
using System.Net.Sockets;
using Microsoft.AspNetCore.Http;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// A listener that fails to start (its port still taken) leaves nothing behind on the shared host. The HTTP consumer
/// unregisters its route, so a start by hand afterwards registers once and a stop gives the port back; the shared
/// host lets go of the web application that did not start.
///
[Collection("HttpServer")]
public sealed class ListenerFailedStartTests : IAsyncLifetime
{
private readonly SharedHttpServerManager _servers = new();
private readonly HttpClient _client = new() { Timeout = TimeSpan.FromSeconds(10) };
private readonly int _port = global::redb.Route.Tests.Shared.TestPorts.Next();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
_client.Dispose();
await _servers.DisposeAsync();
}
private TcpListener TakePort()
{
var squatter = new TcpListener(IPAddress.Loopback, _port);
squatter.Start();
return squatter;
}
[Fact]
public async Task A_route_started_by_hand_after_a_failed_listener_start_registers_once_and_frees_the_port()
{
var calls = 0;
await using var context = new RouteContext();
context.AddComponent(new HttpComponent { ServerManager = _servers });
context.AddRoutes(r => r.From($"http://127.0.0.1:{_port}/ping?inOut=true").RouteId("taken-port").Process(e =>
{
Interlocked.Increment(ref calls);
e.In.Body = "pong";
}));
var squatter = TakePort();
try
{
await context.Start();
context.GetRoute("taken-port")!.Status.Should().Be(RouteStatus.Errored, "the port is taken");
}
finally
{
squatter.Stop();
}
await context.StartRoute("taken-port");
(await _client.GetStringAsync($"http://127.0.0.1:{_port}/ping")).Should().Be("pong");
Volatile.Read(ref calls).Should().Be(1);
await context.Stop();
var stopped = () => _client.GetAsync($"http://127.0.0.1:{_port}/ping");
await stopped.Should().ThrowAsync(
"no stale registration of the failed start keeps the listener up after the route stopped");
}
[Fact]
public async Task The_shared_host_lets_go_of_a_web_application_that_did_not_start()
{
var registration = _servers.RegisterRoute("127.0.0.1", _port, "/ping", "GET", ctx => ctx.Response.WriteAsync("pong"));
var squatter = TakePort();
try
{
var start = () => _servers.EnsureStarted("127.0.0.1", _port);
await start.Should().ThrowAsync("the port is taken");
ServerEntryApp().Should().BeNull("the web application whose start failed is disposed, not kept");
}
finally
{
squatter.Stop();
}
await _servers.EnsureStarted("127.0.0.1", _port);
(await _client.GetStringAsync($"http://127.0.0.1:{_port}/ping")).Should().Be("pong");
_servers.UnregisterRoute(registration);
await _servers.StopIfEmpty("127.0.0.1", _port);
}
private object? ServerEntryApp()
{
var field = typeof(SharedHttpServerManager).GetField("_servers",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!;
var servers = (System.Collections.IDictionary)field.GetValue(_servers)!;
var entry = servers.Values.Cast().Single();
return entry.App;
}
}
Path: redb-route/tests/redb.Route.Tests.Http/PrincipalHostingTests.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/tests/redb.Route.Tests.Http/PrincipalHostingTests.cs
----
using System.Net;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// The caller's identity through the real shared host:
/// identifies the request and puts the principal on the exchange
/// ().
///
/// Before this nothing could bring an identity to an HTTP route. The consumer ignored who the request
/// came from, and a trusted middleware had no channel either: a redbHttp.* header it added is
/// dropped by the anti-spoofing guard, and any other header cannot be told apart from one the caller
/// sent.
///
///
[Collection("HttpServer")]
public class PrincipalHostingTests : IAsyncLifetime
{
private const string TokenHeader = "X-Test-Token";
private const string Client = "203.0.113.7";
private HttpClient _http = null!;
private int _port;
private SharedHttpServerManager? _serverManager;
private HttpConsumer? _consumer;
private IExchange? _captured;
private int _routeRuns;
private readonly CapturingLogger _logger = new();
public Task InitializeAsync()
{
_port = GetFreePort();
_http = new HttpClient();
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
_http.Dispose();
if (_consumer is not null) await _consumer.Stop();
if (_serverManager is not null) await _serverManager.DisposeAsync();
}
private async Task StartAsync(HttpHostingOptions? options)
{
_serverManager = new SharedHttpServerManager(options, _logger);
var component = new HttpComponent();
var parameters = new Dictionary { ["host"] = "127.0.0.1", ["port"] = _port.ToString() };
var uriPath = $"/127.0.0.1:{_port}/probe";
var endpoint = (HttpEndpoint)component.CreateEndpoint(new EndpointUri("http", uriPath, $"http:{uriPath}", parameters));
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci =>
{
Interlocked.Increment(ref _routeRuns);
_captured = ci.Arg();
return Task.CompletedTask;
});
_consumer = new HttpConsumer(endpoint, processor, endpoint.EndpointOptions, _serverManager);
await _consumer.Start();
}
private async Task SendAsync(Action? configure = null)
{
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, $"http://127.0.0.1:{_port}/probe");
configure?.Invoke(req);
return await _http.SendAsync(req);
}
private static ClaimsPrincipal User(string id) =>
new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, id)], "test"));
/// A resolver that knows one token; anything else is an anonymous caller.
private static Func> TokenResolver => ctx =>
Task.FromResult(ctx.Request.Headers[TokenHeader].ToString() == "good" ? User("user-42") : null);
private static HttpHostingOptions WithResolver(Func> resolve)
{
var o = new HttpHostingOptions { ResolvePrincipal = resolve };
return o;
}
// ── Default host ──
[Fact]
public async Task NoResolver_ExchangeCarriesNoIdentity()
{
await StartAsync(null);
var res = await SendAsync(r => r.Headers.Add(TokenHeader, "good"));
res.StatusCode.Should().Be(HttpStatusCode.OK);
ExchangePrincipal.Get(_captured!).Should().BeNull("nobody asked the host to identify callers");
}
// ── Resolver configured ──
[Fact]
public async Task IdentifiedCaller_PrincipalReachesTheExchange()
{
await StartAsync(WithResolver(TokenResolver));
var res = await SendAsync(r => r.Headers.Add(TokenHeader, "good"));
res.StatusCode.Should().Be(HttpStatusCode.OK);
ExchangePrincipal.Get(_captured!)!.FindFirst(ClaimTypes.NameIdentifier)!.Value.Should().Be("user-42");
}
[Fact]
public async Task AnonymousCaller_IsServed_WithoutIdentity()
{
await StartAsync(WithResolver(TokenResolver));
var res = await SendAsync();
res.StatusCode.Should().Be(HttpStatusCode.OK,
"the host identifies, it does not authorize: whether anonymous is acceptable is the route's call");
_routeRuns.Should().Be(1);
ExchangePrincipal.Get(_captured!).Should().BeNull();
}
[Fact]
public async Task ResolverThatThrows_FailsTheRequest_RouteNeverRuns_ErrorIsLogged()
{
await StartAsync(WithResolver(_ => throw new InvalidOperationException("key endpoint https://idp.internal unreachable")));
var res = await SendAsync(r => r.Headers.Add(TokenHeader, "good"));
res.StatusCode.Should().Be(HttpStatusCode.InternalServerError,
"a resolver that could not decide must not turn the caller into an anonymous one");
_routeRuns.Should().Be(0);
(await res.Content.ReadAsStringAsync()).Should().NotContain("idp.internal", "the resolver's failure text is ours, not the caller's");
_logger.Entries.Should().Contain(e => e.Level == LogLevel.Error && e.Exception is InvalidOperationException);
}
[Fact]
public async Task Resolver_SeesTheClientResolvedByTrustedProxies()
{
IPAddress? seen = null;
var o = WithResolver(ctx =>
{
seen = ctx.Connection.RemoteIpAddress;
return Task.FromResult(null);
});
o.TrustedProxies.Add("127.0.0.1");
await StartAsync(o);
await SendAsync(r => r.Headers.TryAddWithoutValidation(ForwardedHeaderResolver.ForwardedFor, Client));
seen.Should().Be(IPAddress.Parse(Client),
"an address-aware resolver has to see the client, not the proxy in front of it");
}
[Fact]
public async Task Caller_CannotForgeTheIdentity_WithHeadersNamedLikeTheKeys()
{
await StartAsync(WithResolver(TokenResolver));
var res = await SendAsync(r =>
{
r.Headers.TryAddWithoutValidation(ExchangePrincipal.PropertyKey, "admin");
r.Headers.TryAddWithoutValidation(SharedHttpServerManager.PrincipalItem, "admin");
});
res.StatusCode.Should().Be(HttpStatusCode.OK);
ExchangePrincipal.Get(_captured!).Should().BeNull("identity is a property set in-process, never a header from the wire");
}
[Fact]
public async Task CorsPreflight_NeverReachesTheResolver()
{
var calls = 0;
_serverManager = new SharedHttpServerManager(WithResolver(_ =>
{
Interlocked.Increment(ref calls);
return Task.FromResult(null);
}), _logger);
var registration = _serverManager.RegisterRoute("127.0.0.1", _port, "/cors", null,
ctx => { ctx.Response.StatusCode = 200; return Task.CompletedTask; },
corsOptions: new RouteCorsOptions(AllowedOrigins: "https://example.com", AllowedMethods: null, AllowCredentials: false));
try
{
await _serverManager.EnsureStarted("127.0.0.1", _port);
var preflight = new HttpRequestMessage(System.Net.Http.HttpMethod.Options, $"http://127.0.0.1:{_port}/cors");
preflight.Headers.Add("Origin", "https://example.com");
preflight.Headers.Add("Access-Control-Request-Method", "POST");
(await _http.SendAsync(preflight)).StatusCode.Should().Be(HttpStatusCode.NoContent);
calls.Should().Be(0, "a preflight carries no credentials and is answered before identity is resolved");
(await _http.GetAsync($"http://127.0.0.1:{_port}/cors")).StatusCode.Should().Be(HttpStatusCode.OK);
calls.Should().Be(1, "the actual request does reach the resolver");
}
finally
{
_serverManager.UnregisterRoute(registration);
}
}
private sealed class CapturingLogger : ILogger
{
private readonly List<(LogLevel Level, Exception? Exception)> _entries = [];
public IReadOnlyList<(LogLevel Level, Exception? Exception)> Entries
{
get { lock (_entries) return _entries.ToArray(); }
}
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func formatter)
{
lock (_entries) _entries.Add((logLevel, exception));
}
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/RequestPathLogTests.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/tests/redb.Route.Tests.Http/RequestPathLogTests.cs
----
using System.Collections.Concurrent;
using System.Net;
using Microsoft.Extensions.Logging;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///
/// A request path with an encoded line break reaches the route (the path is decoded into a route value), yet the
/// consumer's log line carries the path re-escaped: the logged value is the PathString, whose text form is its
/// escaped URI component, so %0D%0A in the request cannot start a new log line.
///
public class RequestPathLogTests
{
[Fact]
public async Task AnEncodedLineBreakInThePath_IsLoggedEscaped_NotAsALineBreak()
{
var capture = new CapturingProvider();
using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(LogLevel.Debug));
var port = global::redb.Route.Tests.Shared.TestPorts.Next();
string? routeValue = null;
await using var server = new SharedHttpServerManager();
await using var context = new RouteContext(loggerFactory: loggerFactory);
context.AddComponent(new HttpComponent { ServerManager = server });
context.AddRoutes(r => r.From($"http://127.0.0.1:{port}/orders/{{id}}").RouteId("path-log")
.Process((e, _) =>
{
routeValue = e.In.getHeader(HttpHeaders.RouteParamPrefix + "id")?.ToString();
return Task.FromException(new InvalidOperationException("boom"));
}));
await context.Start();
using var client = new HttpClient();
var response = await client.GetAsync($"http://127.0.0.1:{port}/orders/a%0D%0Aforged");
response.StatusCode.Should().Be(HttpStatusCode.InternalServerError, "the request passed Kestrel and reached the route");
routeValue.Should().Be("a\r\nforged", "the route value is decoded, so the line break did reach the server");
var line = capture.Entries.Single(m => m.StartsWith("Route failed for GET", StringComparison.Ordinal));
line.Should().Contain("/orders/a%0D%0Aforged").And.NotContain("\r").And.NotContain("\n");
}
private sealed class CapturingProvider : ILoggerProvider
{
public ConcurrentQueue Entries { get; } = new();
public ILogger CreateLogger(string categoryName) => new Logger(this);
public void Dispose() { }
private sealed class Logger(CapturingProvider owner) : ILogger
{
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func formatter)
=> owner.Entries.Enqueue(formatter(state, exception));
}
}
}
Path: redb-route/tests/redb.Route.Tests.Http/RestDslTests.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/tests/redb.Route.Tests.Http/RestDslTests.cs
----
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Http.Rest;
namespace redb.Route.Tests.Http;
/// REST DSL on top of the HTTP consumer: real Kestrel, real HttpClient.
[Collection("HttpServer")]
public class RestDslTests : IAsyncLifetime
{
public sealed class Order
{
public int Id { get; set; }
public string Customer { get; set; } = "";
}
public static class V1 { public sealed class Order { public int Id { get; set; } } }
public static class V2 { public sealed class Order { public string Sku { get; set; } = ""; } }
private sealed class OrdersApi(int port) : RouteBuilder
{
protected override void Configure()
{
this.Rest("/api/orders", o => { o.Host = "127.0.0.1"; o.Port = port; o.BindingMode = RestBindingMode.Json; })
.Get("/{id}").Produces("application/json").OutType().Description("Get an order").To("direct://get-order")
.Post().Consumes("application/json").Type().Id("createOrder").To("direct://create-order")
.Put("/{id}/status").Produces("text/plain").To("direct://set-status")
.Delete("/{id}").Route().Process(e => e.In.Body = null);
var rest = this.Rest("/api/misc", o => { o.Host = "127.0.0.1"; o.Port = port; });
rest.Get("/boom").Route().ThrowException("boom");
rest.Get("/health").Route().SetBody("ok");
// Code review 2026-09-01: two types with one short name, two inline routes whose ids sanitize
// alike, and a handler that reports whether a client could smuggle a query parameter in.
var v = this.Rest("/api/v", o => { o.Host = "127.0.0.1"; o.Port = port; o.BindingMode = RestBindingMode.Json; });
v.Post("/one").Consumes("application/json").Type().To("direct://v-one");
v.Post("/two").Consumes("application/json").Type().To("direct://v-two");
v.Get("/{id}").Route().SetBody("by-template");
v.Get("/id").Route().SetBody("fixed");
v.Get("/whoami").Route().Process(e => e.In.Body = e.In.Headers.ContainsKey("query.role") ? "spoofed" : "clean");
From("direct://v-one").SetBody("one");
From("direct://v-two").SetBody("two");
From("direct://get-order").Process(e =>
{
e.In.Headers.TryGetValue("query.customer", out var customer);
e.In.Body = new Order { Id = int.Parse((string)e.In.Headers["id"]!), Customer = customer as string ?? "n/a" };
});
From("direct://create-order").Process(e =>
{
var order = (Order)e.In.Body!;
e.In.Headers[HttpHeaders.ResponseCode] = 201;
e.In.Body = new Order { Id = order.Id + 1000, Customer = order.Customer };
});
From("direct://set-status").Process(e => e.In.Body = $"status of {e.In.Headers["id"]}");
}
}
private int _port;
private HttpClient _client = null!;
private RouteContext _ctx = null!;
private SharedHttpServerManager _serverManager = null!;
public async Task InitializeAsync()
{
_port = GetFreePort();
_client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{_port}") };
_serverManager = new SharedHttpServerManager();
_ctx = new RouteContext();
_ctx.AddComponent(new HttpComponent { ServerManager = _serverManager });
_ctx.AddRoutes(new OrdersApi(_port));
await _ctx.Start();
}
public async Task DisposeAsync()
{
_client.Dispose();
await _ctx.DisposeAsync();
await _serverManager.DisposeAsync();
}
///
/// The worker API and the dashboard address a route by one path segment: a generated id with '/' (it used to be
/// "rest:openapi /api/orders", "rest:GET /api/orders/{id}") made the route unmanageable there.
///
[Fact]
public async Task GeneratedRouteIds_HaveNoSlashOrSpace_AreDistinct_AndTheSameInTheNextProcess()
{
var ids = _ctx.Routes.Select(r => r.RouteId).ToList();
ids.Should().OnlyContain(id => !id.Contains('/') && !id.Contains(' '));
ids.Should().OnlyHaveUniqueItems();
ids.Should().Contain("createOrder", "an explicit id stays as written");
ids.Should().ContainSingle(id => id.StartsWith("rest-openapi-api-orders-"));
ids.Should().Contain(id => id.StartsWith("rest-GET-api-orders-id-"));
ids.Should().Contain(id => id.StartsWith("rest-DELETE-api-orders-id-") && id.EndsWith("-handler"));
// "/api/v/{id}" and "/api/v/id" sanitize alike; the fingerprint keeps their routes apart.
ids.Count(id => id.StartsWith("rest-GET-api-v-id-") && !id.EndsWith("-handler")).Should().Be(2);
// Stable across restarts: the same declaration in a fresh context yields the same ids.
await using var again = new RouteContext();
await using var manager = new SharedHttpServerManager();
again.AddComponent(new HttpComponent { ServerManager = manager });
again.AddRoutes(new OrdersApi(GetFreePort()));
await again.Start();
again.Routes.Select(r => r.RouteId).Should().BeEquivalentTo(ids);
}
[Fact]
public async Task Get_PathParameterAndQuery_BecomeHeaders_ResponseIsJson()
{
var response = await _client.GetAsync("/api/orders/7?customer=acme");
response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Content.Headers.ContentType!.MediaType.Should().Be("application/json");
var order = await response.Content.ReadFromJsonAsync();
order!.Id.Should().Be(7);
order.Customer.Should().Be("acme");
}
[Fact]
public async Task Post_JsonBinding_UnmarshalsRequest_MarshalsResponse_StatusFromHeader()
{
var response = await _client.PostAsync("/api/orders",
new StringContent("""{"id":1,"customer":"bob"}""", Encoding.UTF8, "application/json"));
response.StatusCode.Should().Be(HttpStatusCode.Created);
var order = await response.Content.ReadFromJsonAsync();
order!.Id.Should().Be(1001);
order.Customer.Should().Be("bob");
}
[Fact]
public async Task Post_WrongContentType_Is415()
{
var response = await _client.PostAsync("/api/orders", new StringContent("", Encoding.UTF8, "application/xml"));
response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType);
(await response.Content.ReadAsStringAsync()).Should().Contain("application/json");
}
[Fact]
public async Task Put_PlainTextResponse()
{
var response = await _client.PutAsync("/api/orders/7/status", new StringContent("shipped"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
(await response.Content.ReadAsStringAsync()).Should().Be("status of 7");
response.Content.Headers.ContentType!.MediaType.Should().Be("text/plain");
}
[Fact]
public async Task Delete_InlineRoute_NoBody_Is204()
{
var response = await _client.DeleteAsync("/api/orders/7");
response.StatusCode.Should().Be(HttpStatusCode.NoContent);
}
[Fact]
public async Task UndeclaredMethod_Is405_UnknownPath_Is404()
{
(await _client.PostAsync("/api/orders/7/status", new StringContent("x"))).StatusCode.Should().Be(HttpStatusCode.MethodNotAllowed);
(await _client.GetAsync("/api/nothing")).StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public async Task UnhandledException_Is500()
{
(await _client.GetAsync("/api/misc/boom")).StatusCode.Should().Be(HttpStatusCode.InternalServerError);
}
[Fact]
public async Task TwoDeclarations_ShareOnePort()
{
(await _client.GetStringAsync("/api/misc/health")).Should().Be("ok");
(await _client.GetAsync("/api/orders/1")).StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task OpenApi_DescribesTheDeclaredOperations()
{
var response = await _client.GetAsync("/api/orders/openapi.json");
response.StatusCode.Should().Be(HttpStatusCode.OK);
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = doc.RootElement;
root.GetProperty("openapi").GetString().Should().Be("3.0.3");
root.GetProperty("info").GetProperty("title").GetString().Should().Be("redb.Route API");
var paths = root.GetProperty("paths");
var byId = paths.GetProperty("/api/orders/{id}");
byId.GetProperty("get").GetProperty("summary").GetString().Should().Be("Get an order");
byId.GetProperty("get").GetProperty("parameters")[0].GetProperty("name").GetString().Should().Be("id");
byId.GetProperty("get").GetProperty("responses").GetProperty("200").GetProperty("content")
.GetProperty("application/json").GetProperty("schema").GetProperty("$ref").GetString().Should().Be("#/components/schemas/Order");
byId.TryGetProperty("delete", out _).Should().BeTrue();
paths.GetProperty("/api/orders/{id}/status").TryGetProperty("put", out _).Should().BeTrue();
var post = paths.GetProperty("/api/orders").GetProperty("post");
post.GetProperty("operationId").GetString().Should().Be("createOrder");
post.GetProperty("requestBody").GetProperty("content").GetProperty("application/json").GetProperty("schema").GetProperty("$ref").GetString()
.Should().Be("#/components/schemas/Order");
var order = root.GetProperty("components").GetProperty("schemas").GetProperty("Order").GetProperty("properties");
order.GetProperty("id").GetProperty("type").GetString().Should().Be("integer");
order.GetProperty("customer").GetProperty("type").GetString().Should().Be("string");
paths.TryGetProperty("/api/misc/health", out _).Should().BeFalse("the second declaration has its own document");
(await _client.GetAsync("/api/misc/openapi.json")).StatusCode.Should().Be(HttpStatusCode.OK);
}
// Code review 2026-09-01, fourth batch.
[Fact]
public async Task OpenApi_TwoTypesWithOneShortName_GetTwoSchemas()
{
using var doc = JsonDocument.Parse(await _client.GetStringAsync("/api/v/openapi.json"));
var names = doc.RootElement.GetProperty("components").GetProperty("schemas").EnumerateObject().Select(p => p.Name).ToList();
names.Should().Contain("Order");
names.Should().ContainSingle(n => n.Contains("V2") && n.EndsWith("Order"), "V2.Order must not resolve to V1.Order's schema");
}
[Fact]
public async Task InlineRoutes_WhoseIdsSanitizeAlike_KeepTheirOwnHandlers()
{
(await _client.GetStringAsync("/api/v/id")).Should().Be("fixed");
(await _client.GetStringAsync("/api/v/anything")).Should().Be("by-template");
}
[Fact]
public async Task AClientHeaderNamedLikeAQueryParameter_IsNotAQueryParameter()
{
using var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "/api/v/whoami");
request.Headers.Add("query.role", "admin");
var response = await _client.SendAsync(request);
(await response.Content.ReadAsStringAsync()).Should().Be("clean");
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Http/RestValidationTests.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/tests/redb.Route.Tests.Http/RestValidationTests.cs
----
using System.Net;
using System.Text;
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Http.Rest;
namespace redb.Route.Tests.Http;
///
/// Client request validation of the REST DSL, the counterpart of Camel's
/// clientRequestValidation: 406 when Accept excludes what the operation produces,
/// 400 when a declared parameter is missing or does not convert to its declared type. Switched on by
/// an explicit option only; parameters declared just for the OpenAPI document change nothing without
/// it. The error body is written by a registry processor when one is named.
///
[Collection("HttpServer")]
public class RestValidationTests : IAsyncLifetime
{
/// Writes a JSON error body from the properties the REST step leaves on the exchange.
private sealed class JsonErrors : IProcessor
{
public Task Process(IExchange exchange, CancellationToken ct = default)
{
var code = exchange.Properties[RestErrorProperties.Code];
exchange.Properties.TryGetValue(RestErrorProperties.Parameter, out var parameter);
exchange.In.Headers[HttpHeaders.ResponseContentType] = "application/problem+json";
exchange.In.Body = JsonSerializer.Serialize(new
{
status = code,
detail = exchange.Properties[RestErrorProperties.Reason],
parameter,
});
return Task.CompletedTask;
}
}
private sealed class Api(int port) : RouteBuilder
{
protected override void Configure()
{
var strict = this.Rest("/strict", o =>
{
o.Host = "127.0.0.1"; o.Port = port; o.ClientRequestValidation = true;
});
strict.Get("/items/{id}").Produces("application/json")
.Param("id", RestParamType.Path, dataType: RestParamDataType.Integer)
.Param("limit", RestParamType.Query, required: true, dataType: RestParamDataType.Integer, description: "Page size")
.Param("verbose", RestParamType.Query, dataType: RestParamDataType.Boolean)
.Param("X-Tenant", RestParamType.Header, required: true)
.Route().SetBody("{\"ok\":true}");
strict.Get("/any").Route().SetBody("no produces, any Accept");
strict.Post("/orders").Consumes("application/json").Route().SetBody("created");
// The same declarations without the option: described in OpenAPI, never enforced.
var loose = this.Rest("/loose", o => { o.Host = "127.0.0.1"; o.Port = port; });
loose.Get("/items").Produces("application/json")
.Param("limit", RestParamType.Query, required: true, dataType: RestParamDataType.Integer)
.Route().SetBody("{\"ok\":true}");
loose.Get("/checked").Produces("application/json").ClientRequestValidation()
.Route().SetBody("{\"ok\":true}");
var custom = this.Rest("/custom", o =>
{
o.Host = "127.0.0.1"; o.Port = port; o.ClientRequestValidation = true; o.ErrorHandler = "#jsonErrors";
});
custom.Get("/items").Produces("application/json")
.Param("limit", RestParamType.Query, required: true, dataType: RestParamDataType.Integer)
.Route().SetBody("{\"ok\":true}");
custom.Post("/orders").Consumes("application/json").Route().SetBody("created");
}
}
private int _port;
private HttpClient _client = null!;
private RouteContext _ctx = null!;
private SharedHttpServerManager _serverManager = null!;
public async Task InitializeAsync()
{
_port = GetFreePort();
_client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{_port}") };
_serverManager = new SharedHttpServerManager();
_ctx = new RouteContext();
_ctx.AddComponent(new HttpComponent { ServerManager = _serverManager });
_ctx.AddToRegistry("jsonErrors", new JsonErrors());
_ctx.AddRoutes(new Api(_port));
await _ctx.Start();
}
public async Task DisposeAsync()
{
_client.Dispose();
await _ctx.DisposeAsync();
await _serverManager.DisposeAsync();
}
private Task Get(string url, string? accept = null, string? tenant = "acme")
{
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
if (accept is not null) request.Headers.TryAddWithoutValidation("Accept", accept);
if (tenant is not null) request.Headers.Add("X-Tenant", tenant);
return _client.SendAsync(request);
}
// ── 406: Accept against produces ─────────────────────────────────────────
[Theory]
[InlineData(null)]
[InlineData("*/*")]
[InlineData("application/*")]
[InlineData("application/json")]
[InlineData("text/html, application/json;q=0.5")]
[InlineData("application/json;q=0.2, */*;q=0")]
public async Task An_accept_that_admits_the_produced_type_passes(string? accept)
{
var response = await Get("/strict/items/7?limit=10", accept);
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Theory]
[InlineData("application/xml")]
[InlineData("text/*")]
[InlineData("application/json;q=0")]
[InlineData("*/*, application/json;q=0")]
public async Task An_accept_that_excludes_the_produced_type_is_406(string accept)
{
var response = await Get("/strict/items/7?limit=10", accept);
response.StatusCode.Should().Be(HttpStatusCode.NotAcceptable);
(await response.Content.ReadAsStringAsync()).Should().Contain("application/json");
}
[Fact]
public async Task An_operation_without_produces_accepts_any_accept()
{
var response = await Get("/strict/any", "application/xml");
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
// ── 400: declared parameters ─────────────────────────────────────────────
[Fact]
public async Task A_missing_required_query_parameter_is_400_naming_it()
{
var response = await Get("/strict/items/7");
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
(await response.Content.ReadAsStringAsync()).Should().Contain("limit");
}
[Fact]
public async Task A_missing_required_header_is_400_naming_it()
{
var response = await Get("/strict/items/7?limit=10", tenant: null);
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
(await response.Content.ReadAsStringAsync()).Should().Contain("X-Tenant");
}
[Theory]
[InlineData("/strict/items/7?limit=ten", "limit")]
[InlineData("/strict/items/seven?limit=10", "id")]
[InlineData("/strict/items/7?limit=10&verbose=maybe", "verbose")]
public async Task A_value_that_does_not_convert_to_the_declared_type_is_400_naming_it(string url, string parameter)
{
var response = await Get(url);
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
(await response.Content.ReadAsStringAsync()).Should().Contain(parameter);
}
[Fact]
public async Task An_optional_parameter_may_be_absent()
{
var response = await Get("/strict/items/7?limit=10");
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task Consumes_is_still_checked_first_with_415()
{
var response = await _client.PostAsync("/strict/orders", new StringContent("", Encoding.UTF8, "application/xml"));
response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType);
}
// ── The option ───────────────────────────────────────────────────────────
[Fact]
public async Task Without_the_option_declared_parameters_and_accept_are_not_enforced()
{
var response = await Get("/loose/items", "application/xml");
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task A_verb_can_switch_validation_on_by_itself()
{
var response = await Get("/loose/checked", "application/xml");
response.StatusCode.Should().Be(HttpStatusCode.NotAcceptable);
}
// ── Error format ─────────────────────────────────────────────────────────
[Fact]
public async Task A_named_error_handler_writes_the_body_with_code_reason_and_parameter()
{
var response = await Get("/custom/items");
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
body.RootElement.GetProperty("status").GetInt32().Should().Be(400);
body.RootElement.GetProperty("parameter").GetString().Should().Be("limit");
body.RootElement.GetProperty("detail").GetString().Should().Contain("limit");
}
[Fact]
public async Task The_error_handler_also_answers_415()
{
var response = await _client.PostAsync("/custom/orders", new StringContent("", Encoding.UTF8, "application/xml"));
response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType);
response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
}
[Fact]
public async Task Without_an_error_handler_the_body_stays_plain_text()
{
var response = await Get("/strict/items/7");
response.Content.Headers.ContentType!.MediaType.Should().Be("text/plain");
}
[Fact]
public async Task An_unknown_error_handler_fails_the_start_not_the_first_request()
{
await using var ctx = new RouteContext();
await using var servers = new SharedHttpServerManager();
ctx.AddComponent(new HttpComponent { ServerManager = servers });
var port = GetFreePort();
ctx.AddRoutes(b => b.Rest("/x", o => { o.Host = "127.0.0.1"; o.Port = port; o.ErrorHandler = "#nobody"; })
.Get("/y").Route().SetBody("y"));
var act = () => ctx.Start();
(await act.Should().ThrowAsync()).Which.ToString().Should().Contain("nobody");
}
// ── Declaration errors ───────────────────────────────────────────────────
[Fact]
public void A_path_parameter_that_is_not_in_the_template_is_refused()
{
var rest = Declaration("/api");
var act = () => rest.Get("/{id}").Param("code", RestParamType.Path);
act.Should().Throw().WithMessage("*code*");
}
[Fact]
public void A_path_parameter_cannot_be_optional()
{
var rest = Declaration("/api");
var act = () => rest.Get("/{id}").Param("id", RestParamType.Path, required: false);
act.Should().Throw().WithMessage("*required*");
}
[Fact]
public void A_parameter_declared_twice_is_refused()
{
var rest = Declaration("/api");
var act = () => rest.Get("").Param("limit").Param("limit");
act.Should().Throw().WithMessage("*limit*");
}
// ── OpenAPI ──────────────────────────────────────────────────────────────
[Fact]
public async Task OpenApi_lists_the_declared_parameters()
{
using var doc = JsonDocument.Parse(await _client.GetStringAsync("/strict/openapi.json"));
var parameters = doc.RootElement.GetProperty("paths").GetProperty("/strict/items/{id}")
.GetProperty("get").GetProperty("parameters").EnumerateArray()
.ToDictionary(p => p.GetProperty("name").GetString()!);
parameters.Keys.Should().BeEquivalentTo(["id", "limit", "verbose", "X-Tenant"]);
parameters["id"].GetProperty("in").GetString().Should().Be("path");
parameters["id"].GetProperty("schema").GetProperty("type").GetString().Should().Be("integer");
parameters["limit"].GetProperty("in").GetString().Should().Be("query");
parameters["limit"].GetProperty("required").GetBoolean().Should().BeTrue();
parameters["limit"].GetProperty("description").GetString().Should().Be("Page size");
parameters["verbose"].GetProperty("required").GetBoolean().Should().BeFalse();
parameters["verbose"].GetProperty("schema").GetProperty("type").GetString().Should().Be("boolean");
parameters["X-Tenant"].GetProperty("in").GetString().Should().Be("header");
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
/// A REST declaration for tests that only inspect the declaration itself.
private static RestDefinition Declaration(string basePath)
=> new InlineRouteBuilder(_ => { }).Rest(basePath, o => o.OpenApi = false);
}
Path: redb-route/tests/redb.Route.Tests.Http/ServiceCollectionExtensionsTests.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/tests/redb.Route.Tests.Http/ServiceCollectionExtensionsTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Core;
using redb.Route.Extensions;
using redb.Route.Abstractions;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
public class ServiceCollectionExtensionsTests
{
[Fact]
public void AddRedbRouteHttp_RegistersHttpComponent()
{
var services = new ServiceCollection();
services.AddRedbRouteHttp();
var sp = services.BuildServiceProvider();
var component = sp.GetService();
component.Should().NotBeNull();
component!.Scheme.Should().Be("http");
}
[Fact]
public void AddRedbRouteHttp_RegistersHttpsComponent()
{
var services = new ServiceCollection();
services.AddRedbRouteHttp();
var sp = services.BuildServiceProvider();
var component = sp.GetService();
component.Should().NotBeNull();
component!.Scheme.Should().Be("https");
}
[Fact]
public void AddRedbRouteHttp_ComponentsAreSingleton()
{
var services = new ServiceCollection();
services.AddRedbRouteHttp();
var sp = services.BuildServiceProvider();
var first = sp.GetService();
var second = sp.GetService();
first.Should().BeSameAs(second);
var firstHttps = sp.GetService();
var secondHttps = sp.GetService();
firstHttps.Should().BeSameAs(secondHttps);
}
[Fact]
public void AddRedbRouteHttp_WithCorsConfig_AppliedToComponents()
{
var services = new ServiceCollection();
services.AddRedbRouteHttp(cors =>
{
cors.Enabled = true;
cors.Origins = "https://app.example.com";
cors.Credentials = true;
});
var sp = services.BuildServiceProvider();
var http = sp.GetRequiredService();
http.DefaultCors.Enabled.Should().BeTrue();
http.DefaultCors.Origins.Should().Be("https://app.example.com");
http.DefaultCors.Credentials.Should().BeTrue();
var https = sp.GetRequiredService();
https.DefaultCors.Enabled.Should().BeTrue();
https.DefaultCors.Origins.Should().Be("https://app.example.com");
https.DefaultCors.Credentials.Should().BeTrue();
}
[Fact]
public void AddRedbRouteHttp_WithoutCorsConfig_DefaultsApplied()
{
var services = new ServiceCollection();
services.AddRedbRouteHttp();
var sp = services.BuildServiceProvider();
var http = sp.GetRequiredService();
http.DefaultCors.Enabled.Should().BeFalse();
http.DefaultCors.Origins.Should().BeNull();
http.DefaultCors.Credentials.Should().BeFalse();
}
[Fact]
public async Task AddRedbRouteHttp_RegistersComponentsInRouteContext()
{
var services = new ServiceCollection();
services.AddRedbRouteHttp();
await using var sp = services.BuildServiceProvider();
await using var context = new RouteContext();
// The hook RouteHostedService applies at startup
foreach (var configurator in sp.GetServices())
configurator.Configure(context);
context.HasComponent("http").Should().BeTrue();
context.HasComponent("https").Should().BeTrue();
}
}
Path: redb-route/tests/redb.Route.Tests.Http/SharedHttpServerTests.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/tests/redb.Route.Tests.Http/SharedHttpServerTests.cs
----
using System.Net;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Tests.Http;
///