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