Bundle: redb-route / tests/redb.Route.Tests.Soap (tests.redb.Route.Tests.Soap.txt), 23 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.Soap/SoapComponentSharedHostFromDiTests.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.Soap/SoapComponentSharedHostFromDiTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Soap;
namespace redb.Route.Tests.Soap;
///
/// Where the component looks for the shared Kestrel host: explicitly assigned, then the context's DI
/// container, then its own. 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; gRPC and AS2 already resolved in this order.
///
public class SoapComponentSharedHostFromDiTests
{
private static IServiceProvider ProviderWith(SharedHttpServerManager manager)
=> new ServiceCollection().AddSingleton(manager).BuildServiceProvider();
[Fact]
public void The_manager_in_the_contexts_container_is_used_when_none_was_assigned()
{
var shared = new SharedHttpServerManager();
var component = new SoapComponent();
using var context = new RouteContext();
context.SetServiceProvider(ProviderWith(shared));
context.AddComponent(component);
component.Server.Should().BeSameAs(shared);
}
[Fact]
public void An_assigned_manager_wins_over_the_container()
{
var assigned = new SharedHttpServerManager();
var component = new SoapComponent { ServerManager = assigned };
using var context = new RouteContext();
context.SetServiceProvider(ProviderWith(new SharedHttpServerManager()));
context.AddComponent(component);
component.Server.Should().BeSameAs(assigned);
}
[Fact]
public void A_manager_set_as_a_context_service_is_found_too()
{
var shared = new SharedHttpServerManager();
var component = new SoapComponent();
using var context = new RouteContext();
context.AddService(typeof(SharedHttpServerManager), shared);
context.AddComponent(component);
// 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.
component.Server.Should().BeSameAs(shared);
}
[Fact]
public void Without_either_the_component_still_owns_one()
{
var component = new SoapComponent();
using var context = new RouteContext();
context.AddComponent(component);
component.Server.Should().NotBeNull();
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapConcurrencyLimitOptionsTests.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.Soap/SoapConcurrencyLimitOptionsTests.cs
----
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Soap;
using redb.Route.Soap.Fluent;
using Xunit;
namespace redb.Route.Tests.Soap;
///
/// Admission-limit options on the SOAP consumer.
/// The shed mechanics live in the shared host and are e2e-proved there and on the HTTP
/// connector; here the contract is that SOAP carries the same quartet: URI → options → the
/// consumer's RegisterRoute call.
///
public sealed class SoapConcurrencyLimitOptionsTests
{
[Fact]
public void UriAndDsl_CarryTheOptions()
{
var built = Route.Soap.Fluent.Soap.Listen("/svc/orders")
.Port(4090)
.MaxConcurrentRequests(3, queue: 9)
.RejectStatusCode(503)
.RetryAfterSeconds(2)
.Build();
built.Should().Contain("maxConcurrentRequests=3")
.And.Contain("requestQueueLimit=9")
.And.Contain("rejectStatusCode=503")
.And.Contain("retryAfterSeconds=2");
var endpoint = (SoapEndpoint)new SoapComponent().CreateEndpoint(EndpointUriParser.Parse(built));
endpoint.SoapOptions.MaxConcurrentRequests.Should().Be(3);
endpoint.SoapOptions.RequestQueueLimit.Should().Be(9);
endpoint.SoapOptions.RejectStatusCode.Should().Be(503);
endpoint.SoapOptions.RetryAfterSeconds.Should().Be(2);
}
[Fact]
public void QueueWithoutLimit_FailsLoud()
{
var uri = EndpointUriParser.Parse("soap:/svc/x?host=127.0.0.1&port=4091&requestQueueLimit=5");
var act = () => new SoapComponent().CreateEndpoint(uri);
act.Should().Throw().WithMessage("*requestQueueLimit*maxConcurrentRequests*");
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapDataFormatTests.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.Soap/SoapDataFormatTests.cs
----
using System.Net;
using System.Net.Sockets;
using System.Xml.Serialization;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// camel-cxf dataFormat parity: MESSAGE (whole-envelope transparent proxy) and POJO (typed request/response
/// via XmlSerializer). PAYLOAD is covered by the loopback suite.
///
public class SoapDataFormatTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
[Fact]
public async Task MessageDataFormat_PassesWholeEnvelopeBothWays()
{
var port = FreePort();
string? routeSawBody = null;
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddToRegistry("msg", new SoapConnectionFactory
{
EndpointUrl = $"http://127.0.0.1:{port}/svc",
DataFormat = SoapDataFormat.Message,
});
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port).ConnectionFactory("msg"))
.Process(e =>
{
routeSawBody = e.In.Body!.ToString();
// Transparent proxy: the route replies with a whole envelope of its own.
e.In.Body =
"" +
"42";
});
r.From("direct://call").To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").ConnectionFactory("msg"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message(
"" +
""));
await producer.Process(exchange);
// The consumer saw the full inbound envelope, and the producer got the full reply envelope.
routeSawBody.Should().Contain("
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port).ConnectionFactory("server"))
.Process(e =>
{
var req = (GetFareRequest)e.In.Body!;
gotRoute = req.Route;
e.In.Body = new GetFareResponse { Price = 100 };
});
r.From("direct://call").To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").ConnectionFactory("client"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message(new GetFareRequest { Route = "JFK-LHR" }));
await producer.Process(exchange);
// The consumer received a typed request object; the producer got back a typed response object.
gotRoute.Should().Be("JFK-LHR");
exchange.Out!.Body.Should().BeOfType().Which.Price.Should().Be(100);
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapEncryptionInteropTests.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.Soap/SoapEncryptionInteropTests.cs
----
using System.Diagnostics;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Xml;
using AwesomeAssertions;
using redb.Route.Soap;
namespace redb.Route.Tests.Soap;
///
/// XML-Encryption interop: proves the WSS layout we emit (EncryptedKey in the Security header, AES body in
/// EncryptedData, joined by a ReferenceList) is decryptable by an INDEPENDENT crypto stack — Node.js built-in
/// crypto (OpenSSL), with zero shared code and no XML-Encryption library. It RSA-OAEP-unwraps the
/// session key and AES-256-CBC-decrypts the body straight from our envelope. GATED (Category=Interop):
/// no-ops unless the Node container answers on 127.0.0.1:18060. The envelope and key go through the folder
/// SOAP_INTEROP_DIR, which the soap-echo container of redb.Route/docker-compose.tests.yml mounts as /work.
///
[Trait("Category", "Interop")]
public class SoapEncryptionInteropTests
{
private const string Host = "127.0.0.1";
private const int ServerPort = 18060;
private static string StandDir =>
Environment.GetEnvironmentVariable("SOAP_INTEROP_DIR")
?? global::redb.Route.Tests.Shared.TestStand.Generated("soap");
[Fact]
public void RedbWssEncryption_DecryptedBy_IndependentNodeCrypto()
{
if (!IsReachable(Host, ServerPort) || !Directory.Exists(StandDir))
return; // gated: Node container / stand not present
// Encrypt to the cert's public key; keep the matching RSA private key to hand Node for the decrypt.
using var rsa = RSA.Create(2048);
var req = new System.Security.Cryptography.X509Certificates.CertificateRequest(
"CN=soap-enc", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
using var cert = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1));
var envelope = SoapEnvelope.Build("4242", SoapVersion.Soap11);
var doc = new XmlDocument { PreserveWhitespace = true };
doc.Load(new MemoryStream(envelope));
SoapEncryption.EncryptBody(doc, cert, SoapVersion.Soap11);
// Per-runtime file names so the parallel hosts of each target framework don't race on the same files.
var tag = Environment.Version.Major;
File.WriteAllText(Path.Combine(StandDir, $"enc-envelope-{tag}.xml"), doc.OuterXml);
File.WriteAllText(Path.Combine(StandDir, $"enc-key-{tag}.pem"), rsa.ExportPkcs8PrivateKeyPem());
var (stdout, stderr, exit) = RunNode(
$"ENC_XML=/work/enc-envelope-{tag}.xml ENC_PEM=/work/enc-key-{tag}.pem node /app/xmlenc-verify.js");
exit.Should().Be(0, $"independent Node crypto should decrypt our WSS envelope; stderr='{stderr}'");
stdout.Should().Contain("PLAIN:").And.Contain("Secret").And.Contain("4242");
}
private static (string stdout, string stderr, int exit) RunNode(string command)
{
var psi = new ProcessStartInfo("docker")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("exec");
psi.ArgumentList.Add("soap-echo");
psi.ArgumentList.Add("sh");
psi.ArgumentList.Add("-c");
psi.ArgumentList.Add(command);
using var p = Process.Start(psi)!;
var stdout = p.StandardOutput.ReadToEnd();
var stderr = p.StandardError.ReadToEnd();
p.WaitForExit(15000);
return (stdout, stderr, p.HasExited ? p.ExitCode : -1);
}
private static bool IsReachable(string host, int port)
{
try
{
using var client = new TcpClient();
var connect = client.ConnectAsync(host, port);
return connect.Wait(TimeSpan.FromMilliseconds(500)) && client.Connected;
}
catch
{
return false;
}
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapEnvelopeTests.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.Soap/SoapEnvelopeTests.cs
----
using System.Text;
using AwesomeAssertions;
using redb.Route.Soap;
namespace redb.Route.Tests.Soap;
/// Unit tests for SOAP envelope build/parse (1.1 & 1.2), fault detection, and Content-Type.
public class SoapEnvelopeTests
{
private const string Payload = "SVO";
[Theory]
[InlineData(SoapVersion.Soap11)]
[InlineData(SoapVersion.Soap12)]
public void Build_Then_Parse_RoundTripsBody(SoapVersion version)
{
var envelope = SoapEnvelope.Build(Payload, version);
var parsed = SoapEnvelope.Parse(envelope, version);
parsed.IsFault.Should().BeFalse();
parsed.BodyXml.Should().Contain("GetFares").And.Contain("SVO");
}
[Fact]
public void Build_Soap11_UsesTextXml()
{
SoapEnvelope.ContentType(SoapVersion.Soap11, "GetFares").Should().StartWith("text/xml");
}
[Fact]
public void Build_Soap12_UsesSoapXml_WithActionParam()
{
var ct = SoapEnvelope.ContentType(SoapVersion.Soap12, "GetFares");
ct.Should().StartWith("application/soap+xml").And.Contain("action=\"GetFares\"");
}
[Fact]
public void Parse_Soap11_Fault_IsDetected()
{
var fault = SoapEnvelope.BuildFault("boom", SoapVersion.Soap11, "soap:Client");
var parsed = SoapEnvelope.Parse(fault, SoapVersion.Soap11);
parsed.IsFault.Should().BeTrue();
parsed.FaultCode.Should().Be("soap:Client");
parsed.FaultString.Should().Be("boom");
}
[Fact]
public void Parse_Soap12_Fault_IsDetected()
{
var fault = SoapEnvelope.BuildFault("kaboom", SoapVersion.Soap12, "soap:Sender");
var parsed = SoapEnvelope.Parse(fault, SoapVersion.Soap12);
parsed.IsFault.Should().BeTrue();
parsed.FaultCode.Should().Be("soap:Sender");
parsed.FaultString.Should().Be("kaboom");
}
[Fact]
public void Build_WithHeader_PutsHeaderInEnvelopeHeaderPlane()
{
var envelope = SoapEnvelope.Build(Payload, SoapVersion.Soap11, "svc");
var headers = SoapEnvelope.ReadHeaders(envelope, SoapVersion.Soap11).ToList();
headers.Should().ContainSingle();
headers[0].Value.Should().Be("svc");
}
///
/// A fault code is a QName in both SOAP versions, so a prefixed code means nothing unless the prefix
/// is bound on the envelope. It was written unbound, which reads fine to the eye and does not resolve
/// in a client that treats it as the QName the specification says it is — and the clients that branch
/// on fault codes are exactly those.
///
[Theory]
[InlineData(SoapVersion.Soap11)]
[InlineData(SoapVersion.Soap12)]
public void A_prefixed_fault_code_resolves_as_a_qname(SoapVersion version)
{
var xml = System.Text.Encoding.UTF8.GetString(
SoapEnvelope.BuildFault("no", version, "wst:FailedAuthentication"));
var envelope = System.Xml.Linq.XElement.Parse(xml);
var code = envelope.Descendants()
.First(e => e.Name.LocalName is "faultcode" or "Value").Value;
code.Should().Be("wst:FailedAuthentication");
// The point of the test: resolving the prefix has to give the WS-Trust namespace, not nothing.
var prefix = code.Split(':')[0];
envelope.GetNamespaceOfPrefix(prefix).Should().NotBeNull();
envelope.GetNamespaceOfPrefix(prefix)!.NamespaceName
.Should().Be("http://docs.oasis-open.org/ws-sx/ws-trust/200512");
}
///
/// A code in a namespace of the caller's own is bound from what they gave, because the connector has
/// no way to guess it and guessing wrong would be worse than leaving it unresolved.
///
[Fact]
public void A_caller_supplied_namespace_binds_its_own_prefix()
{
var xml = System.Text.Encoding.UTF8.GetString(
SoapEnvelope.BuildFault("no", SoapVersion.Soap11, "acme:QuotaExceeded", "urn:acme:faults"));
System.Xml.Linq.XElement.Parse(xml).GetNamespaceOfPrefix("acme")!.NamespaceName
.Should().Be("urn:acme:faults");
}
///
/// The default code keeps the envelope exactly as it was: `soap` is already bound, and nothing else
/// is added for it.
///
[Fact]
public void The_default_fault_code_adds_no_declaration()
{
var xml = System.Text.Encoding.UTF8.GetString(
SoapEnvelope.BuildFault("no", SoapVersion.Soap11));
xml.Should().Contain("soap:Server");
System.Text.RegularExpressions.Regex.Matches(xml, "xmlns:").Should().HaveCount(1);
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapFaultAsReplyTests.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.Soap/SoapFaultAsReplyTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// A fault the route means to send is a reply, not a failure. Until now the only way to answer
/// with soap:Fault was to throw, which left the exchange failed: the route's metrics counted an
/// error, a dead-letter channel took a copy, and a supervising host saw a broken route — for a "no such
/// order" the service is designed to return. Reported by the Tsak agent 2026-09-25, whose DLQ filled
/// with business faults.
///
/// The answer is the one the HTTP consumer already uses for a status code: the route puts it in the
/// reply's headers and returns normally. Throwing still works and still means a failure — an exception
/// the route did not intend is exactly that.
///
///
public class SoapFaultAsReplyTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
private sealed class OutcomeListener : IRouteLifecycleListener
{
public int Failed;
public int Completed;
public Task OnExchangeCompleted(string routeId, IExchange exchange, CancellationToken ct)
{
Interlocked.Increment(ref Completed);
return Task.CompletedTask;
}
public Task OnExchangeFailed(string routeId, IExchange exchange, Exception exception, CancellationToken ct)
{
Interlocked.Increment(ref Failed);
return Task.CompletedTask;
}
}
private static async Task<(HttpStatusCode Status, string? Code, string? Reason)> Post(
int port, SoapVersion version, string bodyXml = "")
{
using var http = new HttpClient();
var content = new ByteArrayContent(SoapEnvelope.Build(bodyXml, version));
content.Headers.ContentType = MediaTypeHeaderValue.Parse(SoapEnvelope.ContentType(version, "urn:t/GetOrder"));
using var resp = await http.PostAsync($"http://127.0.0.1:{port}/svc", content);
var parsed = SoapEnvelope.Parse(await resp.Content.ReadAsByteArrayAsync(), version);
return (resp.StatusCode, parsed.IsFault ? parsed.FaultCode : null, parsed.IsFault ? parsed.FaultString : null);
}
[Theory]
[InlineData(SoapVersion.Soap11, "soap:Client")]
[InlineData(SoapVersion.Soap12, "soap:Sender")]
public async Task Fault_headers_on_the_reply_send_a_fault_and_the_exchange_succeeds(SoapVersion version, string expectedCode)
{
var port = FreePort();
var outcome = new OutcomeListener();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddLifecycleListener(outcome);
ctx.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e => e.In.Headers[SoapHeaders.FaultString] = "No order with that number"));
await ctx.Start();
var (status, code, reason) = await Post(port, version);
reason.Should().Be("No order with that number");
code.Should().Be(expectedCode, "a refusal about the CONTENT of the request is the sender's, not a retry hint");
status.Should().Be(version == SoapVersion.Soap12 ? HttpStatusCode.OK : HttpStatusCode.InternalServerError);
outcome.Failed.Should().Be(0, "the route answered as designed");
outcome.Completed.Should().Be(1);
}
[Fact]
public async Task The_route_picks_the_fault_code_when_it_wants_another_one()
{
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e =>
{
e.In.Headers[SoapHeaders.FaultCode] = "wst:FailedAuthentication";
e.In.Headers[SoapHeaders.FaultString] = "Token rejected";
}));
await ctx.Start();
var (_, code, reason) = await Post(port, SoapVersion.Soap12);
// WS-Trust clients branch on the code, so a route that names one must have it sent verbatim.
code.Should().Be("wst:FailedAuthentication");
reason.Should().Be("Token rejected");
}
[Fact]
public async Task A_thrown_fault_is_still_a_failed_exchange()
{
var port = FreePort();
var outcome = new OutcomeListener();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddLifecycleListener(outcome);
ctx.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(_ => throw new SoapFaultException("soap:Receiver", "Downstream is down")));
await ctx.Start();
var (_, code, reason) = await Post(port, SoapVersion.Soap12);
reason.Should().Be("Downstream is down");
code.Should().Be("soap:Receiver");
outcome.Failed.Should().Be(1, "an exception the route did not intend stays a failure");
}
[Fact]
public async Task A_reply_without_fault_headers_is_an_ordinary_reply()
{
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e => e.In.Body = "ok"));
await ctx.Start();
var (status, code, _) = await Post(port, SoapVersion.Soap12);
code.Should().BeNull();
status.Should().Be(HttpStatusCode.OK);
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapFaultAttributionTests.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.Soap/SoapFaultAttributionTests.cs
----
using System.Net.Http.Headers;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using redb.Route.Core;
using redb.Route.Abstractions;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// Two questions a fault has to answer, and the consumer used to get both wrong for a request it could
/// not read: whose fault is it and how much do we say about why.
///
/// Whose: every rejection below used to come back as soap:Receiver / soap:Server, which
/// SOAP 1.2 defines as a failure "attributable to the processing of the message rather than to the
/// contents of the message itself". That is a retry hint, and it is false here: the same bytes will fail
/// again, so a retry handler is told to loop on a request that can never succeed. A request we cannot
/// parse is Sender / Client.
///
///
/// How much: for the two parse failures, all of it. Their text describes the caller's own bytes, so
/// withholding it buys no secrecy and costs the integrator the clue. For a decryption failure, nothing:
/// the exception describes our key and our configuration, and text that varies with the cause is a
/// decryption oracle. WS-Security is explicit that a fault here "could be used as part of a denial of
/// service or cryptographic attack", and gives one code for every cause: wsse:FailedCheck.
///
///
public class SoapFaultAttributionTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
private static X509Certificate2 SelfSigned(string cn)
{
using var rsa = RSA.Create(2048);
var req = new CertificateRequest($"CN={cn}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1));
}
private static async Task<(string? Code, string? Reason)> PostAndReadFault(
int port, byte[] body, string contentType, SoapVersion version)
{
using var http = new HttpClient();
var content = new ByteArrayContent(body);
content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
using var resp = await http.PostAsync($"http://127.0.0.1:{port}/svc", content);
var bytes = await resp.Content.ReadAsByteArrayAsync();
var parsed = SoapEnvelope.Parse(bytes, version);
parsed.IsFault.Should().BeTrue("a request the consumer refuses must come back as a SOAP fault");
return (parsed.FaultCode, parsed.FaultString);
}
///
/// Stands up a listening SOAP route. The route body never runs in these tests: every request here is
/// rejected before an exchange exists.
///
private static RouteContext Listening(int port, string? factoryName = null,
SoapConnectionFactory? factory = null, ILoggerFactory? loggerFactory = null)
{
var ctx = new RouteContext(loggerFactory: loggerFactory);
ctx.AddComponent(new SoapComponent());
if (factoryName is not null && factory is not null) ctx.AddToRegistry(factoryName, factory);
ctx.AddRoutes(r =>
{
var listen = SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port);
if (factoryName is not null) listen = listen.ConnectionFactory(factoryName);
r.From(listen).Process(e => e.In.Body = "ok");
});
return ctx;
}
[Theory]
[InlineData(SoapVersion.Soap11, "soap:Client")]
[InlineData(SoapVersion.Soap12, "soap:Sender")]
public async Task A_request_the_route_could_not_bind_is_the_senders_fault(SoapVersion version, string expected)
{
// MalformedRequestException is the transport-neutral "your request is wrong" signal (the
// controller dispatcher throws it when the action's parameters do not bind). The consumer
// must map it to a Sender fault CARRYING the message — the text describes the caller's own
// bytes (BR-4 allows exactly that class out) — instead of a Receiver fault with the generic
// reference text, which is a retry hint for bytes that will fail identically forever.
var port = FreePort();
var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(_ => throw new MalformedRequestException("Malformed request for operation 'Register': boom")));
await using var _ = ctx;
await ctx.Start();
var envelope = SoapEnvelope.Build("", version);
var (code, reason) = await PostAndReadFault(port, envelope, SoapEnvelope.ContentType(version, "urn:t/Register"), version);
code.Should().Be(expected, "unbindable bytes are the sender's fault, resending them cannot help");
reason.Should().Contain("Malformed request for operation 'Register'",
"the caller is told what is wrong with THEIR request, not handed a reference id");
}
[Theory]
[InlineData(SoapVersion.Soap11, "soap:Client")]
[InlineData(SoapVersion.Soap12, "soap:Sender")]
public async Task An_envelope_carrying_a_dtd_is_refused_before_its_entities_expand(SoapVersion version, string expected)
{
// SOAP forbids a document type declaration in an envelope, and for good reason: nested internal
// entities expand in memory long before anything validates the message. 452 bytes become 300 000
// characters at these settings, and the real attack does not stop at five levels. Reported while
// preparing the AS4 connector, 2026-09-25.
var port = FreePort();
await using var ctx = Listening(port);
await ctx.Start();
var sb = new System.Text.StringBuilder("");
for (var i = 1; i <= 5; i++)
{
sb.Append($"");
}
var ns = version == SoapVersion.Soap12 ? "http://www.w3.org/2003/05/soap-envelope" : "http://schemas.xmlsoap.org/soap/envelope/";
sb.Append($"]>&lol5;");
var (code, _) = await PostAndReadFault(
port, System.Text.Encoding.UTF8.GetBytes(sb.ToString()), SoapEnvelope.ContentType(version, "urn:t/Op"), version);
code.Should().Be(expected, "an envelope that SOAP does not allow is the sender's fault");
}
[Theory]
[InlineData(SoapVersion.Soap11, "soap:Client")]
[InlineData(SoapVersion.Soap12, "soap:Sender")]
public async Task An_unparseable_envelope_is_the_callers_fault_not_ours(SoapVersion version, string expected)
{
var port = FreePort();
await using var ctx = Listening(port);
await ctx.Start();
var (code, reason) = await PostAndReadFault(
port, "this is not an envelope"u8.ToArray(), SoapEnvelope.ContentType(version, null), version);
code.Should().Be(expected, "the same bytes will fail again, so telling the caller to retry is a lie");
reason.Should().Contain("Malformed SOAP request",
"the parser is describing the caller's own bytes, which is the one clue that finds a BOM " +
"or a truncated stream, and discloses nothing about this process");
}
[Fact]
public async Task A_malformed_MTOM_request_is_the_callers_fault_not_ours()
{
var port = FreePort();
await using var ctx = Listening(port);
await ctx.Start();
// A boundary is declared and no part carries it: SoapMultipart rejects it before the envelope exists.
var (code, reason) = await PostAndReadFault(
port, "nothing here matches the boundary"u8.ToArray(),
"multipart/related; boundary=\"mtom-x\"; type=\"application/xop+xml\"; start-info=\"text/xml\"",
SoapVersion.Soap11);
code.Should().Be("soap:Client");
reason.Should().Contain("Malformed MTOM request");
}
///
/// The one place where the message is withheld, and the code says so: wsse:FailedCheck is what
/// WS-Security defines for "the signature or decryption was invalid".
///
[Fact]
public async Task A_decryption_failure_names_no_reason_and_leaks_no_exception_text()
{
var port = FreePort();
var logs = new CapturingLogs();
using var loggerFactory = LoggerFactory.Create(b => { b.SetMinimumLevel(LogLevel.Trace); b.AddProvider(logs); });
using var theirs = SelfSigned("client");
using var ours = SelfSigned("server");
await using var ctx = Listening(port, "server", new SoapConnectionFactory { SigningCert = ours }, loggerFactory);
await ctx.Start();
// Encrypted to a certificate whose private key this server does not hold.
var (code, reason) = await PostAndReadFault(
port, EncryptedTo(theirs), SoapEnvelope.ContentType(SoapVersion.Soap11, null), SoapVersion.Soap11);
code.Should().Be("wsse:FailedCheck",
"WS-Security gives exactly one code for every way a decryption can fail");
reason.Should().Contain("ref: ", "the caller still needs something to quote when it asks us why");
// The real exception must have reached the log, and none of its words the caller.
var logged = logs.Exceptions.Should().ContainSingle(
"the operator is the one who gets to know why decryption failed").Subject;
reason.Should().NotContain(logged.Message, "that text describes our key, not the caller's bytes");
reason.Should().NotContain(logged.GetType().Name);
}
///
/// The anti-oracle assertion, and the reason the message is withheld rather than merely trimmed: an
/// attacker who can vary the ciphertext must not be able to tell one failure from another. Two
/// genuinely different causes, a key we do not hold and ciphertext that has been tampered with, have
/// to come back identical once the per-request reference is masked.
///
[Fact]
public async Task A_decryption_failure_reads_the_same_whatever_actually_broke()
{
var port = FreePort();
using var theirs = SelfSigned("client");
using var ours = SelfSigned("server");
await using var ctx = Listening(port, "server", new SoapConnectionFactory { SigningCert = ours });
await ctx.Start();
var ct = SoapEnvelope.ContentType(SoapVersion.Soap11, null);
var wrongKey = await PostAndReadFault(port, EncryptedTo(theirs), ct, SoapVersion.Soap11);
var tampered = await PostAndReadFault(port, EncryptedTo(ours, corrupt: true), ct, SoapVersion.Soap11);
// Both really did fail for different reasons, otherwise this test compares one cause with itself.
DecryptFailureCause(ours, corrupt: false).Should().NotBe(DecryptFailureCause(ours, corrupt: true),
"the two inputs must break the decryptor in different ways for the comparison below to mean anything");
tampered.Code.Should().Be(wrongKey.Code);
Mask(tampered.Reason).Should().Be(Mask(wrongKey.Reason),
"differing text per cause is exactly what a padding oracle reads");
static string? Mask(string? reason) => reason is null ? null : Regex.Replace(reason, "ref: [^)]*", "ref: X");
}
///
/// An envelope whose Body is encrypted to , optionally with the ciphertext
/// tampered with after the fact.
///
private static byte[] EncryptedTo(X509Certificate2 cert, bool corrupt = false)
{
var doc = Encrypted(cert, corrupt);
using var ms = new MemoryStream();
doc.Save(ms);
return ms.ToArray();
}
private static System.Xml.XmlDocument Encrypted(X509Certificate2 cert, bool corrupt)
{
var envelope = SoapEnvelope.Build("1", SoapVersion.Soap11);
var doc = new System.Xml.XmlDocument { PreserveWhitespace = true };
doc.Load(new MemoryStream(envelope));
SoapEncryption.EncryptBody(doc, cert, SoapVersion.Soap11);
if (corrupt)
{
var ns = new System.Xml.XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
ns.AddNamespace("xenc", SoapEncryption.XmlEncNs);
var cipher = doc.SelectSingleNode("//soap:Body/xenc:EncryptedData//xenc:CipherValue", ns)!;
var raw = Convert.FromBase64String(cipher.InnerText);
raw[^1] ^= 0xFF; // still valid base64, no longer valid ciphertext
cipher.InnerText = Convert.ToBase64String(raw);
}
return doc;
}
///
/// What the decryptor actually raises for this input, used only to prove the two inputs of the oracle
/// test break it in different ways.
///
private static string DecryptFailureCause(X509Certificate2 ours, bool corrupt)
{
using var other = SelfSigned("nobody");
var doc = Encrypted(corrupt ? ours : other, corrupt);
try
{
SoapEncryption.DecryptBody(doc, ours);
return "";
}
catch (Exception ex) { return ex.GetType().Name + ": " + ex.Message; }
}
private sealed class CapturingLogs : ILoggerProvider
{
private readonly List _exceptions = [];
public IReadOnlyList Exceptions { get { lock (_exceptions) return [.. _exceptions]; } }
public ILogger CreateLogger(string categoryName) => new Sink(this);
public void Dispose() { }
private sealed class Sink(CapturingLogs owner) : ILogger
{
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel level, EventId id, TState state, Exception? ex,
Func formatter)
{
if (ex is not null) lock (owner._exceptions) owner._exceptions.Add(ex);
}
}
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapHeaderPlaneTests.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.Soap/SoapHeaderPlaneTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
/// The two header planes — envelope <soap:Header> vs transport — round-trip.
public class SoapHeaderPlaneTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
[Fact]
public async Task EnvelopeHeader_And_Operation_ReachTheRoute()
{
var port = FreePort();
string? gotHeaderTo = null;
string? gotOperation = null;
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e =>
{
gotHeaderTo = e.In.GetHeader(SoapHeaders.HeaderPrefix + "To");
gotOperation = e.In.GetHeader(SoapHeaders.Operation);
e.In.Body = "ok";
});
r.From("direct://call")
.SetHeader(SoapHeaders.HeaderPrefix + "To", "svc")
.To(SoapDsl.Call($"http://127.0.0.1:{port}/svc"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("1")));
gotHeaderTo.Should().NotBeNull().And.Contain("svc"); // envelope header plane crossed the wire
gotOperation.Should().Be("Ping"); // operation = body root element
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapInteropTests.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.Soap/SoapInteropTests.cs
----
using System.Diagnostics;
using System.Net.Sockets;
using System.Xml.Linq;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// Live interop against an independent SOAP stack — the Node.js soap library, a mature
/// implementation with no shared code with this connector (profile soap of docker-compose.tests.yml). This proves what
/// loopback e2e cannot: that a foreign SOAP implementation accepts our on-the-wire envelope, and that we
/// accept its. CoreWCF was rejected as the reference stack because every version carries an unpatched
/// crypto CVE; a JVM/CXF image is heavier but equivalent — Node was chosen only because its base image was
/// already cached. GATED: each test no-ops unless the container answers on 127.0.0.1:18060, so the normal
/// suite stays green without it. Run with --filter Category=Interop after
/// docker compose -f redb.Route/docker-compose.tests.yml --profile soap up -d --wait.
///
[Trait("Category", "Interop")]
public class SoapInteropTests
{
private const string Host = "127.0.0.1";
private const int ServerPort = 18060; // Node SOAP echo server (compose port mapping)
// Our consumer; the container reaches it via host-gateway. Offset by runtime major so the parallel
// multi-TFM test hosts never contend for the same port.
// 18160+: clear of the gRPC interop ports (18100 and 18110-18159).
private static readonly int ConsumerPort = 18160 + Environment.Version.Major;
private static string ServerUrl => $"http://{Host}:{ServerPort}/echo";
/// Direction A: our producer → the independent Node SOAP server. Proves a foreign stack accepts our wire.
[Fact]
public async Task Redb_Producer_To_NodeSoapServer_Echoes()
{
if (!IsReachable(Host, ServerPort))
return; // gated: Node SOAP server not running — profile soap of docker-compose.tests.yml
await using var ctx = new RouteContext();
ctx.AddComponent(new redb.Route.Soap.SoapComponent());
ctx.AddRoutes(r => r.From("direct://call")
.To(SoapDsl.Call(ServerUrl).Action("urn:soaptest/Echo")));
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message(
"hello-redb"));
await producer.Process(exchange);
// The Node service parsed our envelope, ran Echo, and returned a response our parser read back.
exchange.HasOut.Should().BeTrue();
var result = XElement.Parse(exchange.Out!.Body!.ToString()!)
.Descendants().First(x => x.Name.LocalName == "result").Value;
result.Should().Be("echo:hello-redb");
}
/// Direction B: the independent Node SOAP client → our consumer. Proves a foreign client accepts our responses.
[Fact]
public async Task NodeSoapClient_To_RedbConsumer_Echoes()
{
if (!IsReachable(Host, ServerPort))
return; // gated: Node SOAP container not running
await using var ctx = new RouteContext();
ctx.AddComponent(new redb.Route.Soap.SoapComponent());
// Bind on all interfaces so the container's host-gateway can reach us.
ctx.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("0.0.0.0").Port(ConsumerPort))
.Process(e =>
{
var msg = XElement.Parse(e.In.Body!.ToString()!)
.Descendants().First(x => x.Name.LocalName == "msg").Value;
// Match the WSDL response shape (EchoResponse qualified, result unqualified) so the Node client parses it.
e.In.Body = $"redb:{msg}";
}));
await ctx.Start();
var (stdout, stderr, exit) = RunNodeClient("hi-from-node");
exit.Should().Be(0, $"node client should succeed; stderr='{stderr}'");
stdout.Should().Contain("RESULT:redb:hi-from-node");
}
private static (string stdout, string stderr, int exit) RunNodeClient(string msg)
{
var psi = new ProcessStartInfo("docker")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("exec");
psi.ArgumentList.Add("soap-echo");
psi.ArgumentList.Add("sh");
psi.ArgumentList.Add("-c");
psi.ArgumentList.Add($"TARGET=http://host.docker.internal:{ConsumerPort}/svc node /app/client.js {msg}");
using var p = Process.Start(psi)!;
var stdout = p.StandardOutput.ReadToEnd();
var stderr = p.StandardError.ReadToEnd();
p.WaitForExit(15000);
return (stdout, stderr, p.HasExited ? p.ExitCode : -1);
}
private static bool IsReachable(string host, int port)
{
try
{
using var client = new TcpClient();
var connect = client.ConnectAsync(host, port);
return connect.Wait(TimeSpan.FromMilliseconds(500)) && client.Connected;
}
catch
{
return false;
}
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapLoopbackTests.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.Soap/SoapLoopbackTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// End-to-end loopback: the SOAP producer POSTs a real envelope over a live Kestrel to the SOAP consumer,
/// which delivers the body to a route and returns a response envelope the producer parses. Proves both sides.
///
public class SoapLoopbackTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
[Fact]
public async Task Producer_To_Consumer_RoundTrips()
{
var port = FreePort();
var received = new List();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e =>
{
received.Add(e.In.Body!.ToString()!);
e.In.Body = "ok";
});
r.From("direct://call")
.To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").Operation("Ping"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("1"));
await producer.Process(exchange);
received.Should().ContainSingle().Which.Should().Contain("Ping").And.Contain("1");
exchange.Out.Should().NotBeNull();
exchange.Out!.Body!.ToString().Should().Contain("Reply").And.Contain("ok");
}
[Fact]
public async Task Soap12_RoundTrips_EndToEnd()
{
var port = FreePort();
string? received = null;
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddToRegistry("v12", new SoapConnectionFactory
{
EndpointUrl = $"http://127.0.0.1:{port}/svc12",
SoapVersion = SoapVersion.Soap12,
});
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc12").Host("127.0.0.1").Port(port))
.Process(e => { received = e.In.Body!.ToString(); e.In.Body = "ok"; });
r.From("direct://call12")
.To(SoapDsl.Call($"http://127.0.0.1:{port}/svc12").ConnectionFactory("v12").Operation("Ping"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call12").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("2"));
await producer.Process(exchange);
received.Should().Contain("Ping").And.Contain("2");
exchange.Out!.Body!.ToString().Should().Contain("Reply").And.Contain("ok");
}
[Fact]
public async Task Consumer_Honours_The_Fault_Code_A_Route_Chose()
{
// SoapFaultException carries a FaultCode and SoapEnvelope.BuildFault accepts one, but the consumer
// used to drop it and answer soap:Server for everything. A route could describe what went wrong and
// not what kind of wrong it was.
//
// That matters wherever a client branches on the code rather than on prose: WS-Trust clients treat
// wst:FailedAuthentication and wst:InvalidRequest as different outcomes, and prose is not a contract.
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc-code").Host("127.0.0.1").Port(port))
.Process(_ => throw new SoapFaultException("wst:FailedAuthentication", "bad credentials"));
r.From("direct://call-code")
.To(SoapDsl.Call($"http://127.0.0.1:{port}/svc-code"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call-code").CreateProducer();
await producer.Start();
var act = async () => await producer.Process(new Exchange(new Message("")));
var ex = await act.Should().ThrowAsync();
ex.Which.FaultCode.Should().Contain("FailedAuthentication",
"the code the route chose has to survive to the caller, not be flattened to soap:Server");
ex.Which.FaultString.Should().Be("bad credentials");
}
[Fact]
public async Task Consumer_RouteException_Returns_SoapFault()
{
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc-err").Host("127.0.0.1").Port(port))
.Process(_ => throw new InvalidOperationException("route blew up"));
r.From("direct://call-err")
.To(SoapDsl.Call($"http://127.0.0.1:{port}/svc-err"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call-err").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message(""));
var act = async () => await producer.Process(exchange);
// A route exception on the server side comes back as a SOAP fault the producer surfaces — but
// BR-4: the exception's own text is not what travels. An unhandled failure yields a generic
// faultstring with a reference; a route that wants to say more raises SoapFaultException, whose
// FaultString is deliberate and is still sent verbatim (covered by the fault-code tests).
await act.Should().ThrowAsync()
.Where(e => !e.FaultString!.Contains("route blew up") && e.FaultString!.Contains("ref: "));
}
[Fact]
public async Task StringUri_Forms_Drive_The_Call_EndToEnd()
{
var port = FreePort();
string? received = null;
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
// Both endpoints written as plain string URIs (the forms documented in README.md), no fluent builder.
// A MULTI-segment path guards against first-segment truncation (the URI-authority parsing bug the
// single-slash `soap:/path` form fixes, mirroring the AS2/Http listeners).
r.From($"soap:/api/orders?host=127.0.0.1&port={port}")
.Process(e => { received = e.In.Body!.ToString(); e.In.Body = "ok"; });
r.From("direct://call")
.To($"soap://127.0.0.1:{port}/api/orders?operation=Ping");
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("9"));
await producer.Process(exchange);
received.Should().Contain("Ping").And.Contain("9");
exchange.Out!.Body!.ToString().Should().Contain("Reply").And.Contain("ok");
}
[Fact]
public async Task Consumer_ByteArray_Reply_Is_Sent_As_Xml_Not_Stringified()
{
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
// A route that produces already-serialized XML bytes (Payload mode).
.Process(e => e.In.Body = System.Text.Encoding.UTF8.GetBytes("ok"));
r.From("direct://call").To(SoapDsl.Call($"http://127.0.0.1:{port}/svc"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message(""));
await producer.Process(exchange);
var body = exchange.Out!.Body!.ToString()!;
body.Should().Contain("Reply").And.Contain("ok");
body.Should().NotContain("System.Byte");
}
[Fact]
public void Fluent_Builders_Emit_The_Documented_String_Uris()
{
// Locks the README string examples to the actual DSL output — a guard against fluent↔URI drift.
((string)SoapDsl.Call("https://gds/air.svc").ConnectionFactory("amadeus").Operation("GetFares"))
.Should().Be("soaps://gds/air.svc?connectionFactory=amadeus&operation=GetFares");
((string)SoapDsl.Listen("/svc/orders").Host("0.0.0.0").Port(4090).ConnectionFactory("orders"))
.Should().Be("soap:/svc/orders?host=0.0.0.0&port=4090&connectionFactory=orders");
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapMtomInteropTests.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.Soap/SoapMtomInteropTests.cs
----
using System.Diagnostics;
using System.Net.Sockets;
using System.Text;
using System.Xml.Linq;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// Live MTOM interop: an independent MTOM producer (Node.js soap, forceMTOM) ↔ our consumer.
/// Node's soap implements MTOM on the client but not the server, so this is the meaningful direction.
/// Both halves are proven: our multipart/related parser lifts the foreign stack's inbound XOP
/// attachment, and the foreign client parses the MTOM attachment our consumer returns. GATED
/// (Category=Interop): no-ops unless the Node container answers on 127.0.0.1:18060. See
/// profile soap of docker-compose.tests.yml.
///
[Trait("Category", "Interop")]
public class SoapMtomInteropTests
{
private const string Host = "127.0.0.1";
private const int ServerPort = 18060;
// Distinct from SoapInteropTests' consumer port; offset by runtime major against parallel-TFM contention.
// 18180+: clear of the gRPC interop ports (18100 and 18110-18159) and of SoapInteropTests (18160+).
private static readonly int ConsumerPort = 18180 + Environment.Version.Major;
[Fact]
public async Task NodeMtomClient_To_RedbConsumer_CarriesAttachment()
{
if (!IsReachable(Host, ServerPort))
return; // gated: Node SOAP container not running
byte[]? consumerGot = null;
var uploaded = Encoding.UTF8.GetBytes("node-upload-bytes");
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddToRegistry("mtom", new SoapConnectionFactory { Mtom = true });
ctx.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("0.0.0.0").Port(ConsumerPort).ConnectionFactory("mtom"))
.Process(e =>
{
consumerGot = e.In.Attachments.FirstOrDefault()?.Content.ReadAllBytes();
var msg = XElement.Parse(e.In.Body!.ToString()!).Descendants().First(x => x.Name.LocalName == "msg").Value;
e.In.Body = $"mtom:{msg}";
e.In.Attachments.Clear();
e.In.Attachments.Add(new Attachment
{
Name = "resp-1",
ContentId = "resp-1",
Content = AttachmentContent.FromBytes(Encoding.UTF8.GetBytes("redb-mtom-reply")),
});
}));
await ctx.Start();
var (stdout, stderr, exit) = RunNodeMtomClient("hi-mtom", "node-upload-bytes");
exit.Should().Be(0, $"node mtom client should succeed; stderr='{stderr}'");
stdout.Should().Contain("RESULT:mtom:hi-mtom");
// Inbound proof: our multipart/related parser lifted the foreign client's XOP attachment intact.
consumerGot.Should().Equal(uploaded);
// Outbound proof: the foreign client parsed the MTOM attachment our consumer returned.
stdout.Should().Contain("RESPATT:redb-mtom-reply");
}
private static (string stdout, string stderr, int exit) RunNodeMtomClient(string msg, string attBody)
{
var psi = new ProcessStartInfo("docker")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("exec");
psi.ArgumentList.Add("soap-echo");
psi.ArgumentList.Add("sh");
psi.ArgumentList.Add("-c");
psi.ArgumentList.Add($"TARGET=http://host.docker.internal:{ConsumerPort}/svc node /app/mtom-client.js {msg} {attBody}");
using var p = Process.Start(psi)!;
var stdout = p.StandardOutput.ReadToEnd();
var stderr = p.StandardError.ReadToEnd();
p.WaitForExit(15000);
return (stdout, stderr, p.HasExited ? p.ExitCode : -1);
}
private static bool IsReachable(string host, int port)
{
try
{
using var client = new TcpClient();
var connect = client.ConnectAsync(host, port);
return connect.Wait(TimeSpan.FromMilliseconds(500)) && client.Connected;
}
catch
{
return false;
}
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapMtomTests.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.Soap/SoapMtomTests.cs
----
using System.Net;
using System.Net.Sockets;
using System.Text;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// MTOM/XOP (camel-cxf mtom-enabled parity): binary attachments as multipart/related, exposed as
/// the message attachments. Unit round-trip of the packer plus a full producer→consumer loopback carrying
/// attachments in both directions.
///
public class SoapMtomTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
private static Attachment Part(string contentId, string contentType, byte[] content) => new()
{
Name = contentId,
ContentId = contentId,
ContentType = contentType,
Content = AttachmentContent.FromBytes(content),
};
[Fact]
public void Multipart_Write_Then_Parse_RoundTrips()
{
var payload = new byte[] { 1, 2, 3, 4, 5, 250, 251, 252 };
var atts = new List { Part("blob-1", "application/octet-stream", payload) };
var root = Encoding.UTF8.GetBytes("");
var (body, contentType) = SoapMultipart.Write(root, "text/xml; charset=utf-8", atts);
contentType.Should().Contain("multipart/related").And.Contain("application/xop+xml").And.Contain("start-info=\"text/xml\"");
var (parsedRoot, parsedAtts) = SoapMultipart.Parse(body, contentType);
Encoding.UTF8.GetString(parsedRoot).Should().Contain("Envelope");
parsedAtts.Should().ContainSingle();
parsedAtts[0].ContentId.Should().Be("blob-1");
parsedAtts[0].Name.Should().Be("blob-1");
parsedAtts[0].ContentType.Should().Be("application/octet-stream");
parsedAtts[0].Content.ReadAllBytes().Should().Equal(payload);
}
[Fact]
public void Multipart_Write_AddressesAnAttachmentWithoutContentId_ByItsName()
{
var atts = new List
{
new() { Name = "report.pdf", ContentType = "application/pdf", Content = AttachmentContent.FromBytes([7, 8]) },
};
var root = Encoding.UTF8.GetBytes("");
var (body, contentType) = SoapMultipart.Write(root, "text/xml", atts);
var (_, parsedAtts) = SoapMultipart.Parse(body, contentType);
parsedAtts.Should().ContainSingle().Which.ContentId.Should().Be("report.pdf");
}
// Builds a raw multipart/related body with a chosen (short) boundary, so we can exercise the parser's
// robustness against foreign wire shapes the GUID-boundary writer never produces.
private static byte[] Raw(string s) => Encoding.ASCII.GetBytes(s.Replace("\n", "\r\n"));
[Fact]
public void Parse_DoesNotSplit_OnBoundaryBytesInsideAttachmentContent()
{
// The attachment body literally contains "--BND", but NOT at a line start — it must survive intact.
const string ct = "multipart/related; boundary=BND; type=\"application/xop+xml\"; start=\"\"";
var body = Raw(
"--BND\n" +
"Content-Type: application/xop+xml; type=\"text/xml\"\n" +
"Content-ID: \n" +
"\n" +
"\n" +
"--BND\n" +
"Content-Type: application/octet-stream\n" +
"Content-ID: \n" +
"\n" +
"XX--BNDYY\n" + // boundary bytes mid-content, not line-anchored
"--BND--\n");
var (root, atts) = SoapMultipart.Parse(body, ct);
Encoding.ASCII.GetString(root).Should().Contain("Envelope");
atts.Should().ContainSingle();
Encoding.ASCII.GetString(atts[0].Content.ReadAllBytes()).Should().Be("XX--BNDYY");
}
[Fact]
public void Parse_KeepsAllAttachments_WhenRootPartHasNoContentId()
{
// Root part is plain text/xml with no Content-ID and no `start` param → fallback picks the first part,
// and BOTH attachments must survive (regression: the old fallback dropped the first attachment).
const string ct = "multipart/related; boundary=BND";
var body = Raw(
"--BND\n" +
"Content-Type: text/xml\n" +
"\n" +
"\n" +
"--BND\n" +
"Content-Type: application/octet-stream\n" +
"Content-ID: \n" +
"\n" +
"AAA\n" +
"--BND\n" +
"Content-Type: application/octet-stream\n" +
"Content-ID: \n" +
"\n" +
"BBB\n" +
"--BND--\n");
var (root, atts) = SoapMultipart.Parse(body, ct);
Encoding.ASCII.GetString(root).Should().Contain("Envelope");
atts.Select(a => a.ContentId).Should().BeEquivalentTo(new[] { "a1", "b1" });
atts.Select(a => Encoding.ASCII.GetString(a.Content.ReadAllBytes())).Should().BeEquivalentTo(new[] { "AAA", "BBB" });
}
[Fact]
public void Parse_Throws_OnMultipartContentTypeButNoDelimiter()
{
const string ct = "multipart/related; boundary=BND";
var body = Encoding.ASCII.GetBytes(" plain, no boundary here");
var act = () => SoapMultipart.Parse(body, ct);
act.Should().Throw();
}
[Fact]
public async Task Mtom_Loopback_CarriesAttachmentsBothWays()
{
var port = FreePort();
byte[]? consumerGot = null;
var uploaded = Encoding.UTF8.GetBytes("the-uploaded-bytes");
var replied = Encoding.UTF8.GetBytes("the-reply-bytes");
const string xop = "http://www.w3.org/2004/08/xop/include";
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddToRegistry("mtom", new SoapConnectionFactory
{
EndpointUrl = $"http://127.0.0.1:{port}/svc",
Mtom = true,
});
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port).ConnectionFactory("mtom"))
.Process(e =>
{
consumerGot = e.In.Attachments.Find("up-1")?.Content.ReadAllBytes();
e.In.Body = $"";
e.In.Attachments.Clear();
e.In.Attachments.Add(Part("resp-1", "text/plain", replied));
});
r.From("direct://call").To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").ConnectionFactory("mtom"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var msg = new Message($"");
msg.Attachments.Add(Part("up-1", "application/octet-stream", uploaded));
var exchange = new Exchange(msg);
await producer.Process(exchange);
// The consumer received our uploaded attachment, and its reply attachment came back to the producer.
consumerGot.Should().Equal(uploaded);
var back = exchange.Out!.Attachments;
back.Should().ContainSingle();
back[0].ContentId.Should().Be("resp-1");
back[0].Content.ReadAllBytes().Should().Equal(replied);
}
[Fact]
public async Task Mtom_Consumer_DoesNotEcho_InboundAttachments_WhenRouteSetsNoReplyList()
{
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddToRegistry("mtom", new SoapConnectionFactory
{
EndpointUrl = $"http://127.0.0.1:{port}/svc",
Mtom = true,
});
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port).ConnectionFactory("mtom"))
.Process(e =>
{
// Read the inbound attachment but do NOT change the attachments of the reply.
_ = e.In.Attachments.Find("up-1")?.Content.ReadAllBytes();
e.In.Body = "ok";
});
r.From("direct://call").To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").ConnectionFactory("mtom"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var msg = new Message("");
msg.Attachments.Add(Part("up-1", "application/octet-stream", Encoding.UTF8.GetBytes("caller-secret")));
var exchange = new Exchange(msg);
await producer.Process(exchange);
// The caller's own inbound attachment must NOT come back on the response.
exchange.Out!.Attachments.Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapPrincipalTests.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.Soap/SoapPrincipalTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Security.Claims;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// The caller's identity on SOAP exchanges: the shared host's resolver identifies the HTTP request that
/// carries the envelope, and the consumer puts the principal on the exchange ().
///
public sealed class SoapPrincipalTests
{
[Theory]
[InlineData("good", "soap-user")]
[InlineData(null, "anonymous")]
public async Task The_resolved_caller_reaches_the_route(string? token, string expected)
{
var port = FreePort();
await using var manager = new SharedHttpServerManager(new HttpHostingOptions
{
ResolvePrincipal = http => Task.FromResult(http.Request.Headers["X-Test-Token"].ToString() == "good"
? new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "soap-user")], "test"))
: null),
});
await using var context = new RouteContext();
context.AddComponent(new SoapComponent { ServerManager = manager });
context.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e => e.In.Body =
$"{ExchangePrincipal.Get(e)?.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous"}"));
await context.Start();
using var client = new HttpClient();
var content = new ByteArrayContent(SoapEnvelope.Build("", SoapVersion.Soap11));
content.Headers.ContentType = MediaTypeHeaderValue.Parse(SoapEnvelope.ContentType(SoapVersion.Soap11, "urn:t/Ask"));
using var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"http://127.0.0.1:{port}/svc") { Content = content };
if (token is not null) request.Headers.Add("X-Test-Token", token);
using var response = await client.SendAsync(request);
var parsed = SoapEnvelope.Parse(await response.Content.ReadAsByteArrayAsync(), SoapVersion.Soap11);
parsed.IsFault.Should().BeFalse();
parsed.BodyXml.Should().Contain($">{expected}<");
}
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapProducerTests.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.Soap/SoapProducerTests.cs
----
using System.Net;
using System.Net.Sockets;
using System.Text;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
/// Producer tests against a loopback HTTP server that speaks SOAP by hand (in-box, no WCF).
public class SoapProducerTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
private sealed class SoapStub : IDisposable
{
private readonly HttpListener _listener = new();
public byte[]? LastRequest { get; private set; }
public string Url { get; }
public SoapStub(Func respond)
{
var port = FreePort();
Url = $"http://localhost:{port}/svc";
_listener.Prefixes.Add($"http://localhost:{port}/");
_listener.Start();
_ = Task.Run(async () =>
{
while (_listener.IsListening)
{
HttpListenerContext ctx;
try { ctx = await _listener.GetContextAsync(); }
catch { break; }
using var ms = new MemoryStream();
await ctx.Request.InputStream.CopyToAsync(ms);
LastRequest = ms.ToArray();
var resp = respond(LastRequest);
ctx.Response.ContentType = "text/xml; charset=utf-8";
ctx.Response.OutputStream.Write(resp);
ctx.Response.Close();
}
});
}
public void Dispose() { try { _listener.Stop(); } catch { } _listener.Close(); }
}
private static async Task CallAsync(string url, IExchange exchange,
Action? tune = null, bool throwOnFault = true)
{
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
var factory = new SoapConnectionFactory { EndpointUrl = url, SoapVersion = SoapVersion.Soap11 };
tune?.Invoke(factory);
ctx.AddToRegistry("svc", factory);
ctx.AddRoutes(r =>
{
var call = SoapDsl.Call(url).ConnectionFactory("svc").Operation("GetFares");
if (!throwOnFault) call = call.ThrowOnFault(false);
r.From("direct://call").To(call);
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
await producer.Process(exchange);
return exchange;
}
[Fact]
public async Task Producer_SendsEnvelope_And_ReturnsResponseBody()
{
const string response = "100";
using var stub = new SoapStub(_ => SoapEnvelope.Build(response, SoapVersion.Soap11));
var exchange = new Exchange(new Message("SVO"));
await CallAsync(stub.Url, exchange);
// The server received a valid SOAP envelope carrying our payload.
var received = Encoding.UTF8.GetString(stub.LastRequest!);
received.Should().Contain("Envelope").And.Contain("GetFares").And.Contain("SVO");
// The response body came back on Out.
exchange.Out.Should().NotBeNull();
exchange.Out!.Body!.ToString().Should().Contain("GetFaresResponse").And.Contain("100");
}
[Fact]
public async Task Producer_OnFault_Throws_And_SetsFaultHeaders()
{
using var stub = new SoapStub(_ => SoapEnvelope.BuildFault("no such route", SoapVersion.Soap11, "soap:Client"));
var exchange = new Exchange(new Message(""));
var act = async () => await CallAsync(stub.Url, exchange);
await act.Should().ThrowAsync().Where(e => e.FaultString == "no such route");
exchange.In.GetHeader(SoapHeaders.FaultCode).Should().Be("soap:Client");
}
[Fact]
public async Task Producer_WithThrowOnFaultFalse_ReturnsTheFaultAsTheReply()
{
// A fault is an answer the service is designed to give ("no such route"), and a caller that
// expects it should branch on headers, not catch. Same rule as the HTTP producer's
// throwOnError: the option is explicit, never guessed from the code inside the fault.
using var stub = new SoapStub(_ => SoapEnvelope.BuildFault("no such route", SoapVersion.Soap11, "soap:Client"));
var exchange = new Exchange(new Message(""));
await CallAsync(stub.Url, exchange, tune: null, throwOnFault: false);
exchange.Exception.Should().BeNull();
exchange.In.GetHeader(SoapHeaders.IsFault).Should().BeTrue();
exchange.In.GetHeader(SoapHeaders.FaultCode).Should().Be("soap:Client");
exchange.In.GetHeader(SoapHeaders.FaultString).Should().Be("no such route");
exchange.Out!.Body!.ToString().Should().Contain("Fault", "the reply body is the fault envelope's payload");
}
[Fact]
public async Task Producer_ThrowsOnFaultByDefault()
{
using var stub = new SoapStub(_ => SoapEnvelope.BuildFault("no such route", SoapVersion.Soap11, "soap:Client"));
var act = async () => await CallAsync(stub.Url, new Exchange(new Message("")));
await act.Should().ThrowAsync();
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapRealFormatTests.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.Soap/SoapRealFormatTests.cs
----
using AwesomeAssertions;
using redb.Route.Soap;
namespace redb.Route.Tests.Soap;
///
/// Offline interop (no vulnerable dependency): robustness against the wire formats real SOAP stacks
/// (WCF/CXF) actually emit — arbitrary namespace prefixes, WS-Addressing headers with mustUnderstand,
/// SOAP 1.2 faults. Our parser is namespace-driven, so prefixes must not matter. Live interop against an
/// independent stack (Java CXF in Docker) is the remaining net-gated step; see the plan.
///
public class SoapRealFormatTests
{
// A .NET WCF response: envelope prefix "s", WS-Addressing header with s:mustUnderstand, default-ns body.
private const string WcfStyle =
"" +
"" +
"urn:GetFares" +
"" +
"100" +
"";
// An Apache CXF response: prefix "soapenv", body element with its own prefix "ns1".
private const string CxfStyle =
"" +
"200" +
"";
[Fact]
public void Parses_WcfStyle_PrefixedEnvelope()
{
var parsed = SoapEnvelope.Parse(System.Text.Encoding.UTF8.GetBytes(WcfStyle), SoapVersion.Soap11);
parsed.IsFault.Should().BeFalse();
parsed.BodyXml.Should().Contain("GetFaresResponse").And.Contain("100");
}
[Fact]
public void Reads_WcfStyle_EnvelopeHeader_WithMustUnderstand()
{
var headers = SoapEnvelope.ReadHeaders(System.Text.Encoding.UTF8.GetBytes(WcfStyle), SoapVersion.Soap11).ToList();
headers.Should().ContainSingle();
headers[0].Name.LocalName.Should().Be("Action");
headers[0].Value.Should().Be("urn:GetFares");
}
[Fact]
public void Parses_CxfStyle_PrefixedBodyElement()
{
var parsed = SoapEnvelope.Parse(System.Text.Encoding.UTF8.GetBytes(CxfStyle), SoapVersion.Soap11);
parsed.IsFault.Should().BeFalse();
parsed.BodyXml.Should().Contain("getFaresResponse").And.Contain("200");
}
[Fact]
public void Parses_Soap12_Fault_FromRealShape()
{
const string fault12 =
"" +
"" +
"env:Sender" +
"Invalid fare request" +
"" +
"";
var parsed = SoapEnvelope.Parse(System.Text.Encoding.UTF8.GetBytes(fault12), SoapVersion.Soap12);
parsed.IsFault.Should().BeTrue();
parsed.FaultCode.Should().Be("env:Sender");
parsed.FaultString.Should().Be("Invalid fare request");
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapRestartTests.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.Soap/SoapRestartTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// A SOAP consumer and producer keep working after Stop() and Start() of the same route context: the stop
/// gives the listener path back, the start registers it again on the cached endpoint.
///
public class SoapRestartTests
{
[Fact]
public async Task Consumer_and_producer_work_after_the_context_is_stopped_and_started_again()
{
var port = global::redb.Route.Tests.Shared.TestPorts.Next();
var received = 0;
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port)).Process(e =>
{
Interlocked.Increment(ref received);
e.In.Body = "ok";
});
r.From("direct://call").To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").Operation("Ping"));
});
async Task CheckAsync(int round)
{
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message(""));
await producer.Process(exchange);
exchange.Exception.Should().BeNull("a SOAP call after a restart arrives");
exchange.Out!.Body!.ToString().Should().Contain("ok");
Volatile.Read(ref received).Should().Be(round);
}
await ctx.Start();
await CheckAsync(1);
await ctx.Stop();
await ctx.Start();
await CheckAsync(2);
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapSecurityTests.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.Soap/SoapSecurityTests.cs
----
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
/// WS-Security UsernameToken flows producer → wire → consumer.
public class SoapSecurityTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
[Fact]
public async Task UsernameToken_ReachesConsumer()
{
var port = FreePort();
string? gotUser = null;
string? gotPass = null;
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddToRegistry("secured", new SoapConnectionFactory
{
EndpointUrl = $"http://127.0.0.1:{port}/svc",
SoapVersion = SoapVersion.Soap11,
Username = "alice",
Password = "secret",
});
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e =>
{
gotUser = e.In.GetHeader(SoapHeaders.Username);
gotPass = e.In.GetHeader(SoapHeaders.Password);
e.In.Body = "ok";
});
r.From("direct://call")
.To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").ConnectionFactory("secured"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("")));
gotUser.Should().Be("alice");
gotPass.Should().Be("secret");
}
private static X509Certificate2 SelfSigned()
{
using var rsa = RSA.Create(2048);
var req = new CertificateRequest("CN=soap-test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1));
}
[Fact]
public async Task SignedBody_IsVerifiedByConsumer()
{
var port = FreePort();
bool? sigValid = null;
using var cert = SelfSigned();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddToRegistry("signed", new SoapConnectionFactory
{
EndpointUrl = $"http://127.0.0.1:{port}/svc",
SoapVersion = SoapVersion.Soap11,
SigningCert = cert,
});
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e =>
{
sigValid = e.In.GetHeader(SoapHeaders.SignatureValid);
e.In.Body = "ok";
});
r.From("direct://call")
.To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").ConnectionFactory("signed"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("1")));
sigValid.Should().BeTrue("the consumer must verify the WS-Security Body signature");
}
[Fact]
public void VerifyBody_AuthenticatesAgainstExpectedCert_And_RejectsOthers()
{
using var signer = SelfSigned();
using var other = SelfSigned(); // a different, untrusted certificate
var envelope = SoapEnvelope.Build("", SoapVersion.Soap11);
var doc = new System.Xml.XmlDocument { PreserveWhitespace = true };
doc.Load(new MemoryStream(envelope));
SoapSignature.SignBody(doc, signer, SoapVersion.Soap11);
// Expected partner == the actual signer ⇒ authenticated.
SoapSignature.VerifyBody(doc, signer, SoapVersion.Soap11).Should().BeTrue();
// Expected partner == a DIFFERENT cert ⇒ rejected (this is the H1 fix: no blind trust of embedded cert).
SoapSignature.VerifyBody(doc, other, SoapVersion.Soap11).Should().BeFalse();
// No expected cert ⇒ integrity-only still passes, but this does NOT authenticate the sender.
SoapSignature.VerifyBody(doc, null, SoapVersion.Soap11).Should().BeTrue();
}
[Fact]
public void VerifyBody_Fails_WhenBodyTamperedAfterSigning()
{
using var signer = SelfSigned();
var envelope = SoapEnvelope.Build("1", SoapVersion.Soap11);
var doc = new System.Xml.XmlDocument { PreserveWhitespace = true };
doc.Load(new MemoryStream(envelope));
SoapSignature.SignBody(doc, signer, SoapVersion.Soap11);
// Tamper the signed Body payload.
var n = doc.GetElementsByTagName("n")[0]!;
n.InnerText = "999";
SoapSignature.VerifyBody(doc, signer, SoapVersion.Soap11).Should().BeFalse();
}
[Fact]
public void VerifyBody_Rejects_SignatureWrapping()
{
using var cert = SelfSigned();
var envelope = SoapEnvelope.Build("1", SoapVersion.Soap11);
var doc = new System.Xml.XmlDocument { PreserveWhitespace = true };
doc.Load(new MemoryStream(envelope));
SoapSignature.SignBody(doc, cert, SoapVersion.Soap11);
// Signature-wrapping attack: move the genuinely-signed Body under (first in document order),
// and put an attacker-controlled Body as the Envelope's direct child (what the processing path reads).
const string soapNs = "http://schemas.xmlsoap.org/soap/envelope/";
var env = doc.DocumentElement!;
var header = (System.Xml.XmlElement)env.GetElementsByTagName("Header", soapNs)[0]!;
var signedBody = (System.Xml.XmlElement)env.GetElementsByTagName("Body", soapNs)[0]!;
env.RemoveChild(signedBody);
header.AppendChild(signedBody);
var evil = doc.CreateElement("soap", "Body", soapNs);
evil.InnerXml = "999";
env.AppendChild(evil);
// The signature still validates over the nested original, but it does NOT cover the direct-child Body
// the route consumes — so verification must fail, in both authenticated and integrity-only modes.
SoapSignature.VerifyBody(doc, cert, SoapVersion.Soap11).Should().BeFalse();
SoapSignature.VerifyBody(doc, null, SoapVersion.Soap11).Should().BeFalse();
}
///
/// Sets one unused bit of the last character of a padded base64 value: the bytes .NET 10 decodes stay the same,
/// .NET 11 refuses the value, XML Schema base64Binary has no such spelling.
///
private static void SetUnusedBit(System.Xml.XmlNode node)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var text = node.InnerText.Trim();
text.Should().EndWith("==", "a 256-byte RSA value leaves 4 unused bits in its last character");
var chars = text.ToCharArray();
chars[^3] = alphabet[alphabet.IndexOf(chars[^3], StringComparison.Ordinal) | 0b1];
node.InnerText = new string(chars);
}
[Fact]
public void VerifyBody_RefusesASignatureValueWithNonZeroUnusedBits_OnEveryRuntime()
{
using var signer = SelfSigned();
var envelope = SoapEnvelope.Build("", SoapVersion.Soap11);
var doc = new System.Xml.XmlDocument { PreserveWhitespace = true };
doc.Load(new MemoryStream(envelope));
SoapSignature.SignBody(doc, signer, SoapVersion.Soap11);
// SignatureValue is outside SignedInfo: .NET 10 would verify the same signature bytes, .NET 11 would throw.
SetUnusedBit(doc.GetElementsByTagName("SignatureValue", System.Security.Cryptography.Xml.SignedXml.XmlDsigNamespaceUrl)[0]!);
SoapSignature.VerifyBody(doc, signer, SoapVersion.Soap11).Should().BeFalse();
SoapSignature.VerifyBody(doc, null, SoapVersion.Soap11).Should().BeFalse();
}
[Fact]
public void DecryptBody_RefusesAnEncryptedKeyWithNonZeroUnusedBits_OnEveryRuntime()
{
using var cert = SelfSigned();
var envelope = SoapEnvelope.Build("secret1", SoapVersion.Soap11);
var doc = new System.Xml.XmlDocument { PreserveWhitespace = true };
doc.Load(new MemoryStream(envelope));
SoapEncryption.EncryptBody(doc, cert, SoapVersion.Soap11);
// The wrapped key is 256 bytes: .NET 10 would unwrap the same key, .NET 11 would throw FormatException.
var encryptedKey = (System.Xml.XmlElement)doc.GetElementsByTagName("EncryptedKey", SoapEncryption.XmlEncNs)[0]!;
SetUnusedBit(encryptedKey.GetElementsByTagName("CipherValue", SoapEncryption.XmlEncNs)[0]!);
var act = () => SoapEncryption.DecryptBody(doc, cert);
act.Should().Throw().WithMessage("*CipherValue*not canonical base64*");
doc.OuterXml.Should().NotContain("secret1");
}
[Fact]
public void EncryptBody_Encrypts_All_Body_Children()
{
using var cert = SelfSigned();
// A document/literal Body with two children: both must be encrypted, not just the first.
var envelope = SoapEnvelope.Build("secret1secret2", SoapVersion.Soap11);
var doc = new System.Xml.XmlDocument { PreserveWhitespace = true };
doc.Load(new MemoryStream(envelope));
SoapEncryption.EncryptBody(doc, cert, SoapVersion.Soap11);
doc.OuterXml.Should().NotContain("secret1").And.NotContain("secret2");
doc.GetElementsByTagName("EncryptedData", SoapEncryption.XmlEncNs).Count.Should().Be(2);
// And the one EncryptedKey / ReferenceList round-trips both back.
SoapEncryption.DecryptBody(doc, cert);
doc.OuterXml.Should().Contain("secret1").And.Contain("secret2");
}
[Fact]
public void EncryptBody_ProducesStandardWssLayout()
{
using var cert = SelfSigned();
var envelope = SoapEnvelope.Build("1", SoapVersion.Soap11);
var doc = new System.Xml.XmlDocument { PreserveWhitespace = true };
doc.Load(new MemoryStream(envelope));
SoapEncryption.EncryptBody(doc, cert, SoapVersion.Soap11);
var ns = new System.Xml.XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
ns.AddNamespace("wsse", SoapSecurity.WsseNs);
ns.AddNamespace("xenc", SoapEncryption.XmlEncNs);
// EncryptedKey lives in the header (standard WSS layout), not nested in EncryptedData.
doc.SelectSingleNode("//wsse:Security/xenc:EncryptedKey", ns).Should().NotBeNull();
// It references the EncryptedData by Id via a ReferenceList/DataReference.
var dataRefUri = doc.SelectSingleNode(
"//xenc:EncryptedKey/xenc:ReferenceList/xenc:DataReference/@URI", ns)?.Value;
dataRefUri.Should().StartWith("#ED-");
// The EncryptedData sits in the Body with the matching Id, and carries no nested EncryptedKey.
var ed = doc.SelectSingleNode("//soap:Body/xenc:EncryptedData", ns) as System.Xml.XmlElement;
ed.Should().NotBeNull();
("#" + ed!.GetAttribute("Id")).Should().Be(dataRefUri);
ed.SelectSingleNode(".//xenc:EncryptedKey", ns).Should().BeNull();
}
[Fact]
public async Task SignedAndEncrypted_RoundTrips_DecryptThenVerify()
{
var port = FreePort();
string? gotBody = null;
bool? sigValid = null;
using var cert = SelfSigned();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
// Client signs with its cert AND encrypts to the partner; server holds the key (decrypt) and knows the
// partner cert (authenticated verify). Exercises the sign→encrypt / decrypt→verify round-trip.
ctx.AddToRegistry("client", new SoapConnectionFactory
{
EndpointUrl = $"http://127.0.0.1:{port}/svc",
SoapVersion = SoapVersion.Soap11,
SigningCert = cert,
EncryptCert = cert,
});
ctx.AddToRegistry("server", new SoapConnectionFactory { SigningCert = cert, EncryptCert = cert });
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port).ConnectionFactory("server"))
.Process(e =>
{
gotBody = e.In.Body!.ToString();
sigValid = e.In.GetHeader(SoapHeaders.SignatureValid);
e.In.Body = "ok";
});
r.From("direct://call").To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").ConnectionFactory("client"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("7")));
gotBody.Should().NotBeNull().And.Contain("Secret").And.Contain("7"); // decrypted
sigValid.Should().BeTrue("the signature must verify against the expected partner cert after decryption");
}
[Fact]
public async Task EncryptedBody_IsDecryptedByConsumer()
{
var port = FreePort();
string? gotBody = null;
using var cert = SelfSigned();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
// Producer encrypts to the partner's public cert (no signing); consumer decrypts with the private key.
ctx.AddToRegistry("client", new SoapConnectionFactory
{
EndpointUrl = $"http://127.0.0.1:{port}/svc",
SoapVersion = SoapVersion.Soap11,
EncryptCert = cert,
});
ctx.AddToRegistry("server", new SoapConnectionFactory { SigningCert = cert });
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port).ConnectionFactory("server"))
.Process(e => { gotBody = e.In.Body!.ToString(); e.In.Body = "ok"; });
r.From("direct://call")
.To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").ConnectionFactory("client"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("42")));
// The route received plaintext — proving the Body was encrypted on the wire and decrypted on receipt.
gotBody.Should().NotBeNull().And.Contain("Secret").And.Contain("42");
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapStopDrainsInflightTests.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.Soap/SoapStopDrainsInflightTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// Stopping one route on a shared listener must wait for the calls it is already serving. It used to
/// unregister the route and ask the listener to stop when empty — and when another route still holds
/// the port, the listener stays up, so nobody waited and a deploy cut the call mid-pipeline. Reported
/// by the AS4 agent 2026-09-25; the drain is the engine's .
///
public class SoapStopDrainsInflightTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
[Fact]
public async Task Stop_waits_for_a_call_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 ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
var slow = ctx.GetEndpoint(SoapDsl.Listen("/slow").Host("127.0.0.1").Port(port).Build())
.CreateConsumer(new redb.Route.Processors.DelegateProcessor(async (e, ct) =>
{
entered.TrySetResult();
await release.Task;
finished = true;
e.In.Body = "ok";
}));
// A second route keeps the listener alive after the first one is stopped — the case where
// nothing used to wait.
var other = ctx.GetEndpoint(SoapDsl.Listen("/other").Host("127.0.0.1").Port(port).Build())
.CreateConsumer(new redb.Route.Processors.DelegateProcessor(_ => { }));
await slow.Start();
await other.Start();
using var http = new HttpClient();
var content = new ByteArrayContent(SoapEnvelope.Build("", SoapVersion.Soap12));
content.Headers.ContentType = MediaTypeHeaderValue.Parse(SoapEnvelope.ContentType(SoapVersion.Soap12, "urn:t/Op"));
var call = http.PostAsync($"http://127.0.0.1:{port}/slow", content);
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5));
var stop = slow.Stop();
(await Task.WhenAny(stop, Task.Delay(500)) == stop)
.Should().BeFalse("Stop must not return while a call of this route is still running");
release.TrySetResult();
await stop.WaitAsync(TimeSpan.FromSeconds(10));
finished.Should().BeTrue();
(await call).StatusCode.Should().Be(HttpStatusCode.OK);
await other.Stop();
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapTracePropagationTests.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.Soap/SoapTracePropagationTests.cs
----
using System.Diagnostics;
using System.Net;
using System.Text;
using AwesomeAssertions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Soap;
using redb.Route.Telemetry;
using redb.Route.Tests.Telemetry;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// A SOAP request is inbound traffic like an HTTP request: the consumer's server span covers the whole request, the
/// ones refused before the envelope is read included, continues the caller's trace from traceparent and puts the
/// caller's baggage back; a failed route marks it red. The producer's client span is an RPC span (rpc.method, no
/// messaging.*) and the request carries its context, so the service's span is its child.
/// EnableTelemetry=false opens none of these spans.
///
public sealed class SoapTracePropagationTests : IAsyncLifetime
{
private const string Ping = "1";
private int _port;
private int _offPort;
private RouteContext _ctx = null!;
private RouteContext _offCtx = null!;
private HttpClient _client = null!;
public async Task InitializeAsync()
{
_port = global::redb.Route.Tests.Shared.TestPorts.Next();
_offPort = global::redb.Route.Tests.Shared.TestPorts.Next();
_client = new HttpClient();
var port = _port;
_ctx = new RouteContext();
_ctx.AddComponent(new SoapComponent());
_ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/traced").Host("127.0.0.1").Port(port)).RouteId($"soap-trace-{port}-traced")
.Process(e => e.In.Body = "ok");
r.From(SoapDsl.Listen("/fails").Host("127.0.0.1").Port(port)).RouteId($"soap-trace-{port}-fails")
.Process(_ => throw new InvalidOperationException("route failed"));
r.From(SoapDsl.Listen("/baggage").Host("127.0.0.1").Port(port)).RouteId($"soap-trace-{port}-baggage")
.Process(e => e.In.Body = $"{Activity.Current?.GetBaggageItem("tenant") ?? "none"}");
r.From($"direct://soap-trace-{port}-call")
.To(SoapDsl.Call($"http://127.0.0.1:{port}/traced").Operation("Ping"));
r.From(SoapDsl.Listen("/sender-fault").Host("127.0.0.1").Port(port))
.Process(_ => throw new SoapFaultException("soap:Client", "no such order"));
r.From(SoapDsl.Listen("/receiver-fault").Host("127.0.0.1").Port(port))
.Process(_ => throw new SoapFaultException("soap:Server", "backend down"));
r.From(SoapDsl.Listen("/declared-sender").Host("127.0.0.1").Port(port))
.Process(e => e.In.Headers[SoapHeaders.FaultString] = "no such order");
r.From(SoapDsl.Listen("/declared-receiver").Host("127.0.0.1").Port(port))
.Process(e =>
{
e.In.Headers[SoapHeaders.FaultString] = "backend down";
e.In.Headers[SoapHeaders.FaultCode] = "soap:Server";
});
r.From(SoapDsl.Listen("/cancelled").Host("127.0.0.1").Port(port))
.Process(_ => throw new TaskCanceledException("a call inside the route timed out"));
r.From(SoapDsl.Listen("/slow").Host("127.0.0.1").Port(port))
.Process(async (_, ct) => await Task.Delay(5000, ct));
});
await _ctx.Start();
var offPort = _offPort;
_offCtx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false });
_offCtx.AddComponent(new SoapComponent());
_offCtx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/traced").Host("127.0.0.1").Port(offPort))
.Process(e => e.In.Body = "ok");
r.From($"direct://soap-trace-{offPort}-call")
.To(SoapDsl.Call($"http://127.0.0.1:{offPort}/traced").Operation("Ping"));
});
await _offCtx.Start();
}
public async Task DisposeAsync()
{
_client.Dispose();
await _ctx.DisposeAsync();
await _offCtx.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");
}
/// POSTs a SOAP 1.1 envelope, outside any activity: only carry a context.
private async Task Post(string path, string? contentType = null, string? body = null,
params (string Name, string Value)[] headers)
{
var ambient = Activity.Current;
Activity.Current = null;
try
{
var envelope = body ?? $"{Ping}";
var request = new HttpRequestMessage(HttpMethod.Post, $"http://127.0.0.1:{_port}{path}")
{
Content = new StringContent(envelope, Encoding.UTF8),
};
request.Content.Headers.Remove("Content-Type");
request.Content.Headers.TryAddWithoutValidation("Content-Type", contentType ?? "text/xml; charset=utf-8");
foreach (var (name, value) in headers)
request.Headers.TryAddWithoutValidation(name, value);
return await _client.SendAsync(request);
}
finally
{
Activity.Current = ambient;
}
}
private RouteTelemetryProbe ServerSpans(string path)
=> new(a => a.Kind == ActivityKind.Server
&& RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag) is { } endpoint
&& endpoint.Contains(_port.ToString(), StringComparison.Ordinal)
&& endpoint.Contains(path, StringComparison.Ordinal));
[Fact]
public async Task A_request_opens_a_server_span_that_continues_the_callers_trace()
{
using var probe = ServerSpans("/traced");
using var routes = RouteTelemetryProbe.ForRouteIdPrefix($"soap-trace-{_port}-traced");
var caller = Caller();
(await Post("/traced", headers: ("traceparent", caller.Header))).StatusCode.Should().Be(HttpStatusCode.OK);
var server = probe.Activities.Should().ContainSingle().Subject;
server.TraceId.Should().Be(caller.TraceId);
server.ParentSpanId.Should().Be(caller.SpanId);
routes.Activities.Should().ContainSingle().Which.ParentSpanId.Should().Be(server.SpanId,
"the route runs inside the request");
}
[Fact]
public async Task A_request_refused_before_the_envelope_is_read_has_its_span_too()
{
using var probe = ServerSpans("/traced");
var response = await Post("/traced", "multipart/related; boundary=BND", "not a multipart body");
response.IsSuccessStatusCode.Should().BeFalse();
probe.Activities.Should().ContainSingle()
.Which.Status.Should().NotBe(ActivityStatusCode.Error, "a malformed request is the caller's mistake, answered correctly");
}
[Fact]
public async Task The_callers_baggage_reaches_the_route()
{
using var probe = ServerSpans("/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 Post("/baggage", headers: headers.Select(h => (h.Key, h.Value)).ToArray());
(await response.Content.ReadAsStringAsync()).Should().Contain(">t1<");
}
[Fact]
public async Task A_failed_route_marks_the_server_span_red()
{
using var probe = ServerSpans("/fails");
await Post("/fails");
probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error);
}
[Theory]
[InlineData("/sender-fault")]
[InlineData("/declared-sender")]
public async Task A_sender_fault_the_route_chose_is_an_answer_not_a_failure(string path)
{
using var probe = ServerSpans(path);
var response = await Post(path);
(await response.Content.ReadAsStringAsync()).Should().Contain("Fault");
probe.Activities.Should().ContainSingle().Which.Status.Should().NotBe(ActivityStatusCode.Error,
"a Client/Sender fault is the caller's mistake, answered correctly");
}
[Theory]
[InlineData("/receiver-fault")]
[InlineData("/declared-receiver")]
public async Task A_receiver_fault_marks_the_server_span_red(string path)
{
using var probe = ServerSpans(path);
var response = await Post(path);
(await response.Content.ReadAsStringAsync()).Should().Contain("Fault");
probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error);
}
[Fact]
public async Task A_cancellation_the_caller_did_not_ask_for_fails_the_request_and_its_span()
{
using var probe = ServerSpans("/cancelled");
var response = await Post("/cancelled");
(await response.Content.ReadAsStringAsync()).Should().Contain("Fault", "the caller gets a fault, not a bare 500");
probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error);
}
[Fact]
public async Task The_caller_going_away_is_a_stop_not_a_failure()
{
using var probe = ServerSpans("/slow");
using var impatient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(300) };
var envelope = $"{Ping}";
var act = () => impatient.PostAsync($"http://127.0.0.1:{_port}/slow", new StringContent(envelope, Encoding.UTF8, "text/xml"));
await act.Should().ThrowAsync();
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (probe.Activities.Count == 0 && DateTime.UtcNow < deadline)
await Task.Delay(100);
probe.Activities.Should().ContainSingle().Which.Status.Should().NotBe(ActivityStatusCode.Error);
}
[Fact]
public async Task The_producer_opens_an_rpc_span_and_the_service_runs_under_it()
{
using var server = ServerSpans("/traced");
using var client = new RouteTelemetryProbe(a => a.Kind == ActivityKind.Client
&& RouteTelemetryProbe.Tag(a, "rpc.system") == "soap"
&& RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)!.Contains(_port.ToString(), StringComparison.Ordinal));
var producer = _ctx.GetEndpoint($"direct://soap-trace-{_port}-call").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message(Ping)));
var send = client.Activities.Should().ContainSingle().Subject;
send.GetTagItem("rpc.method").Should().Be("Ping");
send.GetTagItem("messaging.operation").Should().BeNull("an RPC call is not a messaging operation");
send.GetTagItem("messaging.destination.name").Should().BeNull("the URL is not a messaging destination");
server.Activities.Should().ContainSingle().Which.ParentSpanId.Should().Be(send.SpanId,
"the request carries the context of the send");
}
[Fact]
public async Task Tracing_off_opens_no_span()
{
using var probe = new RouteTelemetryProbe(a =>
RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_offPort.ToString(), StringComparison.Ordinal) == true);
var producer = _offCtx.GetEndpoint($"direct://soap-trace-{_offPort}-call").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message(Ping)));
probe.Activities.Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapTransportSecurityTests.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.Soap/SoapTransportSecurityTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// The consumer's transport security: TLS material and the client-certificate policy actually reach the
/// listener, and a configuration that cannot work is refused at start rather than at the first handshake.
///
public class SoapTransportSecurityTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
[Fact]
public void Ssl_Listener_Uri_Carries_The_Scheme_And_The_Certificate_Path()
{
var uri = SoapDsl.Listen("/sts").Host("127.0.0.1").Port(8443)
.Ssl("/etc/certs/sts.pfx")
.ClientCertificate(SoapClientCertificateMode.RequireCertificate, "AA11,BB22")
.Build();
// The scheme is what the component reads TLS from; a parameter alone would leave it plaintext.
uri.Should().StartWith("soaps:/sts");
uri.Should().Contain("sslCertPath=");
uri.Should().Contain("clientCertificateMode=RequireCertificate");
uri.Should().Contain("allowedClientThumbprints=AA11%2CBB22");
}
[Fact]
public void The_Endpoint_Reads_Tls_Settings_From_The_Uri()
{
var component = new SoapComponent();
var endpoint = (SoapEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(
SoapDsl.Listen("/sts").Host("127.0.0.1").Port(8443)
.Ssl("/etc/certs/sts.pfx")
.ClientCertificate(SoapClientCertificateMode.AllowCertificate, "AA11")
.Build()));
var options = endpoint.SoapOptions;
options.UseTls.Should().BeTrue();
options.SslCertPath.Should().Be("/etc/certs/sts.pfx");
options.ClientCertificateMode.Should().Be(SoapClientCertificateMode.AllowCertificate);
options.AllowedClientThumbprints.Should().Be("AA11");
}
///
/// Builds a consumer the way the context does, but without the context: RouteContext.Start
/// logs a consumer that fails to start and carries on with the rest, which is right for a running
/// process and useless for asserting that a refusal happened.
///
private static (RouteContext Context, IConsumer Consumer) BuildConsumer(
string uri, Action? configure = null)
{
var ctx = new RouteContext();
var component = new SoapComponent();
ctx.AddComponent(component);
configure?.Invoke(ctx);
var endpoint = component.CreateEndpoint(EndpointUriParser.Parse(uri));
return (ctx, endpoint.CreateConsumer(new DelegateProcessor(e => e.In.Body = "")));
}
///
/// Without this the listener starts on HTTPS with no certificate, and Kestrel falls back to the
/// development certificate: present on a developer's box, absent in production. The failure then
/// surfaces far from its cause, which is the worst place for a TLS misconfiguration to surface.
///
[Fact]
public async Task Tls_Without_A_Certificate_Is_Refused_At_Start()
{
var (ctx, consumer) = BuildConsumer(
SoapDsl.Listen("/sts").Host("127.0.0.1").Port(FreePort()).Ssl());
await using var _ = ctx;
var start = async () => await consumer.Start();
(await start.Should().ThrowAsync())
.Which.Message.Should().Contain("no certificate");
}
///
/// A client certificate is presented during the TLS handshake. Asking for one on a plaintext listener
/// is a policy that can never be enforced, and silently accepting it would leave an operator believing
/// the endpoint is pinned to their partners when it is open to anyone.
///
[Fact]
public async Task Client_Certificates_Without_Tls_Are_Refused_At_Start()
{
var (ctx, consumer) = BuildConsumer(
SoapDsl.Listen("/sts").Host("127.0.0.1").Port(FreePort())
.ClientCertificate(SoapClientCertificateMode.RequireCertificate));
await using var _ = ctx;
var start = async () => await consumer.Start();
(await start.Should().ThrowAsync())
.Which.Message.Should().Contain("without TLS");
}
///
/// The certificate password belongs on the registered factory, never in the URI: the URI is the route
/// key and is handled as an ordinary string by logging, telemetry and the dashboard.
///
[Fact]
public async Task The_Factory_Supplies_Tls_Material_The_Uri_Does_Not_Carry()
{
var uri = SoapDsl.Listen("/sts").Host("127.0.0.1").Port(FreePort())
.ConnectionFactory("sts-tls").Build();
uri.Should().NotContain("sslCertPath");
var (ctx, consumer) = BuildConsumer(uri, c => c.AddToRegistry("sts-tls",
new SoapConnectionFactory
{
Ssl = true,
SslCertPath = "/nonexistent/sts.pfx",
SslCertPassword = "s3cret",
}));
await using var _ = ctx;
var start = async () => await consumer.Start();
// TLS came from the factory, so the certificate check passes and the failure is Kestrel's own:
// the file is not there. Had the factory been ignored, the listener would have come up plaintext
// and this would not have thrown at all.
var thrown = (await start.Should().ThrowAsync()).Which.ToString();
thrown.Should().NotContain("no certificate");
thrown.Should().NotContain("s3cret");
}
///
/// A route behind a SOAP endpoint could not learn who was calling: the consumer surfaced nothing
/// from the connection at all. Every IP-keyed protection therefore saw nothing and silently did
/// nothing, which reads as «no abuse» rather than as «not wired».
///
[Fact]
public async Task The_Callers_Address_Reaches_The_Route()
{
var port = FreePort();
object? remote = null, compat = null;
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port).HttpCompatHeaders())
.Process(e =>
{
e.In.Headers.TryGetValue(SoapHeaders.RemoteAddress, out remote);
e.In.Headers.TryGetValue("redbHttp.RemoteAddress", out compat);
e.In.Body = "ok";
});
r.From("direct://call").To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").Operation("Ping"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("")));
remote.Should().Be("127.0.0.1");
// The HTTP-namespace bridge is what lets processors written for the HTTP transport work here
// unchanged. It is opt-in, and this route asked for it.
compat.Should().Be("127.0.0.1");
}
///
/// The bridge stays off unless a route asks: writing into another transport's namespace is a
/// deliberate act, and the connector's own headers already carry the same facts.
///
[Fact]
public async Task The_Http_Namespace_Bridge_Is_Off_By_Default()
{
var port = FreePort();
var sawCompat = true;
object? remote = null;
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e =>
{
sawCompat = e.In.Headers.ContainsKey("redbHttp.RemoteAddress");
e.In.Headers.TryGetValue(SoapHeaders.RemoteAddress, out remote);
e.In.Body = "ok";
});
r.From("direct://call").To(SoapDsl.Call($"http://127.0.0.1:{port}/svc").Operation("Ping"));
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://call").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("")));
sawCompat.Should().BeFalse();
// The native header is unconditional: a route always gets to know who called.
remote.Should().Be("127.0.0.1");
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapWsdlTests.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.Soap/SoapWsdlTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// WSDL publishing (camel-cxf ?wsdl parity): a consumer with a configured WSDL serves it on GET, with
/// the soap:address rewritten to the caller's URL; without one, GET is not allowed.
///
public class SoapWsdlTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
private const string SampleWsdl =
"" +
"" +
"" +
"" +
"" +
"";
[Fact]
public void RewriteAddress_ReplacesSoapLocation()
{
var rewritten = SoapWsdl.RewriteAddress(SampleWsdl, "https://real.example/svc");
rewritten.Should().Contain("https://real.example/svc").And.NotContain("placeholder.invalid");
}
[Fact]
public async Task Consumer_PublishesWsdl_On_Get_WithRewrittenAddress()
{
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddToRegistry("pub", new SoapConnectionFactory { Wsdl = SampleWsdl });
ctx.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port).ConnectionFactory("pub"))
.Process(e => e.In.Body = ""));
await ctx.Start();
using var http = new HttpClient();
var resp = await http.GetAsync($"http://127.0.0.1:{port}/svc?wsdl");
resp.StatusCode.Should().Be(HttpStatusCode.OK);
resp.Content.Headers.ContentType!.MediaType.Should().Be("text/xml");
var body = await resp.Content.ReadAsStringAsync();
body.Should().Contain("EchoService").And.Contain("Echo");
body.Should().Contain($"http://127.0.0.1:{port}/svc").And.NotContain("placeholder.invalid");
}
[Fact]
public async Task Consumer_WithoutWsdl_RejectsGet()
{
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r => r.From(SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port))
.Process(e => e.In.Body = ""));
await ctx.Start();
using var http = new HttpClient();
var resp = await http.GetAsync($"http://127.0.0.1:{port}/svc?wsdl");
// No WSDL configured ⇒ GET is not a registered method on this path.
resp.StatusCode.Should().Be(HttpStatusCode.MethodNotAllowed);
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/SoapXmlLimitsTests.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.Soap/SoapXmlLimitsTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Soap;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Soap;
///
/// The SOAP receiver bounds what it reads (11-XML-HARDENING, layer 1). The envelope is parsed several times on its
/// way to the route, so its structure is checked once up front against , and again
/// after decryption: anyone can encrypt for our certificate, so the plaintext is the caller's too. A request over a
/// limit is the sender's fault and says which limit. The request body is bounded by maxRequestBodySize.
///
public class SoapXmlLimitsTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
private static string Nested(int levels) =>
string.Concat(Enumerable.Repeat("", levels)) + string.Concat(Enumerable.Repeat("", levels));
/// A raw envelope: SoapEnvelope.Build parses its body through SafeXml and would refuse the hostile one itself.
private static byte[] RawEnvelope(string body, SoapVersion version)
{
var ns = version == SoapVersion.Soap12 ? "http://www.w3.org/2003/05/soap-envelope" : "http://schemas.xmlsoap.org/soap/envelope/";
return System.Text.Encoding.UTF8.GetBytes($"{body}");
}
private static RouteContext Listening(int port, Func? listen = null,
SoapConnectionFactory? factory = null, Action? reached = null)
{
var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
if (factory is not null) ctx.AddToRegistry("server", factory);
ctx.AddRoutes(r =>
{
var builder = SoapDsl.Listen("/svc").Host("127.0.0.1").Port(port);
if (factory is not null) builder = builder.ConnectionFactory("server");
if (listen is not null) builder = listen(builder);
r.From(builder).Process(e => { reached?.Invoke(); e.In.Body = "ok"; });
});
return ctx;
}
private static async Task Post(int port, byte[] body, SoapVersion version)
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
var content = new ByteArrayContent(body);
content.Headers.ContentType = MediaTypeHeaderValue.Parse(SoapEnvelope.ContentType(version, "urn:t/Op"));
return await http.PostAsync($"http://127.0.0.1:{port}/svc", content);
}
private static async Task<(string? Code, string? Reason)> Fault(HttpResponseMessage response, SoapVersion version)
{
var parsed = SoapEnvelope.Parse(await response.Content.ReadAsByteArrayAsync(), version);
parsed.IsFault.Should().BeTrue("a request the consumer refuses comes back as a SOAP fault");
return (parsed.FaultCode, parsed.FaultString);
}
[Theory]
[InlineData(SoapVersion.Soap11, "soap:Client")]
[InlineData(SoapVersion.Soap12, "soap:Sender")]
public async Task A_body_over_the_depth_limit_is_the_senders_fault_and_never_reaches_the_route(SoapVersion version, string expected)
{
var port = FreePort();
var reached = false;
await using var ctx = Listening(port, reached: () => reached = true);
await ctx.Start();
var watch = System.Diagnostics.Stopwatch.StartNew();
using var response = await Post(port, RawEnvelope(Nested(100_000), version), version);
watch.Stop();
var (code, reason) = await Fault(response, version);
code.Should().Be(expected);
reason.Should().Contain(nameof(XmlLimits.MaxDepth));
reached.Should().BeFalse();
watch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(5));
}
[Fact]
public async Task A_body_within_the_limits_reaches_the_route()
{
var port = FreePort();
var reached = false;
await using var ctx = Listening(port, reached: () => reached = true);
await ctx.Start();
using var response = await Post(port, SoapEnvelope.Build(Nested(100), SoapVersion.Soap11), SoapVersion.Soap11);
response.StatusCode.Should().Be(HttpStatusCode.OK);
reached.Should().BeTrue();
}
[Fact]
public async Task An_encrypted_body_is_checked_again_after_decryption()
{
// The envelope is small and flat; the hostile structure is inside the ciphertext: one element with more attributes
// than the default limit. Not depth: the patched XML library refuses deep plaintext itself
// during decryption, before our check would see it.
using var rsa = RSA.Create(2048);
using var ours = new CertificateRequest("CN=server", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)
.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1));
var port = FreePort();
var reached = false;
await using var ctx = Listening(port, factory: new SoapConnectionFactory { SigningCert = ours }, reached: () => reached = true);
await ctx.Start();
var doc = new System.Xml.XmlDocument { PreserveWhitespace = true };
var wide = " $"a{i}=\"v\"")) + "/>";
doc.Load(new MemoryStream(RawEnvelope(wide, SoapVersion.Soap11)));
SoapEncryption.EncryptBody(doc, ours, SoapVersion.Soap11);
using var ms = new MemoryStream();
doc.Save(ms);
using var response = await Post(port, ms.ToArray(), SoapVersion.Soap11);
var (code, reason) = await Fault(response, SoapVersion.Soap11);
code.Should().Be("soap:Client");
reason.Should().Contain(nameof(XmlLimits.MaxAttributesPerElement));
reached.Should().BeFalse();
}
[Fact]
public async Task A_request_over_maxRequestBodySize_is_refused_by_the_server()
{
var port = FreePort();
var reached = false;
await using var ctx = Listening(port, listen: b => b.MaxRequestBodySize(64 * 1024), reached: () => reached = true);
await ctx.Start();
var big = SoapEnvelope.Build($"{new string('x', 200 * 1024)}", SoapVersion.Soap11);
using var response = await Post(port, big, SoapVersion.Soap11);
response.IsSuccessStatusCode.Should().BeFalse();
reached.Should().BeFalse();
}
[Fact]
public void The_default_request_body_bound_is_100_megabytes()
{
new SoapEndpointOptions().MaxRequestBodySize.Should().Be(100L * 1024 * 1024);
}
}
Path: redb-route/tests/redb.Route.Tests.Soap/redb.Route.Tests.Soap.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Soap/redb.Route.Tests.Soap.csproj
----