Bundle: redb-route / redb.Route.Soap (redb.Route.Soap.txt), 18 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Soap/Extensions/ServiceCollectionExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; using redb.Route.Http; namespace redb.Route.Soap; /// /// Extension methods for registering the SOAP transport in a DI container. /// public static class ServiceCollectionExtensions { /// /// Registers the so that soap:// and soaps:// URIs are resolved. /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteSoap(); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// public static IServiceCollection AddRedbRouteSoap(this IServiceCollection services) { // Share ONE Kestrel host with every other HTTP-based connector in this worker (idempotent). services.AddRedbRouteHttpHosting(); services.AddSingleton(); // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteContextConfigurator((sp, context) => { var component = sp.GetRequiredService(); component.ServerManager = sp.GetRequiredService(); context.AddComponent(component); // registers soap + soaps, sets Context + Logger }); return services; } } Path: redb-route/redb.Route.Soap/Fluent/Soap.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/Fluent/Soap.cs ---- using System.Text; namespace redb.Route.Soap.Fluent; /// /// Entry point for the SOAP fluent DSL. /// /// // Call a service /// .To(Soap.Call("https://gds/air.svc").ConnectionFactory("amadeus").Operation("GetFares")) /// /// // Host a SOAP endpoint /// From(Soap.Listen("/svc/orders").Host("0.0.0.0").Port(4090).ConnectionFactory("self")) /// /// public static class Soap { /// Producer: call a SOAP service at the given endpoint URL (http ⇒ soap, https ⇒ soaps). public static SoapProducerBuilder Call(string endpointUrl) => new(endpointUrl); /// Consumer: host a SOAP receive endpoint at the given path. public static SoapConsumerBuilder Listen(string path) => new(path); } /// Fluent builder for a SOAP producer (service call) URI. public sealed class SoapProducerBuilder { private readonly string _url; private string? _connectionFactory; private string? _operation; private string? _action; private bool? _throwOnFault; internal SoapProducerBuilder(string url) => _url = url ?? throw new ArgumentNullException(nameof(url)); /// References a registered . public SoapProducerBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } /// Operation name. public SoapProducerBuilder Operation(string operation) { _operation = operation; return this; } /// Explicit SOAPAction. public SoapProducerBuilder Action(string action) { _action = action; return this; } /// /// Whether a soap:Fault in the reply fails the exchange (default true). False returns the /// fault as the reply, with redbSoap.isFault, redbSoap.faultCode and /// redbSoap.faultString to branch on. /// public SoapProducerBuilder ThrowOnFault(bool value = true) { _throwOnFault = value; return this; } /// Builds the soap:// / soaps:// URI. public string Build() { string scheme = "soap", rest = _url; if (_url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { scheme = "soaps"; rest = _url["https://".Length..]; } else if (_url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { scheme = "soap"; rest = _url["http://".Length..]; } var sb = new StringBuilder(scheme).Append("://").Append(rest); var sep = rest.Contains('?') ? '&' : '?'; void Append(string key, string? value) { if (string.IsNullOrEmpty(value)) return; sb.Append(sep).Append(key).Append('=').Append(Uri.EscapeDataString(value)); sep = '&'; } Append("connectionFactory", _connectionFactory); Append("operation", _operation); Append("action", _action); if (_throwOnFault is { } tof) Append("throwOnFault", tof ? "true" : "false"); return sb.ToString(); } /// Allows passing the builder directly to To(). public static implicit operator string(SoapProducerBuilder builder) => builder.Build(); } /// Fluent builder for a SOAP consumer (receive endpoint) URI. public sealed class SoapConsumerBuilder { private readonly string _path; private string _host = "0.0.0.0"; private int _port; private int _maxConcurrentRequests; private int _requestQueueLimit; private int? _rejectStatusCode; private int? _retryAfterSeconds; private long? _maxRequestBodySize; private string? _connectionFactory; private bool _ssl; private string? _sslCertPath; private SoapClientCertificateMode _clientCertificateMode = SoapClientCertificateMode.NoCertificate; private string? _allowedClientThumbprints; private bool _emitHttpCompatHeaders; internal SoapConsumerBuilder(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); _path = path.StartsWith('/') ? path : "/" + path; } /// Bind host. public SoapConsumerBuilder Host(string host) { _host = host; return this; } /// Bind port. public SoapConsumerBuilder Port(int port) { _port = port; return this; } /// References a registered . public SoapConsumerBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } /// /// Serves the endpoint over TLS. The certificate path may be given here or left to the connection /// factory; the password belongs on the factory only, so it never becomes part of the route key. /// public SoapConsumerBuilder Ssl(string? certPath = null) { _ssl = true; _sslCertPath = certPath; return this; } /// Requires or allows a client certificate (mTLS). Only meaningful together with TLS. public SoapConsumerBuilder ClientCertificate( SoapClientCertificateMode mode, string? allowedThumbprints = null) { _clientCertificateMode = mode; _allowedClientThumbprints = allowedThumbprints; return this; } /// /// Also publishes the caller's address, path and method under redbHttp.*, so processors /// written against the HTTP transport work unchanged behind this endpoint. /// public SoapConsumerBuilder HttpCompatHeaders(bool enabled = true) { _emitHttpCompatHeaders = enabled; return this; } /// /// Admission limit: at most concurrent pipeline executions; overflow /// beyond the optional FIFO is shed with 429 + Retry-After before /// any envelope work. /// public SoapConsumerBuilder MaxConcurrentRequests(int max, int queue = 0) { _maxConcurrentRequests = max; _requestQueueLimit = queue; return this; } /// Status code for a shed request (default 429). public SoapConsumerBuilder RejectStatusCode(int statusCode) { _rejectStatusCode = statusCode; return this; } /// Retry-After value for a shed request in seconds; 0 = do not send (default 1). public SoapConsumerBuilder RetryAfterSeconds(int seconds) { _retryAfterSeconds = seconds; return this; } /// Upper bound on a request body in bytes, MTOM attachments included; 0 = no bound (default 100 MB). public SoapConsumerBuilder MaxRequestBodySize(long bytes) { _maxRequestBodySize = bytes; return this; } /// Builds the soap:/path?... (or soaps:) URI. public string Build() { // The scheme is what the component reads the TLS decision from, so TLS changes the scheme rather // than adding a parameter — the same spelling a hand-written URI uses. var sb = new StringBuilder(_ssl ? "soaps:" : "soap:").Append(_path); var sep = '?'; void Append(string key, string value) { sb.Append(sep).Append(key).Append('=').Append(Uri.EscapeDataString(value)); sep = '&'; } Append("host", _host); Append("port", _port.ToString(System.Globalization.CultureInfo.InvariantCulture)); if (!string.IsNullOrEmpty(_connectionFactory)) Append("connectionFactory", _connectionFactory); if (!string.IsNullOrEmpty(_sslCertPath)) Append("sslCertPath", _sslCertPath!); if (_clientCertificateMode != SoapClientCertificateMode.NoCertificate) Append("clientCertificateMode", _clientCertificateMode.ToString()); if (_emitHttpCompatHeaders) Append("emitHttpCompatHeaders", "true"); if (_maxConcurrentRequests > 0) Append("maxConcurrentRequests", _maxConcurrentRequests.ToString(System.Globalization.CultureInfo.InvariantCulture)); if (_requestQueueLimit > 0) Append("requestQueueLimit", _requestQueueLimit.ToString(System.Globalization.CultureInfo.InvariantCulture)); if (_rejectStatusCode is { } rsc) Append("rejectStatusCode", rsc.ToString(System.Globalization.CultureInfo.InvariantCulture)); if (_retryAfterSeconds is { } ras) Append("retryAfterSeconds", ras.ToString(System.Globalization.CultureInfo.InvariantCulture)); if (_maxRequestBodySize is { } mrb) Append("maxRequestBodySize", mrb.ToString(System.Globalization.CultureInfo.InvariantCulture)); if (!string.IsNullOrEmpty(_allowedClientThumbprints)) Append("allowedClientThumbprints", _allowedClientThumbprints!); return sb.ToString(); } /// Allows passing the builder directly to From(). public static implicit operator string(SoapConsumerBuilder builder) => builder.Build(); } Path: redb-route/redb.Route.Soap/README.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/README.md ---- # redb.Route.Soap > Documentation and articles: **SOAP / WSDL web-service transport for the [redb.Route](../redb.Route) ESB framework**, oriented to Apache Camel's `camel-cxf`. Call SOAP services and host SOAP endpoints as ordinary route steps — with the two SOAP header planes, SOAP 1.1 / 1.2, faults, WS-Security (UsernameToken + XML-Signature + XML-Encryption), MTOM attachments, and `?wsdl` publishing. Schemes: `soap` (HTTP), `soaps` (HTTPS). - **Call** (`.To(...)`) — wrap a payload in an envelope, POST it, parse the response, surface a `soap:Fault`. - **Host** (`.From(...)`) — run a SOAP endpoint on the shared Kestrel server; the route handles the request and its reply becomes the response envelope. - **Both directions**, **SOAP 1.1 and 1.2**, three camel-cxf **dataFormat** modes, **WS-Security**, **MTOM**. Everything is **in-box** — `HttpClient`, the shared `redb.Route.Http.Hosting` Kestrel host, and `System.Security.Cryptography.Xml` for WS-Security. No CoreWCF, no `System.ServiceModel` runtime, no vulnerable dependency. Interop is validated against an independent SOAP stack (Node.js `soap`) in both directions, plain and MTOM. --- ## Install & register ```csharp services.AddRedbRoute(route => { route.Services.AddRedbRouteSoap(); route.AddRouteBuilder(); }); ``` `AddRedbRouteSoap()` registers the `soap` / `soaps` schemes and shares one Kestrel receive server with every other HTTP-based connector in the process (via `redb.Route.Http.Hosting`). --- ## Quick start Every endpoint works two equivalent ways — a **fluent builder** or a plain **string URI**. Use whichever reads better; the fluent builder simply emits the string form under the hood. ```csharp // Call a service — fluent From("direct://get-fares") .To(Soap.Call("https://gds/air.svc").ConnectionFactory("amadeus").Operation("GetFares")); // Call a service — string URI (identical) From("direct://get-fares") .To("soaps://gds/air.svc?connectionFactory=amadeus&operation=GetFares"); // Host a SOAP endpoint — fluent From(Soap.Listen("/svc/orders").Host("0.0.0.0").Port(4090).ConnectionFactory("orders")) .Process(handle); // Host a SOAP endpoint — string URI (identical) From("soap:/svc/orders?host=0.0.0.0&port=4090&connectionFactory=orders") .Process(handle); ``` In the default **Payload** mode the message body is the XML of `` — send a fragment, receive a fragment. No code generation, works against any service. ## Endpoint URIs If you prefer raw strings (config files, `From`/`To` with a literal), here is the full grammar. **Producer** (`.To(...)`) — `soap://` for HTTP, `soaps://` for HTTPS; the host+path is the service address: ``` soap://{host}{/path}?connectionFactory={name}&operation={op}&action={soapAction} soaps://gds/air.svc?connectionFactory=amadeus&operation=GetFares ``` **Consumer** (`.From(...)`) — `soap:` plus the receive path; the host/port are query parameters: ``` soap:/{path}?host={bind}&port={port}&connectionFactory={name} soap:/svc/orders?host=0.0.0.0&port=4090&connectionFactory=orders ``` | Query parameter | Side | Meaning | |---|---|---| | `connectionFactory` | both | Name of the registered `SoapConnectionFactory`. | | `operation` | producer | Operation name / SOAPAction. | | `action` | producer | Explicit SOAPAction (overrides the factory default). | | `throwOnFault` | producer | Whether a `soap:Fault` reply fails the exchange (default `true`). | | `host` | consumer | Bind address (`0.0.0.0` for all interfaces). | | `port` | consumer | Listen port. | The `soaps` scheme (or an `https://` URL passed to `Soap.Call`) turns on TLS. Certificates, credentials, the SOAP version and the data format live on the `SoapConnectionFactory` (below), never in the URI. --- ## Service bindings — `SoapConnectionFactory` A binding is the WSDL/endpoint, version, data format, and WS-Security material. Register it **once** by name; routes reference it with `.ConnectionFactory("name")`, so certificates and credentials never live in a URI (the same pattern as AS2 / RabbitMQ). ```csharp context.AddToRegistry("amadeus", new SoapConnectionFactory { EndpointUrl = "https://gds/air.svc", SoapVersion = SoapVersion.Soap11, DataFormat = SoapDataFormat.Payload, DefaultAction = "urn:GetFares", // WS-Security (optional) SigningCert = ourPfx, // our cert + PRIVATE key — signs outgoing, decrypts incoming EncryptCert = partnerCer, // partner's PUBLIC cert — encrypts outgoing, verifies their signature Username = "svc", Password = "secret", // UsernameToken Mtom = true, // enable MTOM/XOP attachments Wsdl = "contracts/air.wsdl", // published on GET ?wsdl (consumer) }); ``` | Property | Role | |---|---| | `EndpointUrl` | Service URL to POST to (producer) / public address (consumer). | | `SoapVersion` | `Soap11` (default) or `Soap12`. Drives Content-Type and SOAPAction placement. | | `DataFormat` | `Payload` (default), `Message`, or `Pojo`. | | `DefaultAction` | SOAPAction used when the exchange carries no `redbSoap.action`. | | `SigningCert` | Our cert **with private key**: signs outgoing, decrypts incoming. | | `EncryptCert` | Partner's public cert: encrypts outgoing, **authenticates** their signature. | | `Username` / `Password` | WS-Security UsernameToken. `Password` is `[Sensitive]` (redacted in logs). | | `RequestType` / `ResponseType` | Pojo mode: CLR types for the request (consumer) / response (producer). | | `Mtom` | Send/receive binary attachments as `multipart/related`. | | `Wsdl` | File path or inline XML; a consumer serves it on `GET ?wsdl`. | --- ## dataFormat modes (camel-cxf parity) Set `SoapConnectionFactory.DataFormat`: ### `Payload` (default) The route body is the inner `` XML. Works with any service, no codegen. The producer wraps a fragment in an envelope; the consumer hands the route the Body payload and wraps the route's reply. ### `Message` — transparent proxy The route body is the **whole envelope**, in and out. The producer sends `In.Body` verbatim (no header injection, no auto-security — those are the route's own); the consumer hands the route the entire wire envelope and returns whatever envelope the route produced. Use it to inspect, log, or forward SOAP traffic untouched. ### `Pojo` — typed objects Typed request/response via `XmlSerializer` — the .NET analogue of camel-cxf's POJO mode over JAXB document/literal. DTOs are ordinary XML-serializable types and may be generated from a WSDL with `dotnet-svcutil`. ```csharp context.AddToRegistry("air", new SoapConnectionFactory { EndpointUrl = "https://gds/air.svc", DataFormat = SoapDataFormat.Pojo, ResponseType = typeof(GetFaresResponse), // producer: reply type }); From("direct://q") .Process(e => e.In.Body = new GetFaresRequest { Route = "JFK-LHR" }) .To(Soap.Call("https://gds/air.svc").ConnectionFactory("air")); // e.Out.Body is now a GetFaresResponse ``` On a consumer set `RequestType` (the inbound type the route receives); the route's reply object is serialized back. Override the producer's response type per message with the `redbSoap.responseType` header. --- ## Two header planes SOAP has two distinct header planes, and the connector keeps them apart: 1. **Transport HTTP headers** — `SOAPAction`, `Content-Type`. Handled internally. 2. **Envelope ``** — the SOAP header block. Each child element maps to a `redbSoap.header.` exchange header (in and out). Set one on the producer and it becomes a `` child; read them on the consumer. Connector metadata carries the `redbSoap.` prefix and is **stripped before the envelope goes out** (`SoapHeaders.IsRedbHeader`), so it never leaks onto the wire. | Header | Direction | Meaning | |---|---|---| | `redbSoap.action` | in/out | SOAPAction of the request/operation. | | `redbSoap.operation` | in | Local name of the Body payload's root element (route on it). | | `redbSoap.faultCode` / `redbSoap.faultString` | in/out | Fault code / reason. Inbound: a `soap:Fault` that arrived. Outbound on a consumer reply: send this fault instead of a normal response. | | `redbSoap.isFault` | in | Producer with `throwOnFault=false`: the reply is a fault. | | `redbSoap.username` / `redbSoap.password` | in | WS-Security UsernameToken, surfaced on the consumer. | | `redbSoap.signatureValid` | in | Whether an inbound Body signature verified (see WS-Security). | | `redbSoap.responseType` | out | Pojo mode: per-message response CLR `Type`. | | `redbSoap.header.*` | in/out | Envelope `` block elements (the second plane). | --- ## SOAP 1.1 vs 1.2 and faults `SoapVersion` drives the wire: - **1.1** — `text/xml` + a separate `SOAPAction` HTTP header; faults carry `faultcode` / `faultstring`. - **1.2** — `application/soap+xml` with the action folded into the Content-Type; faults carry `Code`/`Value` and `Reason`/`Text`. A fault response surfaces on `redbSoap.faultCode` / `redbSoap.faultString` and throws `SoapFaultException` from the producer. On the consumer, a route exception becomes a `soap:Fault` (HTTP 500 for 1.1, HTTP 200 for 1.2, per convention). Both fault shapes are parsed regardless of prefix (the parser is namespace-driven, so WCF `s:` and CXF `soapenv:` envelopes read the same). ### A fault that is an answer, not a failure "No such order" is what the service is *designed* to return, and it should not read as a broken route — counted as an error, copied into a dead-letter channel, shown as a failing route to whoever supervises it. Both directions have a way to say so, and both are explicit rather than inferred from the fault code: a Sender fault can be a bug in the route just as easily as a business answer, and only the author knows which. **Answering with a fault** — put the reason on the reply and return normally: ```csharp .Process(e => e.In.Headers[SoapHeaders.FaultString] = "No order with that number") // optional: e.In.Headers[SoapHeaders.FaultCode] = "wst:FailedAuthentication"; ``` The consumer sends a `soap:Fault` and the exchange stays successful. Without a code the fault is the sender's (`soap:Sender` / `soap:Client`): a refusal about the *content* of the request will refuse the same bytes again, while `Receiver` means "retry". Throwing `SoapFaultException` still works and still means a failure — an exception the route did not intend is exactly that. **Receiving a fault** — `throwOnFault=false` on the call: ```csharp .To(Soap.Call(url).ConnectionFactory("svc").Operation("GetFares").ThrowOnFault(false)) .Choice() .When(Header(SoapHeaders.IsFault).isEqualTo(true)).To("direct://no-fares") .Otherwise().To("direct://quote") ``` The fault comes back on `Out`, with `redbSoap.isFault`, `redbSoap.faultCode` and `redbSoap.faultString` to branch on. Default stays `true` — a fault fails the exchange, as before. Mirrors `throwOnError` on the HTTP producer. --- ## WS-Security All in-box via `System.Security.Cryptography.Xml`, configured with certificates/credentials on the `SoapConnectionFactory`. Certificate roles mirror AS2: - **`SigningCert`** — our cert with private key: **signs** outgoing bodies and **decrypts** incoming ones. - **`EncryptCert`** — the partner's public cert: **encrypts** outgoing bodies and **authenticates** their incoming signature. **UsernameToken** — set `Username` (+ `Password`) and the producer prepends a `` header; the consumer surfaces them on `redbSoap.username` / `redbSoap.password`. **XML-Signature** — with `SigningCert` set the producer signs the `` (Exclusive C14N, SHA-256, `wsu:Id` reference, embedded X.509). The consumer verifies and reports `redbSoap.signatureValid`: - When **`EncryptCert` is set**, verification is **authenticated**: the signer must be that exact partner certificate (thumbprint match) and the signature must cover the `` — a forged self-signed signature or a signature over a decoy element is rejected. - When it is **not set**, only cryptographic **integrity** against the embedded key is checked (the Body was not tampered), which does **not** establish who the sender is. **XML-Encryption** — with `EncryptCert` set the producer encrypts the `` to the partner; the consumer decrypts with its `SigningCert` private key. The wire is the **standard WSS layout** real stacks produce and expect: an `` (AES session key, RSA-OAEP-wrapped) in the `` header, joined by a `ReferenceList` to the `` (AES-256-CBC) in the Body. The order is **sign-then-encrypt** outbound and **decrypt-then-verify** inbound, and the producer applies the same to responses (symmetric). Decryption also reads the legacy inline layout. ```csharp context.AddToRegistry("secured", new SoapConnectionFactory { EndpointUrl = "https://partner/svc", SigningCert = ourPfx, // sign + decrypt EncryptCert = partnerCer, // encrypt + authenticate their signature }); ``` --- ## MTOM / attachments Set `Mtom = true`. Binary attachments travel as `multipart/related` + `xop:Include` and are the [message attachments](../README.md#attachments) (`exchange.In.Attachments`), as Camel's `AttachmentMessage`, so the Body contract is untouched and the same attachments can go on to `smtp:` or come from an upload. ```csharp var msg = new Message("" + ""); msg.Attachments.Add(new Attachment { Name = "doc-1", ContentId = "doc-1", ContentType = "application/pdf", Content = AttachmentContent.FromBytes(pdfBytes), }); await producer.Process(new Exchange(msg)); ``` - **Producer.** Sends every message attachment as a part addressed by its `Content-ID`, else by its name; the reply's MTOM parts become the attachments of the reply, which replace the request ones when the pipeline moves on (a reply without parts leaves the request attachments). - **Consumer.** Every non-root part of an inbound `multipart/related` becomes a message attachment named by its `Content-ID`, with its full `Content-Type`. To reply with attachments, the route changes them (for example `Attachments.Clear()` and `Add`); a reply that holds exactly the request attachments is sent without them, so the connector does not echo the caller's own files. - In an expression: `attachments.size`, `attachmentContent('doc-1')`, `attachments[0].contentId`. The MIME parser is line-anchored, so boundary-looking bytes inside a binary part never cause a mis-split. The `redbSoap.attachments` and `redbSoap.hasAttachments` headers and the `SoapAttachment` type are gone (see `UPGRADING.md`, "Mail and SOAP attachments are message attachments"). --- ## WSDL publishing Set `SoapConnectionFactory.Wsdl` to a file path or inline XML on a consumer and it is served on `GET {path}?wsdl`, with the `` location rewritten to the address the client actually reached you on (camel-cxf `?wsdl` parity). Without a WSDL, GET is not an allowed method on the endpoint. .NET Core has no runtime WSDL *import* (by design), so the WSDL is the authored — or `dotnet-svcutil`-derived — contract, not reflected from CLR types. Pair it with `Pojo` mode for typed request/response. --- ## Telemetry & statistics Spans on the `redb.Route` activity source (`AddSource("redb.Route")`), both with `rpc.system = soap` and `redb.route.endpoint`: - **Consumer.** One `Server` span per request, `soap receive`, over the whole request, the ones refused before the envelope is read included. Its parent is the host's ASP.NET Core span when the application instruments ASP.NET Core, otherwise the caller's `traceparent`; without one it is a root. The caller's baggage is back on it, and the route's spans are its children. As a 5xx against a 4xx: a Receiver/Server fault, thrown or declared on the reply, and any other failure of the route mark it an error, a cancellation included unless the caller went away; a malformed request or a Sender/Client fault is an answer to the caller and does not. Only a `Client` (SOAP 1.1) or `Sender` (SOAP 1.2) code counts as the caller's: any other code, `wst:FailedAuthentication` included, marks the span; in SOAP 1.2 a caller fault is `Sender` with a subcode. - **Producer.** One `Client` span per call, `soap {action}`, with `rpc.method` = the action; an error for a failed call or a `soap:Fault` reply. The request carries the context of this span. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. And `IEndpointStatistics` counters (`MessagesIn/Out`, `Errors`, bytes). `[Sensitive]` fields (the UsernameToken password) are redacted in logs and the TSAK dashboard, and endpoint URIs are sanitized. --- ## Fluent DSL ```csharp // Producer — builds "soaps://host/svc?connectionFactory=name&operation=GetFares" Soap.Call("https://host/svc") // http ⇒ soap, https ⇒ soaps .ConnectionFactory("name") .Operation("GetFares") // or .Action("urn:GetFares") // Consumer — builds "soap:/svc/path?host=0.0.0.0&port=4090&connectionFactory=name" Soap.Listen("/svc/path") .Host("0.0.0.0") .Port(4090) .ConnectionFactory("name") ``` Both builders implicitly convert to the endpoint URI (shown in the comments), so they drop straight into `.To(...)` / `.From(...)` — and you can pass that exact string yourself instead (see **Endpoint URIs**). --- ## Interop & boundaries **Validated** against independent stacks (zero shared code), gated `Category=Interop`; the harness is profile `soap` of the test stand `docker-compose.tests.yml`: - **Node.js `soap`** in both directions — our producer → their server, their client → our consumer — plain SOAP and MTOM (`SoapInteropTests`, `SoapMtomInteropTests`). - **Node.js `crypto` (OpenSSL)** decrypts our WSS-encrypted envelope end to end — RSA-OAEP key unwrap + AES-256-CBC — proving the encryption layout interoperates (`SoapEncryptionInteropTests`). Honest boundaries (documented in `../../docs/SOAP_CONNECTOR_PLAN.md`): - **Runtime WSDL import** is absent in .NET Core by design — use a static WSDL contract + Pojo types. - **WSDL generation from CLR types** (reflection, as CXF/CoreWCF) is not done — contract-first is the model. - **`CipherReference`** (external ciphertext) and non-OAEP key transport are not handled; UsernameToken `PasswordDigest` is treated as plaintext. Rare WS-* variants. Part of the redb.Route connector family. ## Request limits A request is bounded before the route sees it: | Parameter | Default | Description | |---|---|---| | `maxRequestBodySize` | 100 MB | Upper bound on the request body in bytes, MTOM attachments included; the HTTP server refuses a larger one. `0` = no bound. DSL: `.MaxRequestBodySize(bytes)` | The envelope is read through the core `SafeXml`: a DTD is refused, and the structure is checked while it is read, with the core's default limits (depth 256, 1024 attributes and 256 namespace declarations on an element). The check runs once before anything parses the request, and again after the body is decrypted, since anyone can encrypt for our certificate. A request over a limit is a `Client` (SOAP 1.1) or `Sender` (SOAP 1.2) fault that names the limit, and never reaches the route. The sender reads the service's answers with the same limits. ## Concurrency limits Kestrel executes as many handlers as requests arrive; without a limit a route has no ceiling. The admission limit caps concurrent pipeline executions per endpoint and sheds the overflow BEFORE any pipeline work (load shedding, not backpressure): | Parameter | Default | Description | |---|---|---| | `maxConcurrentRequests` | `0` (unlimited) | Max concurrent pipeline executions | | `requestQueueLimit` | `0` | Requests over the limit that WAIT (FIFO) instead of being rejected | | `rejectStatusCode` | `429` | Status for a shed request | | `retryAfterSeconds` | `1` | `Retry-After` header value; `0` = do not send | A shed request is answered before an exchange exists: it appears in the endpoint's `Rejected` counter, not in `MessagesIn` or `Errors`. The limit is strictly per endpoint — other routes on the same listener keep their own budget. For "slow down but do not drop" semantics use `.Threads(n)` in the route instead; the two compose (the limit sheds at the door, Threads paces inside). Path: redb-route/redb.Route.Soap/SoapBase64.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapBase64.cs ---- using System.Security.Cryptography.Xml; using System.Xml; using redb.Route.Serialization; namespace redb.Route.Soap; /// /// The base64 values of an XML Signature or XML Encryption element are XML Schema base64Binary, whose lexical /// space has no value with non-zero unused bits in its last character. .NET 11 refuses such a value inside /// and , .NET 10 decodes it; checking it before they run makes a /// SOAP endpoint refuse it on every runtime. /// internal static class SoapBase64 { private const string Base64Encoding = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"; private static readonly HashSet DsBase64 = new(StringComparer.Ordinal) { "DigestValue", "SignatureValue", "X509Certificate", "X509SKI", "X509CRL", "Modulus", "Exponent", "P", "Q", "G", "Y", "J", "Seed", "PgenCounter", "PGPKeyID", "PGPKeyPacket", "SPKISexp", }; private static readonly HashSet XencBase64 = new(StringComparer.Ordinal) { "CipherValue", "OAEPparams", "KA-Nonce" }; private static readonly HashSet WsseBase64 = new(StringComparer.Ordinal) { "BinarySecurityToken", "KeyIdentifier" }; /// /// The first base64 element under (itself included) whose value has non-zero unused bits, /// or null when there is none. /// public static XmlElement? FirstNonCanonical(XmlElement root) { if (IsNonCanonical(root)) return root; foreach (var node in root.GetElementsByTagName("*")) if (node is XmlElement element && IsNonCanonical(element)) return element; return null; } private static bool IsNonCanonical(XmlElement element) { var base64 = element.NamespaceURI switch { SignedXml.XmlDsigNamespaceUrl => DsBase64.Contains(element.LocalName), SoapEncryption.XmlEncNs => XencBase64.Contains(element.LocalName), SoapSecurity.WsseNs => WsseBase64.Contains(element.LocalName) && element.GetAttribute("EncodingType") is "" or Base64Encoding, _ => false, }; return base64 && Base64Text.HasUnusedBitsSet(element.InnerText); } } Path: redb-route/redb.Route.Soap/SoapComponent.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapComponent.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Http; namespace redb.Route.Soap; // ── Component ──────────────────────────────────────────────────────────────── /// /// SOAP / WSDL transport component (oriented to Apache Camel camel-cxf). Schemes: soap (HTTP) /// and soaps (HTTPS). Producer calls a service; consumer hosts a SOAP endpoint on the shared Kestrel /// host. Baseline is in-box (HttpClient + Http.Hosting + System.Security.Cryptography.Xml); typed WSDL (Pojo) /// and CoreWCF ?wsdl publishing are not part of it. /// public sealed class SoapComponent : ComponentBase { /// public override string Scheme => "soap"; /// HTTPS variant of the SOAP scheme. public override IReadOnlyList AlternateSchemes => ["soaps"]; /// Shared Kestrel host for the SOAP receive endpoint (set from DI; used by the consumer). public SharedHttpServerManager? ServerManager { get; set; } private readonly Lazy _ownServer = new(() => new SharedHttpServerManager()); /// /// The receive server. Resolution order: explicitly assigned → the context's DI singleton → a /// lazily-created own instance (standalone/test). The DI step matters for module hosts that add /// the component by scanning rather than through the extension method, so nothing ever assigns /// while the one shared manager sits in the container. /// internal SharedHttpServerManager Server => ServerManager ?? Context.Resolve() ?? _ownServer.Value; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new SoapEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Path = uri.Path; // The scheme carries the TLS decision: soaps ⇒ HTTPS. if (string.Equals(uri.Scheme, "soaps", StringComparison.OrdinalIgnoreCase)) options.UseTls = true; options.Validate(); return new SoapEndpoint(uri, this, options); } /// public override async ValueTask DisposeAsync() { if (_ownServer.IsValueCreated) await _ownServer.Value.DisposeAsync().ConfigureAwait(false); await base.DisposeAsync().ConfigureAwait(false); } } // ── Options ────────────────────────────────────────────────────────────────── /// Whether the consumer requires, allows, or ignores a client certificate (mTLS). public enum SoapClientCertificateMode { /// No client certificate is requested. Default. NoCertificate, /// A certificate is requested; the call proceeds when the client presents none. AllowCertificate, /// A certificate is required; the handshake fails without one. RequireCertificate, } /// Options for a SOAP endpoint. public sealed class SoapEndpointOptions : EndpointOptions { /// Path from the URI (producer host+path, or consumer receive path). public string Path { get; set; } = string.Empty; /// Name of the registered . [RegistryReference(typeof(SoapConnectionFactory))] public string? ConnectionFactory { get; set; } /// Operation name / SOAPAction override for a producer call. public string? Operation { get; set; } /// /// Whether a soap:Fault in the reply fails the exchange (default true). Set false when the /// fault is an answer the service is designed to give: the reply comes back on Out, the /// fault code and reason on redbSoap.faultCode / redbSoap.faultString, and /// redbSoap.isFault says which kind of reply arrived. Explicit rather than inferred from /// the fault code: a Sender fault can be a bug in the route just as easily as a business answer, /// and only the author knows which. Mirrors throwOnError on the HTTP producer. /// public bool ThrowOnFault { get; set; } = true; /// Explicit SOAPAction (overrides the factory default). public string? Action { get; set; } /// Consumer bind host. public string Host { get; set; } = "0.0.0.0"; /// Consumer bind port. public int Port { get; set; } /// HTTPS/TLS. Set automatically when the URI scheme is soaps. public bool UseTls { get; set; } /// /// Path to the PFX certificate the consumer serves TLS with. Required alongside /// unless a named supplies it. /// public string? SslCertPath { get; set; } /// Password for the PFX certificate. [Sensitive] public string? SslCertPassword { get; set; } /// Client-certificate policy (mTLS) for the consumer. Requires . public SoapClientCertificateMode ClientCertificateMode { get; set; } = SoapClientCertificateMode.NoCertificate; /// /// Comma-separated thumbprints of accepted client certificates. When set, a presented certificate /// whose thumbprint is not listed is rejected even if its chain validates. /// public string? AllowedClientThumbprints { get; set; } /// /// Also publish the caller's address, path and method under redbHttp.*, so processors written /// against the HTTP transport (rate limiting, lockout, device metadata) work unchanged behind a SOAP /// endpoint. Default: false — the connector's own redbSoap.* headers always carry the same /// facts, and writing into another transport's namespace should be asked for. /// public bool EmitHttpCompatHeaders { get; set; } // ── Admission limit (HTTP_CONCURRENCY_LIMITS_PLAN) ── /// /// Maximum concurrent executions of this consumer's pipeline. 0 (default) = unlimited. /// Overflow beyond the limit and is shed with /// before any pipeline work. /// public int MaxConcurrentRequests { get; set; } /// Requests over the limit that WAIT for a permit (FIFO). 0 (default) = reject immediately. public int RequestQueueLimit { get; set; } /// Status code for a shed request. Default 429 Too Many Requests. public int RejectStatusCode { get; set; } = 429; /// Value of the Retry-After header on a shed request; 0 = do not send it. Default 1. public int RetryAfterSeconds { get; set; } = 1; /// Default : 100 MB, room for MTOM attachments. public const long DefaultMaxRequestBodySize = 100L * 1024 * 1024; /// /// Upper bound on a request body in bytes, MTOM attachments included; a larger request is refused by the HTTP /// server before the consumer reads it. 0 = no bound. Default . /// public long MaxRequestBodySize { get; set; } = DefaultMaxRequestBodySize; /// public override void Validate() { // Minimal. Full fail-fast (version/operation/cert checks) lands with the producer/consumer. ConcurrencyLimitOptions.ValidateShape(MaxConcurrentRequests, RequestQueueLimit, RejectStatusCode, RetryAfterSeconds); if (MaxRequestBodySize < 0) throw new ArgumentOutOfRangeException(nameof(MaxRequestBodySize), MaxRequestBodySize, "SOAP maxRequestBodySize must not be negative."); } } // ── Endpoint ───────────────────────────────────────────────────────────────── /// SOAP endpoint. Producer calls a service; consumer hosts a receive endpoint. public sealed class SoapEndpoint : EndpointBase { private readonly SoapEndpointOptions _options; internal SoapEndpoint(EndpointUri uri, SoapComponent component, SoapEndpointOptions options) : base(uri, component, options) => _options = options; internal SoapEndpointOptions SoapOptions => _options; /// public override IProducer CreateProducer() => new SoapProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) => new SoapConsumer(this, processor, ((SoapComponent)Component).Server); } Path: redb-route/redb.Route.Soap/SoapConnectionFactory.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapConnectionFactory.cs ---- using System.Security.Cryptography.X509Certificates; using redb.Route.Core; namespace redb.Route.Soap; /// /// A SOAP service binding: WSDL/endpoint, version, data format, and WS-Security material. Registered once by /// name in the route registry and referenced by .ConnectionFactory("name"), so certificates and /// credentials never live in a URI (same pattern as AS2 / RabbitMQ). /// public sealed class SoapConnectionFactory { /// /// Optional WSDL: a file path or inline XML. A consumer publishes it on GET ?wsdl (address rewritten /// to the caller's URL). Not runtime-imported (.NET Core has no WSDL import) — it is the contract. /// public string? Wsdl { get; set; } /// Service endpoint URL to POST to (producer) or the public address (consumer). public string EndpointUrl { get; set; } = ""; /// SOAP version. Drives Content-Type and SOAPAction placement. public SoapVersion SoapVersion { get; set; } = SoapVersion.Soap11; /// How the route sees the message. Default . public SoapDataFormat DataFormat { get; set; } = SoapDataFormat.Payload; /// Default SOAPAction when the exchange does not carry redbSoap.action. public string? DefaultAction { get; set; } // ── Transport TLS (consumer: how the endpoint is served) ── /// /// Serve the receive endpoint over TLS. The scheme soaps says the same thing; this is here so a /// deployment can turn TLS on together with the certificate it needs, in one registered place. /// public bool Ssl { get; set; } /// Path to the PFX certificate served on the TLS handshake. public string? SslCertPath { get; set; } /// Password for (redacted in logs and the dashboard). [Sensitive] public string? SslCertPassword { get; set; } /// Client-certificate policy (mTLS) for the receive endpoint. public SoapClientCertificateMode ClientCertificateMode { get; set; } = SoapClientCertificateMode.NoCertificate; /// /// Comma-separated thumbprints of accepted client certificates. Chain validation stays Kestrel's job; /// this adds «and it must be one of ours», which is what pins a partner in a closed contour. /// public string? AllowedClientThumbprints { get; set; } // ── WS-Security (baseline: XML-Signature / XML-Encryption via System.Security.Cryptography.Xml) ── /// Our certificate with private key: signs outgoing, decrypts incoming. public X509Certificate2? SigningCert { get; set; } /// Partner's public certificate: encrypts outgoing, verifies their signature. public X509Certificate2? EncryptCert { get; set; } /// UsernameToken user. public string? Username { get; set; } /// UsernameToken password (redacted in logs and the dashboard). [Sensitive] public string? Password { get; set; } /// /// Use MTOM/XOP for binary attachments. When set, a producer sends the message attachments /// () as multipart/related and a consumer /// replies with them; a consumer always parses inbound multipart/related into message attachments /// regardless of this flag. /// public bool Mtom { get; set; } // ── Pojo dataFormat (typed serialization via XmlSerializer; DTOs may come from dotnet-svcutil) ── /// /// Pojo mode: the CLR type the inbound request body deserializes into on a consumer. XML-serializable /// (e.g. a dotnet-svcutil-generated DTO with [XmlRoot] matching the request element). /// public Type? RequestType { get; set; } /// /// Pojo mode: the CLR type the response body deserializes into on a producer (the reply object the route /// receives). Overridable per message via the redbSoap.responseType header. /// public Type? ResponseType { get; set; } } Path: redb-route/redb.Route.Soap/SoapConsumer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapConsumer.cs ---- using System.Diagnostics; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; using redb.Route.Http; using redb.Route.Telemetry; namespace redb.Route.Soap; /// /// SOAP consumer (baseline, in-box): hosts a SOAP receive endpoint on the shared Kestrel server. Parses the /// inbound envelope (version detected from Content-Type), delivers the <soap:Body> payload to /// the route, and returns a response envelope built from (request-reply). A route /// exception becomes a soap:Fault response. Records MessagesIn and opens a Server span. /// public sealed class SoapConsumer : IConsumer { private readonly SoapEndpoint _endpoint; private readonly IProcessor _processor; private readonly SharedHttpServerManager _server; private RouteRegistration? _registration; // Unregistering the route stops new requests; the ones already in the pipeline still have to // finish, and the listener stays up while another route holds the port. private readonly InflightDrainGuard _drain = new(); private ILogger? _logger; public IEndpoint Endpoint => _endpoint; internal SoapConsumer(SoapEndpoint endpoint, IProcessor processor, SharedHttpServerManager server) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _server = server ?? throw new ArgumentNullException(nameof(server)); } /// public async Task Start(CancellationToken ct = default) { _drain.Start(ct); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; var o = _endpoint.SoapOptions; var factory = ResolveFactory(); // Publish the WSDL on GET ?wsdl when the factory carries one (camel-cxf parity); POST-only otherwise. var methods = string.IsNullOrWhiteSpace(factory?.Wsdl) ? "POST" : "POST,GET"; // TLS material: the URI wins where it says something, the named factory fills the rest. That is // the point of the factory — a certificate password put in a URI travels into logs, telemetry and // the dashboard, because the URI is the route key and gets handled as an ordinary string. var ssl = o.UseTls || (factory?.Ssl ?? false); var certPath = o.SslCertPath ?? factory?.SslCertPath; var certPassword = o.SslCertPassword ?? factory?.SslCertPassword; var certMode = o.ClientCertificateMode != SoapClientCertificateMode.NoCertificate ? o.ClientCertificateMode : factory?.ClientCertificateMode ?? SoapClientCertificateMode.NoCertificate; var thumbprints = o.AllowedClientThumbprints ?? factory?.AllowedClientThumbprints; // Fail here rather than inside Kestrel: without a certificate the listener falls back to the // ASP.NET development certificate, which is present on a developer's machine and absent in // production. That turns a configuration mistake into either a service that silently serves a // certificate nobody trusts, or one that fails on a box with an error naming neither this route // nor TLS. if (ssl && string.IsNullOrWhiteSpace(certPath)) throw new InvalidOperationException( $"SOAP consumer on {o.Host}:{o.Port}{o.Path} is set to serve TLS but has no certificate. " + "Set sslCertPath on the endpoint URI, or SslCertPath on the connection factory it names."); if (certMode != SoapClientCertificateMode.NoCertificate && !ssl) throw new InvalidOperationException( $"SOAP consumer on {o.Host}:{o.Port}{o.Path} asks for client certificates without TLS. " + "A client certificate is presented during the TLS handshake, so there is nowhere to " + "present it — use the soaps scheme, or drop clientCertificateMode."); _registration = _server.RegisterRoute( o.Host, o.Port, o.Path, methods, HandleRequest, ssl, certPath, certPassword, corsOptions: null, // SOAP is not a browser transport maxRequestBodySize: o.MaxRequestBodySize, clientCertificateMode: MapClientCertificateMode(certMode), clientCertificateValidation: BuildThumbprintValidator(thumbprints), concurrencyLimit: ConcurrencyLimitOptions.FromEndpoint( o.MaxConcurrentRequests, o.RequestQueueLimit, o.RejectStatusCode, o.RetryAfterSeconds, onRejected: _endpoint.RecordRejected)); try { await _server.EnsureStarted(o.Host, o.Port, ct).ConfigureAwait(false); } catch { // The listener did not come up: the route leaves it, so a later Start registers once. await Stop(CancellationToken.None).ConfigureAwait(false); throw; } } private static Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode? MapClientCertificateMode( SoapClientCertificateMode mode) => mode switch { SoapClientCertificateMode.AllowCertificate => Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode.AllowCertificate, SoapClientCertificateMode.RequireCertificate => Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode.RequireCertificate, _ => null, }; /// /// Builds the allow-list check for client certificates. Chain validation is Kestrel's job; this adds /// "and it must be one of ours", which is what pins a partner in a service-to-service contour. /// private static Func? BuildThumbprintValidator(string? allowedThumbprints) { if (string.IsNullOrWhiteSpace(allowedThumbprints)) return null; var allowed = allowedThumbprints! .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Select(t => t.Replace(" ", string.Empty)) .ToHashSet(StringComparer.OrdinalIgnoreCase); return (cert, _, _) => allowed.Contains(cert.Thumbprint); } /// public async Task Stop(CancellationToken ct = default) { if (_registration is null) return; _server.UnregisterRoute(_registration); _registration = null; await _drain.DrainAsync(ct, _logger, $"soap://{_endpoint.SoapOptions.Host}:{_endpoint.SoapOptions.Port}{_endpoint.SoapOptions.Path}").ConfigureAwait(false); await _server.StopIfEmpty(_endpoint.SoapOptions.Host, _endpoint.SoapOptions.Port, ct).ConfigureAwait(false); } private async Task HandleRequest(HttpContext http) { // Counted for the drain: a call already inside the pipeline must finish before Stop returns, // even though the listener stays up for the other routes on this port. _drain.Increment(); // The server span of the request, over the whole of it, the refused ones too: the caller's trace goes on from // the host's span when ASP.NET Core instrumentation opened it, else from traceparent; without either it is a root. using var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, "soap receive", ActivityKind.Server, "rpc.system", "soap", _endpoint.Uri.NormalizedKey, http.Request.Headers, static (headers, name) => headers.TryGetValue(name, out var value) ? value.ToString() : null, InboundParent.HostRequest); try { await HandleRequestCore(http, span.Activity).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !http.RequestAborted.IsCancellationRequested) { // Only the caller going away is a stop; any other cancellation (a timeout inside the route) is a failure. span.Activity.RecordFailure(ex); throw; } finally { _drain.Decrement(); } } private async Task HandleRequestCore(HttpContext http, Activity? span) { // WSDL publishing: a GET serves the contract and never enters the SOAP pipeline. if (HttpMethods.IsGet(http.Request.Method)) { await ServeWsdl(http).ConfigureAwait(false); return; } byte[] reqBytes; using (var ms = new MemoryStream()) { await http.Request.Body.CopyToAsync(ms, http.RequestAborted).ConfigureAwait(false); reqBytes = ms.ToArray(); } var wireLen = reqBytes.Length; var factory = ResolveFactory(); var dataFormat = factory?.DataFormat ?? SoapDataFormat.Payload; var contentType = http.Request.ContentType; // Version up front — from the multipart start-info when MTOM — so an MTOM parse failure faults in the // right SOAP dialect rather than always defaulting to 1.1. var version = DetectVersion(SoapMultipart.IsMultipartRelated(contentType) ? SoapMultipart.StartInfo(contentType!) ?? "text/xml" : contentType); // Inbound MTOM/XOP (camel-cxf mtom-enabled parity): unwrap multipart/related into the root envelope // plus attachments, then continue as if a plain envelope had arrived. IReadOnlyList? inAttachments = null; if (SoapMultipart.IsMultipartRelated(contentType)) { try { var (rootBytes, atts) = SoapMultipart.Parse(reqBytes, contentType!); reqBytes = rootBytes; inAttachments = atts; } catch (Exception ex) { // The text stays: SoapMultipart throws our own messages about the caller's own multipart // framing, so it discloses nothing about this process and is the only thing that lets an // integrator find a missing boundary. What changes is the code — see WriteFault below. _endpoint.RecordError(ex); await WriteFault(http, version, $"Malformed MTOM request: {ex.Message}", SoapEnvelope.SenderCode(version)).ConfigureAwait(false); return; } } // Pipeline statistics (MessagesIn/BytesIn) are the core StatisticsProcessor's - the // ownership audit removed the double. Transport-level failures above stay recorded here. // The envelope is parsed several times below (decryption, the body, the signature, the headers): one // streaming pass over the structure first, so every later parse reads a bounded document. if (await RefusedOverLimits(http, version, reqBytes).ConfigureAwait(false)) return; // WS-Security decrypt: if the Body is encrypted and we hold the private key, decrypt first, // so signature verification and parsing below see the plaintext. Skipped in Message (transparent // proxy) mode — there the route receives the wire bytes verbatim. var decrypted = false; if (dataFormat != SoapDataFormat.Message && factory?.SigningCert is { HasPrivateKey: true } decKey) { try { var doc = SafeXml.LoadDocument(reqBytes); if (SoapEncryption.HasEncryptedData(doc)) { SoapEncryption.DecryptBody(doc, decKey); using var dms = new MemoryStream(); doc.Save(dms); reqBytes = dms.ToArray(); decrypted = true; } } catch (Exception ex) { // This one is different from the two parse failures around it, and the difference is not // style. CryptographicException describes OUR key and OUR configuration, not the caller's // bytes; and text that varies with the reason decryption failed is a decryption oracle. // WS-Security says so outright — a fault here "could be used as part of a denial of // service or cryptographic attack" — and gives exactly one code for every cause, // wsse:FailedCheck ("the signature or decryption was invalid"). One code, one sentence, // no gradations: an attacker learns nothing by varying the ciphertext. The exception goes // to the log, and the caller gets the request id to quote at us. _logger?.LogError(ex, "SOAP decryption failed for {Path} (request {RequestId})", http.Request.Path, http.TraceIdentifier); _endpoint.RecordError(ex); await WriteFault(http, version, $"Security check failed (ref: {http.TraceIdentifier}).", "wsse:FailedCheck").ConfigureAwait(false); return; } } // The plaintext came from the caller too: anyone can encrypt for our certificate. Its structure is checked // again before anything reads it. if (decrypted && await RefusedOverLimits(http, version, reqBytes).ConfigureAwait(false)) return; SoapParseResult parsed; try { parsed = SoapEnvelope.Parse(reqBytes, version); } catch (Exception ex) { // Message mode is a transparent proxy: hand the raw envelope to the route even if it has no // parseable , rather than faulting on the route's behalf. if (dataFormat == SoapDataFormat.Message) parsed = new SoapParseResult(false, null, null, string.Empty); else { // XmlException here reads "'<' is an unexpected token. Line 1, position 5." — a description // of the bytes the caller sent us, not of anything on this side. Stripping it would cost // an integrator the one clue that finds a BOM, a wrong encoding or a truncated stream, // and buy no secrecy: we would only be refusing to quote the caller their own input. _endpoint.RecordError(ex); await WriteFault(http, version, $"Malformed SOAP request: {ex.Message}", SoapEnvelope.SenderCode(version)).ConfigureAwait(false); return; } } // The message the route sees depends on dataFormat: MESSAGE = whole envelope, POJO = a deserialized // request object, PAYLOAD = the inner payload. The wrapper Content-Type is NOT leaked. object? bodyForRoute = dataFormat switch { SoapDataFormat.Message => System.Text.Encoding.UTF8.GetString(reqBytes), SoapDataFormat.Pojo when factory?.RequestType is { } reqType => SoapPojo.Deserialize(parsed.BodyXml, reqType), _ => parsed.BodyXml, }; var message = new Message(bodyForRoute) { ContentType = "text/xml" }; if (inAttachments is not null) { foreach (var attachment in inAttachments) message.Attachments.Add(attachment); } var action = ExtractAction(http.Request, version); if (!string.IsNullOrEmpty(action)) message.Headers[SoapHeaders.Action] = action; // WS-Security Body signature: verify when present, using the cert embedded in the signature. try { var doc = SafeXml.LoadDocument(reqBytes); // EncryptCert is the partner's known cert; when set, verification also authenticates the signer. if (SoapSignature.HasSignature(doc)) message.Headers[SoapHeaders.SignatureValid] = SoapSignature.VerifyBody(doc, factory?.EncryptCert, version); } catch { /* malformed signature — leave the flag unset */ } // Operation = local name of the Body payload's root element (so routes can branch on it). if (!string.IsNullOrWhiteSpace(parsed.BodyXml)) { try { message.Headers[SoapHeaders.Operation] = SafeXml.ParseElement(parsed.BodyXml).Name.LocalName; } catch { /* non-element body — no operation */ } } // Second header plane: envelope elements under redbSoap.header.* // Guarded: in Message mode the body may be non-XML (tolerated above), and ReadHeaders re-parses it. try { foreach (var h in SoapEnvelope.ReadHeaders(reqBytes, version)) { message.Headers[SoapHeaders.HeaderPrefix + h.Name.LocalName] = h.ToString(); // WS-Security UsernameToken → surface user/password for the route to authenticate. if (SoapSecurity.IsSecurityHeader(h) && SoapSecurity.ReadUsernameToken(h) is { } creds) { message.Headers[SoapHeaders.Username] = creds.Username; if (creds.Password is not null) message.Headers[SoapHeaders.Password] = creds.Password; } } } catch { /* non-XML / headerless body — no envelope header plane */ } SurfaceConnection(http, message, _endpoint.SoapOptions.EmitHttpCompatHeaders); var exchange = Exchange.Create(message, _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOut; ExchangePrincipal.Set(exchange, SharedHttpServerManager.GetResolvedPrincipal(http)); try { try { await _processor.Process(exchange, http.RequestAborted).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !http.RequestAborted.IsCancellationRequested) { exchange.Exception ??= ex; } if (exchange.Exception is not null && !exchange.ExceptionHandled) { // No RecordError: the core StatisticsProcessor saw the same exchange.Exception. // A route that threw SoapFaultException has already said what kind of failure this is. // Flattening it to soap:Server would leave the caller only prose to branch on, and prose // is not a contract: WS-Trust clients, for one, treat wst:FailedAuthentication and // wst:InvalidRequest as different outcomes. // FaultString, not Message: Exception.Message on a SoapFaultException is the composed // "SOAP fault: - " text, so using it would send the caller our rendering // of a fault instead of the reason the route actually gave. // Anything that is NOT a SoapFaultException is an unhandled failure, and its Message is // written by whoever threw it — a file path, a connection string, the name of an inner // service. That text never goes to the caller (BR-4); the fault carries the exchange id // to quote, and the core StatisticsProcessor keeps the exception for diagnostics. // A request that could not be BOUND is the caller's fault in SOAP's literal sense: // MalformedRequestException carries a message about the caller's own bytes (the // BR-4 rule allows exactly that class of text out), and the code must be Sender — // a Receiver fault is a retry hint, and these bytes will fail identically forever. if (exchange.Exception is MalformedRequestException malformed) { await WriteFault(http, version, malformed.Message, SoapEnvelope.SenderCode(version)) .ConfigureAwait(false); return; } var chosen = exchange.Exception as SoapFaultException; // As a 4xx against a 5xx: a Sender/Client fault the route chose is an answer to the caller, not a // failure; a Receiver/Server fault and any other exception is ours. if (!IsSenderFault(chosen?.FaultCode)) span.RecordFailure(exchange.Exception); await WriteFault( http, version, chosen?.FaultString ?? $"An unexpected error occurred while processing the request (ref: {exchange.ExchangeId}).", chosen?.FaultCode, chosen?.FaultCodeNamespace) .ConfigureAwait(false); return; } var outMsg = exchange.HasOut ? exchange.Out! : exchange.In; // A fault the route MEANT to send: it put the reason on the reply and returned normally, // so the exchange is a success and only the wire carries a fault. Throwing would have // worked too, but then a business answer ("no such order") would count as a route error, // fill a dead-letter channel and read as a broken route to whoever supervises it. Same // shape the HTTP consumer uses for a status code — the reply says what to send. if (outMsg.Headers.TryGetValue(SoapHeaders.FaultString, out var declared) && declared?.ToString() is { Length: > 0 } declaredReason) { // No code named: a refusal about the CONTENT of the request is Sender / Client. // Receiver would be a retry hint, and a deliberate refusal will refuse again. var declaredCode = outMsg.Headers.TryGetValue(SoapHeaders.FaultCode, out var dc) ? dc?.ToString() : null; var code = declaredCode ?? SoapEnvelope.SenderCode(version); // The same rule as a thrown fault: a Receiver/Server code is ours even when the route sent it on purpose. if (!IsSenderFault(code)) span?.SetStatus(ActivityStatusCode.Error, declaredReason); await WriteFault(http, version, declaredReason, code).ConfigureAwait(false); return; } byte[] respEnvelope; var respContentType = SoapEnvelope.ContentType(version, null); if (dataFormat == SoapDataFormat.Message) { // Transparent proxy: the route's reply is already a whole envelope — send it verbatim. respEnvelope = outMsg.Body is byte[] rb ? rb : System.Text.Encoding.UTF8.GetBytes(outMsg.Body?.ToString() ?? string.Empty); } else { // A byte[] reply is already-serialized XML (UTF-8), not an object to ToString(); decode it // rather than emitting "System.Byte[]". Pojo mode serializes a typed object; otherwise ToString(). var respBodyXml = outMsg.Body switch { byte[] b => System.Text.Encoding.UTF8.GetString(b), string s => s, null => string.Empty, var o when dataFormat == SoapDataFormat.Pojo => SoapPojo.Serialize(o), var o => o.ToString() ?? string.Empty, }; respEnvelope = SoapEnvelope.Build(respBodyXml, version); // WS-Security on the response, symmetric to the producer's request leg (sign-then-encrypt), so // the caller's decrypt/verify has something to act on. Only in Payload/Pojo (Message is verbatim). if (factory?.SigningCert is not null || factory?.EncryptCert is not null) { var sdoc = SafeXml.LoadDocument(respEnvelope); if (factory.SigningCert is { } signCert) SoapSignature.SignBody(sdoc, signCert, version); if (factory.EncryptCert is { } encCert) SoapEncryption.EncryptBody(sdoc, encCert, version); using var sms = new MemoryStream(); sdoc.Save(sms); respEnvelope = sms.ToArray(); } } // Outbound MTOM: package the reply with the message attachments the route set. A reply that still // holds exactly the request attachments is not packaged, so a route that never touches them does not // echo the caller's own files back. var outAttachments = outMsg.Attachments; if (factory?.Mtom == true && outAttachments.Count > 0 && !SameAttachments(outAttachments, inAttachments)) (respEnvelope, respContentType) = SoapMultipart.Write(respEnvelope, SoapEnvelope.ContentType(version, null), outAttachments); http.Response.ContentType = respContentType; await http.Response.Body.WriteAsync(respEnvelope, http.RequestAborted).ConfigureAwait(false); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } private SoapConnectionFactory? ResolveFactory() { var name = _endpoint.SoapOptions.ConnectionFactory; if (string.IsNullOrEmpty(name)) return null; // A set-but-unknown name fails loud -- never a silent fallback. return ((_endpoint.Component as ComponentBase)?.Context).GetRequiredFromRegistry(name); } /// /// Surfaces what the connection itself says: who called, and what the handshake proved about them. /// /// A route had no way to learn any of this before — not the caller's address, not their certificate. /// The address is what every IP-keyed protection keys on (rate limiting, brute-force lockout, audit /// of where a request came from), and its absence did not make those protections fail: they saw /// nothing and quietly did nothing, which is the worse of the two outcomes. /// /// private static void SurfaceConnection(HttpContext http, Message message, bool emitHttpCompat) { var remote = http.Connection.RemoteIpAddress; if (remote is not null) { var ip = remote.IsIPv4MappedToIPv6 ? remote.MapToIPv4().ToString() : remote.ToString(); message.Headers[SoapHeaders.RemoteAddress] = ip; message.Headers[SoapHeaders.RemotePort] = http.Connection.RemotePort; // Opt-in bridge for processors written against the HTTP transport, the same one the gRPC // consumer offers. Off by default: writing into another transport's namespace is a // deliberate act, not a side effect of choosing SOAP. if (emitHttpCompat) message.Headers["redbHttp.RemoteAddress"] = ip; } if (emitHttpCompat) { message.Headers["redbHttp.Path"] = http.Request.Path.Value ?? string.Empty; message.Headers["redbHttp.Method"] = http.Request.Method; } // mTLS: what the handshake proved about the caller. Chain and allow-list checks already ran in // Kestrel, so a certificate reaching here is one the listener accepted. var clientCert = http.Connection.ClientCertificate; if (clientCert is not null) { message.Headers[SoapHeaders.ClientCertThumbprint] = clientCert.Thumbprint; message.Headers[SoapHeaders.ClientCertSubject] = clientCert.Subject; message.Headers[SoapHeaders.ClientCertNotAfter] = clientCert.NotAfter.ToUniversalTime().ToString("O"); } } /// Serves the configured WSDL (address rewritten to the caller's URL), or 404 when none is set. private async Task ServeWsdl(HttpContext http) { var xml = SoapWsdl.Load(ResolveFactory()?.Wsdl); if (xml is null) { http.Response.StatusCode = StatusCodes.Status404NotFound; return; } var endpointUrl = $"{http.Request.Scheme}://{http.Request.Host}{http.Request.Path}"; http.Response.ContentType = "text/xml; charset=utf-8"; await http.Response.WriteAsync(SoapWsdl.RewriteAddress(xml, endpointUrl), http.RequestAborted).ConfigureAwait(false); } private static SoapVersion DetectVersion(string? contentType) => contentType is not null && contentType.Contains("application/soap+xml", StringComparison.OrdinalIgnoreCase) ? SoapVersion.Soap12 : SoapVersion.Soap11; /// True when the reply holds the very attachments the request brought, in the same order. private static bool SameAttachments(IReadOnlyList reply, IReadOnlyList? request) { if (request is null || reply.Count != request.Count) return false; for (var i = 0; i < reply.Count; i++) { if (!ReferenceEquals(reply[i], request[i])) return false; } return true; } private static string? ExtractAction(HttpRequest request, SoapVersion version) { if (version == SoapVersion.Soap11) return request.Headers.TryGetValue("SOAPAction", out var v) ? v.ToString().Trim('"') : null; // 1.2: action is a Content-Type parameter. Take the value up to the next ';' so it parses correctly // even when action is not the last parameter (e.g. "…; action=\"X\"; charset=utf-8"). var ct = request.ContentType ?? string.Empty; var idx = ct.IndexOf("action=", StringComparison.OrdinalIgnoreCase); if (idx < 0) return null; var rest = ct[(idx + "action=".Length)..]; var end = rest.IndexOf(';'); return (end < 0 ? rest : rest[..end]).Trim().Trim('"'); } /// /// Checks the structure of against and answers a /// request over a limit with a Sender fault that names the limit. Malformed XML is not answered here: the parse /// below answers it, or passes it on in Message mode. /// private async Task RefusedOverLimits(HttpContext http, SoapVersion version, byte[] envelope) { try { SafeXml.Check(envelope, XmlLimits.Default); return false; } catch (XmlLimitException ex) { _endpoint.RecordError(ex); await WriteFault(http, version, $"SOAP request refused: {ex.Message}", SoapEnvelope.SenderCode(version)).ConfigureAwait(false); return true; } catch (System.Xml.XmlException) { return false; } } /// /// Whether is the caller's fault: Client (SOAP 1.1) or Sender (SOAP 1.2), /// with or without a prefix. null is the default Receiver/Server code. /// private static bool IsSenderFault(string? faultCode) { if (string.IsNullOrEmpty(faultCode)) return false; var local = faultCode[(faultCode.LastIndexOf(':') + 1)..]; return local is "Client" or "Sender"; } private static async Task WriteFault( HttpContext http, SoapVersion version, string message, string? faultCode = null, string? faultCodeNamespace = null) { var fault = SoapEnvelope.BuildFault(message, version, faultCode, faultCodeNamespace); http.Response.StatusCode = version == SoapVersion.Soap12 ? 200 : 500; // 1.1 fault ⇒ HTTP 500 (SOAP convention) http.Response.ContentType = SoapEnvelope.ContentType(version, null); await http.Response.Body.WriteAsync(fault, http.RequestAborted).ConfigureAwait(false); } } Path: redb-route/redb.Route.Soap/SoapEncryption.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapEncryption.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.Xml; using System.Xml; namespace redb.Route.Soap; /// /// WS-Security XML-Encryption of the SOAP Body payload (in-box ), in the layout real /// WSS stacks (WCF, Apache CXF/WSS4J) produce and expect: the payload is encrypted with a per-message AES-256 /// key, the <xenc:EncryptedKey> (that key RSA-wrapped to the recipient) lives in the /// <wsse:Security> header and points at the <xenc:EncryptedData> in the Body through a /// <xenc:ReferenceList>/<xenc:DataReference>. Decryption also accepts the older inline /// layout (EncryptedKey nested in EncryptedData) for backward compatibility. Runs on the patched /// System.Security.Cryptography.Xml 9.0.18 (CVE-2026-50648 fixed). /// internal static class SoapEncryption { public const string XmlEncNs = "http://www.w3.org/2001/04/xmlenc#"; /// Encrypts the Body's payload element to the recipient's certificate (standard WSS layout). public static void EncryptBody(XmlDocument doc, X509Certificate2 recipientCert, SoapVersion version) { var soapNs = SoapEnvelope.Ns(version).NamespaceName; var body = (XmlElement)(doc.GetElementsByTagName("Body", soapNs)[0] ?? throw new InvalidOperationException("No to encrypt.")); // ALL child elements, not just the first: a document/literal Body can carry several, and encrypting // only the first would leak the rest in cleartext. They share one session key (standard WSS). var payloads = body.ChildNodes.OfType().ToList(); if (payloads.Count == 0) throw new InvalidOperationException("Empty — nothing to encrypt."); // 1. Fresh AES-256 session key, RSA-wrapped to the recipient (OAEP). The EncryptedKey's ReferenceList // points at every EncryptedData below. using var sessionKey = Aes.Create(); sessionKey.KeySize = 256; using var rsa = recipientCert.GetRSAPublicKey() ?? throw new InvalidOperationException("Recipient certificate has no RSA public key."); var wrappedKey = EncryptedXml.EncryptKey(sessionKey.Key, rsa, useOAEP: true); var encryptedKey = new EncryptedKey { EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSAOAEPUrl), CipherData = new CipherData(wrappedKey), }; encryptedKey.KeyInfo.AddClause(new KeyInfoX509Data(recipientCert)); // recipient hint // 2. Encrypt each Body child in place; reference each EncryptedData from the EncryptedKey. var encXml = new EncryptedXml(); foreach (var payload in payloads) { var cipher = encXml.EncryptData(payload, sessionKey, content: false); var edId = "ED-" + Guid.NewGuid().ToString("N"); var encryptedData = new EncryptedData { Type = EncryptedXml.XmlEncElementUrl, // whole element replaced Id = edId, EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url), CipherData = new CipherData(cipher), }; encryptedKey.AddReference(new DataReference("#" + edId)); EncryptedXml.ReplaceElement(payload, encryptedData, content: false); } // 3. Put the EncryptedKey in the Security header. var security = SoapSignature.EnsureSecurityHeader(doc, version); security.AppendChild(doc.ImportNode(encryptedKey.GetXml(), true)); } /// Whether the document carries an EncryptedData element. public static bool HasEncryptedData(XmlDocument doc) => doc.GetElementsByTagName("EncryptedData", XmlEncNs).Count > 0; /// /// Decrypts the Body payload in place using our private key. Accepts both the standard WSS layout /// (EncryptedKey in the Security header with a ReferenceList) and the legacy inline layout. /// public static void DecryptBody(XmlDocument doc, X509Certificate2 ourCertWithKey) { var encKeyEl = (XmlElement)(doc.GetElementsByTagName("EncryptedKey", XmlEncNs)[0] ?? throw new InvalidOperationException("No EncryptedKey to decrypt.")); RefuseNonCanonical(encKeyEl); var encKey = new EncryptedKey(); encKey.LoadXml(encKeyEl); using var rsa = ourCertWithKey.GetRSAPrivateKey() ?? throw new InvalidOperationException("Decryption certificate has no RSA private key."); var useOaep = encKey.EncryptionMethod?.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl; var sessionKey = EncryptedXml.DecryptKey(encKey.CipherData.CipherValue, rsa, useOaep); // Resolve the EncryptedData(s) the key references; fall back to every EncryptedData in the document. var targets = new List(); foreach (EncryptedReference reference in encKey.ReferenceList) if (reference.Uri is { Length: > 1 } uri && uri[0] == '#' && FindById(doc, uri[1..]) is { } el) targets.Add(el); if (targets.Count == 0) targets.AddRange(doc.GetElementsByTagName("EncryptedData", XmlEncNs).OfType()); foreach (var edEl in targets) RefuseNonCanonical(edEl); foreach (var edEl in targets) { var encData = new EncryptedData(); encData.LoadXml(edEl); using var alg = CreateSymmetric(encData.EncryptionMethod?.KeyAlgorithm); alg.Key = sessionKey; var eXml = new EncryptedXml(doc); var plain = eXml.DecryptData(encData, alg); eXml.ReplaceData(edEl, plain); } } /// base64Binary has one spelling: a value with non-zero unused bits is refused on every runtime before EncryptedXml decodes it. private static void RefuseNonCanonical(XmlElement element) { if (SoapBase64.FirstNonCanonical(element) is { } bad) throw new CryptographicException($"{bad.Name} is not canonical base64 (non-zero unused bits in its last character)."); } private static XmlElement? FindById(XmlDocument doc, string id) => doc.GetElementsByTagName("EncryptedData", XmlEncNs) .OfType() .FirstOrDefault(e => e.GetAttribute("Id") == id); private static SymmetricAlgorithm CreateSymmetric(string? algorithm) { var aes = Aes.Create(); aes.KeySize = algorithm switch { EncryptedXml.XmlEncAES128Url => 128, EncryptedXml.XmlEncAES192Url => 192, _ => 256, // AES-256 default (also our own EncryptBody) }; return aes; } } Path: redb-route/redb.Route.Soap/SoapEnvelope.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapEnvelope.cs ---- using System.Text; using System.Xml.Linq; using redb.Route.Core; namespace redb.Route.Soap; /// Result of parsing a SOAP envelope: the body payload, or a fault. internal readonly record struct SoapParseResult(bool IsFault, string? FaultCode, string? FaultString, string BodyXml); /// /// Builds and parses SOAP 1.1 / 1.2 envelopes with (in-box, no WCF). /// Payload mode: the exchange body is the content of <soap:Body>. Faults are detected for /// both versions (1.1 faultcode/faultstring, 1.2 Code/Reason). /// internal static class SoapEnvelope { public const string Ns11 = "http://schemas.xmlsoap.org/soap/envelope/"; public const string Ns12 = "http://www.w3.org/2003/05/soap-envelope"; public static XNamespace Ns(SoapVersion v) => v == SoapVersion.Soap12 ? Ns12 : Ns11; /// The HTTP Content-Type for the version (SOAPAction is folded into it for 1.2). public static string ContentType(SoapVersion v, string? action) => v == SoapVersion.Soap12 ? $"application/soap+xml; charset=utf-8{(string.IsNullOrEmpty(action) ? "" : $"; action=\"{action}\"")}" : "text/xml; charset=utf-8"; /// /// Wraps (an XML fragment) in an envelope. Optional /// becomes the <soap:Header> content. /// public static byte[] Build(string bodyXml, SoapVersion version, string? headerXml = null) { var soap = Ns(version); var body = new XElement(soap + "Body"); if (!string.IsNullOrWhiteSpace(bodyXml)) body.Add(ParseBodyContent(bodyXml)); var envelope = new XElement(soap + "Envelope", new XAttribute(XNamespace.Xmlns + "soap", soap.NamespaceName)); if (!string.IsNullOrWhiteSpace(headerXml)) envelope.Add(new XElement(soap + "Header", ParseFragments(headerXml!))); envelope.Add(body); var doc = new XDocument(new XDeclaration("1.0", "utf-8", null), envelope); using var ms = new MemoryStream(); using (var writer = System.Xml.XmlWriter.Create(ms, new System.Xml.XmlWriterSettings { Encoding = new UTF8Encoding(false), OmitXmlDeclaration = false })) doc.Save(writer); return ms.ToArray(); } /// Parses a response/request envelope into its body payload or a fault. public static SoapParseResult Parse(byte[] envelope, SoapVersion version) { var doc = SafeXml.Load(envelope); var soap = Ns(version); var body = doc.Root?.Element(soap + "Body") ?? throw new FormatException("SOAP envelope has no ."); var fault = body.Element(soap + "Fault"); if (fault is not null) { if (version == SoapVersion.Soap12) { var code = fault.Element(soap + "Code")?.Element(soap + "Value")?.Value; var reason = fault.Element(soap + "Reason")?.Element(soap + "Text")?.Value; return new SoapParseResult(true, code, reason, fault.ToString()); } // 1.1: faultcode / faultstring live in the empty namespace. var faultcode = fault.Element("faultcode")?.Value; var faultstring = fault.Element("faultstring")?.Value; return new SoapParseResult(true, faultcode, faultstring, fault.ToString()); } var payload = body.Elements().FirstOrDefault(); return new SoapParseResult(false, null, null, payload?.ToString() ?? string.Empty); } /// Extracts the <soap:Header> child elements (the envelope header plane), or empty. public static IEnumerable ReadHeaders(byte[] envelope, SoapVersion version) { var doc = SafeXml.Load(envelope); var soap = Ns(version); var header = doc.Root?.Element(soap + "Header"); return header?.Elements() ?? Enumerable.Empty(); } /// /// Namespaces for the prefixes a fault code is most likely to use, so a route naming a standard /// fault does not have to repeat the URI every time. A prefix that is not here, and whose namespace /// the route did not give, is written as it was handed over — the alternative would be inventing a /// namespace for it, and a wrong namespace is worse than an unresolved prefix. /// private static readonly Dictionary WellKnownFaultPrefixes = new(StringComparer.Ordinal) { ["wst"] = "http://docs.oasis-open.org/ws-sx/ws-trust/200512", ["wsse"] = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", ["wsu"] = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", ["wsa"] = "http://www.w3.org/2005/08/addressing", ["wsrm"] = "http://docs.oasis-open.org/ws-rx/wsrm/200702", }; /// /// The fault code for "the caller sent something we cannot process", spelled for this SOAP version: /// soap:Sender in 1.2, soap:Client in 1.1. /// /// This is not cosmetic. SOAP 1.2 defines the other value, Receiver (the 1.1 Server), /// as a failure "attributable to the processing of the message rather than to the contents of the /// message itself" — in practice a retry hint. A request we could not even parse is the opposite: /// the same bytes will fail again, so a caller that branches on the code (and a retry handler is /// exactly such a caller) must be told the fault is its own, or it will re-send until it gives up. /// /// public static string SenderCode(SoapVersion version) => version == SoapVersion.Soap12 ? "soap:Sender" : "soap:Client"; /// /// Builds a SOAP Fault envelope (for a consumer returning an error). /// /// A fault code is a QName in both SOAP versions, so a prefixed code such as /// wst:FailedAuthentication is only meaningful when the prefix is bound on the envelope. It is /// declared here for that reason: a code whose prefix nothing declares is not a code a strict client /// can resolve, and the clients that branch on fault codes are exactly the strict ones. /// /// /// /// Namespace for the prefix in . Optional: standard prefixes are known, /// and this is for a code in a namespace of the caller's own. /// public static byte[] BuildFault(string faultString, SoapVersion version, string? faultCode = null, string? faultCodeNamespace = null) { var soap = Ns(version); var code = faultCode ?? (version == SoapVersion.Soap12 ? "soap:Receiver" : "soap:Server"); XElement fault = version == SoapVersion.Soap12 ? new XElement(soap + "Fault", new XElement(soap + "Code", new XElement(soap + "Value", code)), new XElement(soap + "Reason", new XElement(soap + "Text", faultString))) : new XElement(soap + "Fault", new XElement("faultcode", code), new XElement("faultstring", faultString)); var envelope = new XElement(soap + "Envelope", new XAttribute(XNamespace.Xmlns + "soap", soap.NamespaceName), new XElement(soap + "Body", fault)); // The `soap` prefix is already bound above, so a soap:* code needs nothing further. if (ResolveFaultPrefix(code, faultCodeNamespace) is var (prefix, ns) && prefix is not null) envelope.Add(new XAttribute(XNamespace.Xmlns + prefix, ns!)); return Encoding.UTF8.GetBytes(new XDocument(envelope).ToString(SaveOptions.DisableFormatting)); } /// /// Works out which prefix a fault code uses and what to bind it to, or nothing when there is no /// prefix, when it is already bound, or when its namespace is unknown and was not supplied. /// private static (string? Prefix, string? Namespace) ResolveFaultPrefix(string code, string? supplied) { var colon = code.IndexOf(':'); if (colon <= 0) return (null, null); var prefix = code[..colon]; if (prefix == "soap") return (null, null); if (!string.IsNullOrEmpty(supplied)) return (prefix, supplied); return WellKnownFaultPrefixes.TryGetValue(prefix, out var ns) ? (prefix, ns) : (null, null); } private static object ParseBodyContent(string xml) { // The common case is a single Body child element; XElement.Parse also skips a leading XML prolog. try { return SafeXml.ParseElement(xml, LoadOptions.PreserveWhitespace); } // A document/literal body may legitimately carry several sibling elements — wrap-parse and add all. catch (System.Xml.XmlException) { return ParseFragments(xml).Cast().ToArray(); } } /// Parses one or more sibling XML elements (e.g. several <soap:Header> children). private static IEnumerable ParseFragments(string xml) { // Wrap so multiple top-level elements parse; each element carries its own inline xmlns. var wrapped = SafeXml.ParseElement($"{xml}", LoadOptions.PreserveWhitespace); return wrapped.Elements(); } } Path: redb-route/redb.Route.Soap/SoapFaultException.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapFaultException.cs ---- namespace redb.Route.Soap; /// /// Thrown when a SOAP call returns a soap:Fault. The fault code/string are also placed on the /// exchange under redbSoap.faultCode / redbSoap.faultString so OnException handlers /// (or a route that catches this) can react. /// public sealed class SoapFaultException : Exception { /// SOAP fault code (1.1 faultcode / 1.2 Code/Value). public string? FaultCode { get; } /// SOAP fault string (1.1 faultstring / 1.2 Reason/Text). public string? FaultString { get; } /// /// Namespace the prefix in stands for, when the code uses one the connector /// does not already know. A fault code is a QName, so an unbound prefix is not something a strict /// client can resolve — and the clients that branch on fault codes are the strict ones. /// public string? FaultCodeNamespace { get; } /// Creates a SOAP fault exception. /// /// Optional namespace for the prefix in . The standard prefixes /// (wst, wsse, wsu, wsa, …) are known and need not be given. /// public SoapFaultException(string? faultCode, string? faultString, string? faultCodeNamespace = null) : base($"SOAP fault: {faultCode} — {faultString}") { FaultCode = faultCode; FaultString = faultString; FaultCodeNamespace = faultCodeNamespace; } } Path: redb-route/redb.Route.Soap/SoapHeaders.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapHeaders.cs ---- namespace redb.Route.Soap; /// SOAP protocol version. public enum SoapVersion { /// SOAP 1.1: text/xml + a separate SOAPAction HTTP header. Soap11, /// SOAP 1.2: application/soap+xml with the action as a Content-Type parameter. Soap12 } /// How the route sees the SOAP message (Apache Camel camel-cxf dataFormat parity). public enum SoapDataFormat { /// The XML of the <soap:Body> content. Default; works with any service, no codegen. Payload, /// The whole SOAP envelope (transparent proxy). Message, /// Typed request/response objects via (DTOs may be dotnet-svcutil-generated). Pojo } /// /// Well-known exchange header keys for the SOAP component. Metadata with no standard wire name is /// redbSoap.-prefixed and stripped on send (), mirroring /// RmqHeaders/HttpHeaders. Envelope <soap:Header> elements map under /// — a second header plane distinct from the transport HTTP headers. /// public static class SoapHeaders { /// Prefix for redb-specific SOAP metadata headers. public const string Prefix = "redbSoap."; /// SOAPAction of the request/operation. public const string Action = "redbSoap.action"; /// Operation name. public const string Operation = "redbSoap.operation"; /// Target namespace. public const string Namespace = "redbSoap.namespace"; /// Fault code (SOAP 1.1 faultcode / 1.2 Code). public const string FaultCode = "redbSoap.faultCode"; /// Fault string (SOAP 1.1 faultstring / 1.2 Reason). /// /// On a consumer reply this header is also the instruction: set it, return normally, and the /// consumer answers with a soap:Fault carrying it, while the exchange stays successful — /// a fault the service is designed to give ("no such order") is an answer, not a failure. Use /// to name the code; without it the fault is the sender's, because a /// refusal about the content of the request is what SOAP calls Sender / Client. /// public const string FaultString = "redbSoap.faultString"; /// /// Set by the producer on a reply that is a fault (bool), so a route with /// throwOnFault=false can branch without catching. /// public const string IsFault = "redbSoap.isFault"; /// WS-Security UsernameToken user (surfaced on the consumer). public const string Username = "redbSoap.username"; /// WS-Security UsernameToken password (surfaced on the consumer). public const string Password = "redbSoap.password"; /// Whether an inbound WS-Security Body signature verified (bool). public const string SignatureValid = "redbSoap.signatureValid"; /// Caller's IP address, from the connection rather than from anything the caller sent. public const string RemoteAddress = "redbSoap.remoteAddress"; /// Caller's source port. public const string RemotePort = "redbSoap.remotePort"; /// Thumbprint of the TLS client certificate, when the handshake presented one (mTLS). public const string ClientCertThumbprint = "redbSoap.clientCertThumbprint"; /// Subject of the TLS client certificate. public const string ClientCertSubject = "redbSoap.clientCertSubject"; /// Expiry of the TLS client certificate, ISO-8601 UTC. public const string ClientCertNotAfter = "redbSoap.clientCertNotAfter"; /// Pojo mode: per-message override of the response CLR to deserialize into. public const string ResponseType = "redbSoap.responseType"; /// Prefix for individual <soap:Header> block elements (the envelope header plane). public const string HeaderPrefix = "redbSoap.header."; /// Whether the header key is redb-internal SOAP metadata (stripped before the envelope goes out). public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.Soap/SoapMultipart.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapMultipart.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Soap; /// /// MTOM/XOP wire packaging: a SOAP envelope plus binary attachments as a multipart/related body /// (RFC 2387 + the XOP spec). The root part is the envelope (declared application/xop+xml), each /// attachment is a MIME part addressed by Content-ID and referenced from the body via /// <xop:Include href="cid:..."/>. Hand-rolled (no MimeKit dependency) and scoped to the shapes /// real MTOM stacks emit. The delimiter search is line-anchored (RFC 2046: a boundary is CRLF--boundary /// at a line start) so boundary-looking bytes inside a binary part cannot cause a false split; the consumer /// parses regardless of transfer-encoding; the producer writes binary. /// internal static class SoapMultipart { public const string XopNs = "http://www.w3.org/2004/08/xop/include"; private const string RootCid = "root.message@redb.route"; private static readonly byte[] Crlf = { (byte)'\r', (byte)'\n' }; /// /// Wraps the envelope + attachments into a multipart/related body and returns the HTTP Content-Type. /// , when supplied, is added as an action parameter on the multipart /// Content-Type — the SOAP 1.2 way to carry the action once the envelope's own media type is hidden. /// public static (byte[] body, string contentType) Write( byte[] rootXml, string rootMediaType, IReadOnlyList attachments, string? action = null) { var boundary = "----=_redb_mtom_" + Guid.NewGuid().ToString("N"); var startInfo = MediaTypeBase(rootMediaType); // text/xml (1.1) or application/soap+xml (1.2) using var ms = new MemoryStream(); void Line(string s) { var b = Encoding.ASCII.GetBytes(s); ms.Write(b, 0, b.Length); ms.Write(Crlf, 0, 2); } // Root part: the SOAP envelope, declared as XOP. Line("--" + boundary); Line($"Content-Type: application/xop+xml; charset=UTF-8; type=\"{startInfo}\""); Line("Content-Transfer-Encoding: binary"); Line($"Content-ID: <{RootCid}>"); Line(string.Empty); ms.Write(rootXml, 0, rootXml.Length); ms.Write(Crlf, 0, 2); // Attachment parts, addressed by the attachment Content-ID, else its name. The id is bracketed exactly // once (a caller-supplied id may already carry them). foreach (var att in attachments) { Line("--" + boundary); Line($"Content-Type: {att.ContentType}"); Line("Content-Transfer-Encoding: binary"); Line($"Content-ID: <{StripBrackets(att.ContentId ?? att.Name)}>"); Line(string.Empty); using (var content = att.Content.OpenRead()) content.CopyTo(ms); ms.Write(Crlf, 0, 2); } Line("--" + boundary + "--"); var contentType = $"multipart/related; boundary=\"{boundary}\"; type=\"application/xop+xml\"; " + $"start=\"<{RootCid}>\"; start-info=\"{startInfo}\""; if (!string.IsNullOrEmpty(action)) contentType += $"; action=\"{action}\""; return (ms.ToArray(), contentType); } /// True when the HTTP Content-Type is a multipart/related (MTOM) envelope. public static bool IsMultipartRelated(string? contentType) => contentType is not null && contentType.Contains("multipart/related", StringComparison.OrdinalIgnoreCase); /// The start-info parameter (the inner SOAP media type) of a multipart/related Content-Type. public static string? StartInfo(string contentType) => Param(contentType, "start-info"); /// /// Parses a multipart/related body: returns the root part bytes (the SOAP envelope, per the start /// parameter, an application/xop+xml Content-Type, or the first part) and the other parts as message /// attachments, each named by its Content-ID. Throws when the boundary is missing /// or matches no part, rather than silently yielding an empty envelope. /// public static (byte[] root, IReadOnlyList attachments) Parse(byte[] body, string contentType) { var boundary = Param(contentType, "boundary") ?? throw new FormatException("multipart/related Content-Type has no boundary."); var startCid = StripBrackets(Param(contentType, "start")); var delimiter = Encoding.ASCII.GetBytes("--" + boundary); var rawParts = SplitParts(body, delimiter); if (rawParts.Count == 0) throw new FormatException($"multipart/related body has no parts for boundary '{boundary}'."); // Classify every part once, then pick the root by index — never by mutating the attachment list. var parsed = new (string cid, string type, byte[] content)[rawParts.Count]; var rootIndex = -1; for (var i = 0; i < rawParts.Count; i++) { var (headers, content) = SplitHeadersAndBody(rawParts[i]); var cid = StripBrackets(HeaderValue(headers, "Content-ID")) ?? string.Empty; var type = HeaderValue(headers, "Content-Type") ?? "application/octet-stream"; parsed[i] = (cid, type, content); var isRoot = type.Contains("application/xop+xml", StringComparison.OrdinalIgnoreCase) || (startCid is not null && cid == startCid); if (isRoot && rootIndex < 0) rootIndex = i; } if (rootIndex < 0) rootIndex = 0; // no explicit root marker: the first part is the SOAP envelope var attachments = new List(); for (var i = 0; i < parsed.Length; i++) { if (i == rootIndex) continue; var (cid, type, content) = parsed[i]; if (!string.IsNullOrEmpty(cid)) attachments.Add(new Attachment { Name = cid, ContentId = cid, ContentType = type, // the full Content-Type, parameters included Content = AttachmentContent.FromBytes(content), }); } return (parsed[rootIndex].content, attachments); } // ── byte-level MIME helpers ── private static List SplitParts(byte[] body, byte[] delimiter) { var parts = new List(); int idx = FindDelimiter(body, delimiter, 0); while (idx >= 0) { int partStart = idx + delimiter.Length; // A closing delimiter is followed by "--"; stop there. if (partStart + 1 < body.Length && body[partStart] == (byte)'-' && body[partStart + 1] == (byte)'-') break; // Skip the CRLF (or lone LF) after the delimiter. if (partStart < body.Length && body[partStart] == (byte)'\r') partStart++; if (partStart < body.Length && body[partStart] == (byte)'\n') partStart++; int next = FindDelimiter(body, delimiter, partStart); if (next < 0) break; // The content ends at the CRLF immediately before the next delimiter. int end = next; if (end >= 2 && body[end - 1] == (byte)'\n' && body[end - 2] == (byte)'\r') end -= 2; else if (end >= 1 && body[end - 1] == (byte)'\n') end -= 1; parts.Add(body[partStart..Math.Max(partStart, end)]); idx = next; } return parts; } /// /// Finds the next occurrence of --boundary that is line-anchored (at the start of the buffer or /// immediately after a LF), so identical bytes inside a binary part are not mistaken for a delimiter. /// private static int FindDelimiter(byte[] body, byte[] delimiter, int start) { int i = start; while ((i = IndexOf(body, delimiter, i)) >= 0) { if (i == 0 || body[i - 1] == (byte)'\n') return i; i += 1; // not at a line start — a coincidental match inside content; keep searching } return -1; } private static (string headers, byte[] body) SplitHeadersAndBody(byte[] part) { var sep = new byte[] { (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n' }; int i = IndexOf(part, sep, 0); if (i < 0) { // Tolerate bare-LF header separators. var sepLf = new byte[] { (byte)'\n', (byte)'\n' }; i = IndexOf(part, sepLf, 0); if (i < 0) return (HeaderText(part, 0, part.Length), Array.Empty()); return (HeaderText(part, 0, i), part[(i + 2)..]); } return (HeaderText(part, 0, i), part[(i + 4)..]); } // Latin1 maps every byte 1:1 to a char, so header bytes survive without the '?' substitution ASCII would apply. private static string HeaderText(byte[] buffer, int index, int count) => Encoding.Latin1.GetString(buffer, index, count); private static string? HeaderValue(string headers, string name) { foreach (var line in headers.Split('\n')) { var l = line.TrimEnd('\r'); int c = l.IndexOf(':'); if (c > 0 && l.AsSpan(0, c).Trim().Equals(name, StringComparison.OrdinalIgnoreCase)) return l[(c + 1)..].Trim(); } return null; } private static int IndexOf(byte[] haystack, byte[] needle, int start) { for (int i = start; i <= haystack.Length - needle.Length; i++) { int j = 0; while (j < needle.Length && haystack[i + j] == needle[j]) j++; if (j == needle.Length) return i; } return -1; } // ── Content-Type parameter helpers ── private static string MediaTypeBase(string contentType) { int semi = contentType.IndexOf(';'); return (semi < 0 ? contentType : contentType[..semi]).Trim(); } private static string? Param(string contentType, string name) { // Split on top-level ';' only — a quoted value may legally contain ';' (e.g. boundary="a;b" or // start-info="application/soap+xml; action=..."), so splitting inside quotes would corrupt it. int i = 0, n = contentType.Length; while (i < n) { int start = i; var inQuotes = false; while (i < n && (inQuotes || contentType[i] != ';')) { if (contentType[i] == '"') inQuotes = !inQuotes; i++; } var seg = contentType[start..i].Trim(); i++; // past the ';' int eq = seg.IndexOf('='); if (eq > 0 && seg.AsSpan(0, eq).Trim().Equals(name, StringComparison.OrdinalIgnoreCase)) { var value = seg[(eq + 1)..].Trim(); if (value.Length >= 2 && value[0] == '"' && value[^1] == '"') value = value[1..^1]; // one quote pair return value; } } return null; } private static string? StripBrackets(string? cid) => cid?.Trim().Trim('<', '>'); } Path: redb-route/redb.Route.Soap/SoapPojo.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapPojo.cs ---- using System.Collections.Concurrent; using System.Xml; using System.Xml.Serialization; namespace redb.Route.Soap; /// /// Pojo dataFormat: typed request/response bodies via — the .NET analogue of /// camel-cxf's POJO mode over JAXB document/literal. The body element the serializer emits becomes the /// <soap:Body> payload; the response payload deserializes into the configured CLR type. DTOs are /// ordinary XML-serializable types and may be generated from a WSDL with dotnet-svcutil. No WCF /// runtime and no vulnerable CoreWCF dependency. /// internal static class SoapPojo { // Weak per type: a type of an unloadable module (collectible load context) does not stay alive in this cache. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable Cache = new(); private static XmlSerializer For(Type t) => Cache.GetValue(t, static x => new XmlSerializer(x)); /// Serializes a CLR object to an XML fragment (no declaration) for embedding in the SOAP body. public static string Serialize(object body) { var ser = For(body.GetType()); // Suppress the xsi/xsd namespace noise XmlSerializer adds by default. var ns = new XmlSerializerNamespaces(); ns.Add(string.Empty, string.Empty); var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false }; using var sw = new StringWriter(); using (var xw = XmlWriter.Create(sw, settings)) ser.Serialize(xw, body, ns); return sw.ToString(); } /// Deserializes a SOAP body XML fragment into the given CLR type. public static object? Deserialize(string bodyXml, Type type) { if (string.IsNullOrWhiteSpace(bodyXml)) return null; var ser = For(type); using var sr = new StringReader(bodyXml); return ser.Deserialize(sr); } } Path: redb-route/redb.Route.Soap/SoapProducer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapProducer.cs ---- using System.Diagnostics; using System.Net.Http.Headers; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Soap; /// /// SOAP producer (baseline, in-box): wraps the exchange body in a 1.1/1.2 envelope, POSTs it with /// , and puts the response body on (request-reply). /// A soap:Fault surfaces on redbSoap.fault* and throws . /// Opens a Client telemetry span and records endpoint statistics, like every other connector. /// public sealed class SoapProducer : ConnectableProducer { private readonly SoapEndpoint _endpoint; private HttpClient? _http; internal SoapProducer(SoapEndpoint endpoint) => _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"soap:{EndpointUri.Sanitize(_endpoint.Uri.NormalizedKey)}"; /// protected override Task ConnectAsync(CancellationToken ct) { _http = new HttpClient(); return Task.CompletedTask; } /// protected override Task DisconnectAsync(CancellationToken ct) { _http?.Dispose(); _http = null; return Task.CompletedTask; } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); var factory = ResolveFactory(); var version = factory?.SoapVersion ?? SoapVersion.Soap11; var url = ResolveUrl(factory); var dataFormat = factory?.DataFormat ?? SoapDataFormat.Payload; var action = exchange.In.GetHeader(SoapHeaders.Action) ?? _endpoint.SoapOptions.Action ?? _endpoint.SoapOptions.Operation ?? factory?.DefaultAction; var httpContentType = SoapEnvelope.ContentType(version, action); byte[] envelope; if (dataFormat == SoapDataFormat.Message) { // MESSAGE dataFormat (camel-cxf parity): transparent proxy — the route supplies the whole // envelope, so we neither wrap it nor inject headers/security; those are the route's own. envelope = exchange.In.Body is byte[] raw ? raw : System.Text.Encoding.UTF8.GetBytes(exchange.In.Body is { } envelopeBody ? BodyText.Of(envelopeBody) : string.Empty); } else { // PAYLOAD / POJO dataFormat: build an envelope around the body fragment. var bodyXml = dataFormat == SoapDataFormat.Pojo && exchange.In.Body is not null and not string ? SoapPojo.Serialize(exchange.In.Body) // typed object ⇒ document/literal XML : exchange.In.Body is { } fragment ? BodyText.Of(fragment) : string.Empty; var headerXml = BuildHeaderBlock(exchange.In.Headers); // envelope plane // WS-Security UsernameToken: prepend a header when the factory supplies creds. if (!string.IsNullOrEmpty(factory?.Username)) headerXml = SoapSecurity.BuildUsernameTokenHeader(factory!.Username!, factory.Password) + (headerXml ?? string.Empty); envelope = SoapEnvelope.Build(bodyXml, version, headerXml); // WS-Security: sign with our cert, then encrypt to the partner's cert (sign-then-encrypt). if (factory?.SigningCert is not null || factory?.EncryptCert is not null) { var doc = SafeXml.LoadDocument(envelope); if (factory.SigningCert is { } signingCert) SoapSignature.SignBody(doc, signingCert, version); if (factory.EncryptCert is { } encryptCert) SoapEncryption.EncryptBody(doc, encryptCert, version); using var protectedMs = new MemoryStream(); doc.Save(protectedMs); envelope = protectedMs.ToArray(); } } // MTOM/XOP (camel-cxf mtom-enabled parity): wrap envelope + attachments as multipart/related. For // SOAP 1.2 the action rides on the multipart Content-Type (1.1 keeps its SOAPAction header below). var attachments = exchange.In.Attachments; if (factory?.Mtom == true && attachments.Count > 0) (envelope, httpContentType) = SoapMultipart.Write( envelope, SoapEnvelope.ContentType(version, action), attachments, version == SoapVersion.Soap12 ? action : null); // An RPC span: the operation is rpc.method; the URL and the SOAPAction are not messaging destinations. using var span = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"soap {action ?? "call"}", ActivityKind.Client, "rpc.system", "soap", _endpoint.Uri.NormalizedKey); if (span is { IsAllDataRequested: true } && !string.IsNullOrEmpty(action)) span.SetTag("rpc.method", action); // The envelope is what we SEND. It used to land in BytesIn because that was the only // byte counter the statistics surface had. _endpoint.RecordBytesOut(envelope.Length); var content = new ByteArrayContent(envelope); if (MediaTypeHeaderValue.TryParse(httpContentType, out var mt)) content.Headers.ContentType = mt; using var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = content }; if (version == SoapVersion.Soap11 && !string.IsNullOrEmpty(action)) request.Headers.TryAddWithoutValidation("SOAPAction", $"\"{action}\""); // The context of this call, written by the producer rather than left to HttpClient instrumentation the // application may not have. RouteTelemetryExtensions.InjectTraceContext(span, request, static (r, name, value) => { r.Headers.Remove(name); r.Headers.TryAddWithoutValidation(name, value); }); HttpResponseMessage sent; try { sent = await _http!.SendAsync(request, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Only our own token cancelling the call is a stop; an HttpClient timeout (a TaskCanceledException) failed. span.RecordFailure(ex); throw; } using var response = sent; var respBytes = await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false); // Inbound MTOM: unwrap multipart/related and surface the attachments on the reply. IReadOnlyList? respAttachments = null; if (SoapMultipart.IsMultipartRelated(response.Content.Headers.ContentType?.ToString())) { var (rootBytes, atts) = SoapMultipart.Parse(respBytes, response.Content.Headers.ContentType!.ToString()); respBytes = rootBytes; respAttachments = atts; } // Symmetric to the consumer: decrypt an encrypted response when we hold the private key, so parse // and signature-verify below see plaintext. Skipped in Message (transparent proxy) mode — there // the route must receive the response bytes verbatim, exactly as the consumer skips inbound decrypt. if (dataFormat != SoapDataFormat.Message && factory?.SigningCert is { HasPrivateKey: true } decKey) { try { var rdoc = SafeXml.LoadDocument(respBytes); if (SoapEncryption.HasEncryptedData(rdoc)) { SoapEncryption.DecryptBody(rdoc, decKey); using var rms = new MemoryStream(); rdoc.Save(rms); respBytes = rms.ToArray(); } } catch { /* leave as-is; parse below surfaces a fault if truly malformed */ } } var parsed = SoapEnvelope.Parse(respBytes, version); if (parsed.IsFault) { exchange.In.Headers[SoapHeaders.FaultCode] = parsed.FaultCode; exchange.In.Headers[SoapHeaders.FaultString] = parsed.FaultString; exchange.In.Headers[SoapHeaders.IsFault] = true; // A client span is an error for a fault either way: the call did not do what it asked. span?.SetStatus(ActivityStatusCode.Error, parsed.FaultString); // throwOnFault=false: the fault is an answer the service is designed to give, and the // route branches on the headers instead of catching. Explicit, never guessed from the // code inside the fault — the same rule the HTTP producer's throwOnError follows. if (_endpoint.SoapOptions.ThrowOnFault) { // The throw carries the fault into the core, which records the error once. throw new SoapFaultException(parsed.FaultCode, parsed.FaultString); } } exchange.Out = dataFormat switch { // MESSAGE: hand back the whole envelope. POJO: deserialize into the response type. PAYLOAD: body XML. SoapDataFormat.Message => new Message(System.Text.Encoding.UTF8.GetString(respBytes)) { ContentType = SoapEnvelope.ContentType(version, null) }, SoapDataFormat.Pojo when ResolveResponseType(exchange, factory) is { } rt => new Message(SoapPojo.Deserialize(parsed.BodyXml, rt)) { ContentType = "text/xml" }, _ => new Message(parsed.BodyXml) { ContentType = "text/xml" }, }; // Verify a response signature (authenticated when the partner cert is configured), like the consumer. // Not in Message mode: the route owns the verbatim envelope there. if (dataFormat != SoapDataFormat.Message) { try { var rdoc = SafeXml.LoadDocument(respBytes); if (SoapSignature.HasSignature(rdoc)) exchange.Out!.Headers[SoapHeaders.SignatureValid] = SoapSignature.VerifyBody(rdoc, factory?.EncryptCert, version); } catch { /* malformed signature — leave the flag unset */ } } // The reply attachments replace the request ones when the pipeline moves Out to In; a reply without // attachments leaves the request attachments on the message. if (respAttachments is not null) { foreach (var attachment in respAttachments) exchange.Out!.Attachments.Add(attachment); } // No catch/RecordError: exceptions fly into the core (ToProcessor / the template), // which records them against this endpoint (ownership audit). } private static Type? ResolveResponseType(IExchange exchange, SoapConnectionFactory? factory) => exchange.In.GetHeader(SoapHeaders.ResponseType) ?? factory?.ResponseType; /// /// Builds the <soap:Header> content from every redbSoap.header.* exchange header (the /// envelope header plane). Other redbSoap.* metadata is deliberately NOT put on the wire. /// private static string? BuildHeaderBlock(IDictionary headers) { System.Text.StringBuilder? sb = null; foreach (var (key, value) in headers) { if (value is null || !key.StartsWith(SoapHeaders.HeaderPrefix, StringComparison.OrdinalIgnoreCase)) continue; (sb ??= new System.Text.StringBuilder()).Append(value); } return sb?.ToString(); } private SoapConnectionFactory? ResolveFactory() { var name = _endpoint.SoapOptions.ConnectionFactory; if (string.IsNullOrEmpty(name)) return null; // A set-but-unknown name fails loud -- never a silent fallback. return ((_endpoint.Component as ComponentBase)?.Context).GetRequiredFromRegistry(name); } private string ResolveUrl(SoapConnectionFactory? factory) { if (!string.IsNullOrEmpty(factory?.EndpointUrl)) return factory!.EndpointUrl; // Reconstruct from the producer URI: soaps://host/path ⇒ https://host/path. var scheme = _endpoint.SoapOptions.UseTls ? "https" : "http"; return $"{scheme}://{_endpoint.SoapOptions.Path}"; } } Path: redb-route/redb.Route.Soap/SoapSecurity.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapSecurity.cs ---- using System.Xml.Linq; namespace redb.Route.Soap; /// /// WS-Security helpers: UsernameToken (pure XML, common and interoperable). XML-Signature and /// XML-Encryption of the envelope (BinarySecurityToken / EncryptedData, full WSS policy) are a /// dedicated effort validated against a real stack, using System.Security.Cryptography.Xml. /// internal static class SoapSecurity { public const string WsseNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; public const string PasswordTextType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"; /// Builds a <wsse:Security> header carrying a UsernameToken (as an XML string). public static string BuildUsernameTokenHeader(string username, string? password) { XNamespace wsse = WsseNs; var token = new XElement(wsse + "UsernameToken", new XElement(wsse + "Username", username)); if (password is not null) token.Add(new XElement(wsse + "Password", new XAttribute("Type", PasswordTextType), password)); var security = new XElement(wsse + "Security", new XAttribute(XNamespace.Xmlns + "wsse", WsseNs), token); return security.ToString(SaveOptions.DisableFormatting); } /// Extracts (username, password) from a <wsse:Security> element, or null if absent. public static (string Username, string? Password)? ReadUsernameToken(XElement security) { XNamespace wsse = WsseNs; var token = security.Element(wsse + "UsernameToken"); var user = token?.Element(wsse + "Username")?.Value; if (string.IsNullOrEmpty(user)) return null; var pass = token!.Element(wsse + "Password")?.Value; return (user, pass); } /// Whether an envelope header element is the <wsse:Security> element. public static bool IsSecurityHeader(XElement element) => element.Name.LocalName == "Security" && element.Name.NamespaceName == WsseNs; } Path: redb-route/redb.Route.Soap/SoapSignature.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapSignature.cs ---- using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.Xml; using System.Xml; namespace redb.Route.Soap; /// /// WS-Security XML-Signature over the SOAP Body, using in-box . The signature /// lands inside the <wsse:Security> header with an embedded X.509 certificate (KeyInfo). This is /// loopback-grade message signing; full WSS policy interop (STR references, exclusive-c14n inclusive prefixes, /// encryption) is validated against a real stack. /// internal static class SoapSignature { public const string WsuNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"; /// SignedXml that also resolves references to elements carrying a wsu:Id. private sealed class WssSignedXml : SignedXml { public WssSignedXml(XmlDocument document) : base(document) { } public override XmlElement? GetIdElement(XmlDocument document, string idValue) { var byId = base.GetIdElement(document, idValue); if (byId is not null) return byId; // idValue can come from an inbound signature's Reference URI — never interpolate quotes into XPath. if (idValue.IndexOfAny(new[] { '\'', '"' }) >= 0) return null; var nsm = new XmlNamespaceManager(document.NameTable); nsm.AddNamespace("wsu", WsuNs); return document.SelectSingleNode($"//*[@wsu:Id='{idValue}']", nsm) as XmlElement; } } /// Signs the SOAP Body and places the signature in the <wsse:Security> header. public static void SignBody(XmlDocument envelope, X509Certificate2 cert, SoapVersion version) { var soapNs = SoapEnvelope.Ns(version).NamespaceName; var body = (XmlElement)(envelope.GetElementsByTagName("Body", soapNs)[0] ?? throw new InvalidOperationException("No to sign.")); const string bodyId = "id-Body-1"; var wsuId = envelope.CreateAttribute("wsu", "Id", WsuNs); wsuId.Value = bodyId; body.SetAttributeNode(wsuId); using var key = cert.GetRSAPrivateKey() ?? throw new InvalidOperationException("Signing certificate has no RSA private key."); var signedXml = new WssSignedXml(envelope) { SigningKey = key }; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; var reference = new Reference("#" + bodyId); reference.AddTransform(new XmlDsigExcC14NTransform()); reference.DigestMethod = SignedXml.XmlDsigSHA256Url; signedXml.AddReference(reference); signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA256Url; var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); var signatureElement = signedXml.GetXml(); var security = EnsureSecurityHeader(envelope, version); security.AppendChild(envelope.ImportNode(signatureElement, true)); } /// Whether the envelope carries a ds:Signature. public static bool HasSignature(XmlDocument envelope) => envelope.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl).Count > 0; /// /// Verifies the Body signature. When is supplied (the partner's known /// certificate), the signer MUST be that certificate — this authenticates the sender. When it is null, /// only cryptographic integrity against the embedded key is checked (this does NOT authenticate the /// sender — any self-signed cert would pass). In both cases the signed reference MUST cover the /// <soap:Body>, defeating signature-wrapping where a decoy element is signed and the Body left /// unsigned. /// public static bool VerifyBody(XmlDocument envelope, X509Certificate2? expectedCert, SoapVersion version) { if (envelope.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl)[0] is not XmlElement sig) return false; // base64Binary has one spelling; refused on every runtime before SignedXml decodes it. if (SoapBase64.FirstNonCanonical(sig) is not null) return false; var signedXml = new WssSignedXml(envelope); signedXml.LoadXml(sig); bool cryptoOk; if (expectedCert is not null) { // Authenticated: the signing cert must be the expected partner cert, then verify with its key. var signer = SigningCertFrom(signedXml); if (signer is null || !string.Equals(signer.Thumbprint, expectedCert.Thumbprint, StringComparison.OrdinalIgnoreCase)) return false; cryptoOk = signedXml.CheckSignature(expectedCert, verifySignatureOnly: true); } else { // Integrity only, against the embedded key — does not establish who the sender is. cryptoOk = signedXml.CheckSignature(); } return cryptoOk && SignedReferenceCoversBody(signedXml, envelope, version); } /// The X.509 certificate embedded in the signature's KeyInfo, if any. private static X509Certificate2? SigningCertFrom(SignedXml signedXml) { if (signedXml.KeyInfo is null) return null; foreach (var clause in signedXml.KeyInfo) if (clause is KeyInfoX509Data x509 && x509.Certificates.Count > 0) return x509.Certificates[0] as X509Certificate2; return null; } /// True when a signed reference resolves to the <soap:Body> the processing path uses. private static bool SignedReferenceCoversBody(SignedXml signedXml, XmlDocument envelope, SoapVersion version) { var soapNs = SoapEnvelope.Ns(version).NamespaceName; // CRITICAL: resolve the Body the SAME way SoapEnvelope.Parse does — the Envelope's DIRECT-CHILD Body — // not GetElementsByTagName (document order, any depth). Otherwise an attacker can nest a genuinely // signed Body inside
(first in document order) so the anti-wrapping check passes, while Parse // hands the route a different, unsigned direct-child Body: an XML signature-wrapping bypass. Also // require exactly one direct-child Body, so a second/ambiguous Body cannot be smuggled in. if (envelope.DocumentElement is not { } env || env.LocalName != "Envelope" || env.NamespaceURI != soapNs) return false; XmlElement? body = null; var bodyCount = 0; foreach (var node in env.ChildNodes) if (node is XmlElement el && el.LocalName == "Body" && el.NamespaceURI == soapNs) { body ??= el; bodyCount++; } if (body is null || bodyCount != 1) return false; foreach (Reference r in signedXml.SignedInfo.References) { var uri = r.Uri; if (string.IsNullOrEmpty(uri) || uri[0] != '#') continue; if (ReferenceEquals(signedXml.GetIdElement(envelope, uri[1..]), body)) return true; } return false; } /// Returns the <wsse:Security> header element, creating the header/element if absent. internal static XmlElement EnsureSecurityHeader(XmlDocument envelope, SoapVersion version) { var soap = SoapEnvelope.Ns(version).NamespaceName; var existing = envelope.GetElementsByTagName("Security", SoapSecurity.WsseNs); if (existing.Count > 0) return (XmlElement)existing[0]!; var envelopeEl = (XmlElement)envelope.GetElementsByTagName("Envelope", soap)[0]!; var header = envelope.GetElementsByTagName("Header", soap).Count > 0 ? (XmlElement)envelope.GetElementsByTagName("Header", soap)[0]! : (XmlElement)envelopeEl.InsertBefore(envelope.CreateElement("soap", "Header", soap), envelopeEl.FirstChild)!; var security = envelope.CreateElement("wsse", "Security", SoapSecurity.WsseNs); header.AppendChild(security); return security; } } Path: redb-route/redb.Route.Soap/SoapWsdl.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Soap/SoapWsdl.cs ---- using System.Xml.Linq; using redb.Route.Core; namespace redb.Route.Soap; /// /// WSDL publishing for a SOAP consumer (camel-cxf ?wsdl parity). .NET Core has no runtime WSDL /// import (by design), but publishing a static contract is straightforward: a consumer whose /// is set serves it on GET …?wsdl, with the /// <soap:address> location rewritten to the address the client actually reached us on. The WSDL /// itself is authored (or dotnet-svcutil-derived), not generated from types — the honest boundary. /// internal static class SoapWsdl { /// Resolves the configured WSDL: inline XML as-is, otherwise a file path to read. public static string? Load(string? wsdlPathOrXml) { if (string.IsNullOrWhiteSpace(wsdlPathOrXml)) return null; var trimmed = wsdlPathOrXml.TrimStart(); if (trimmed.StartsWith('<')) return wsdlPathOrXml; // inline WSDL XML // Looks like a path: read it, or return null (⇒ 404) rather than serving a bogus path string as WSDL. return File.Exists(wsdlPathOrXml) ? File.ReadAllText(wsdlPathOrXml) : null; } /// /// Rewrites every <soap:address> / <soap12:address> location to /// so a client that fetched the WSDL posts back to the real address. /// Best-effort: malformed WSDL is returned unchanged. /// public static string RewriteAddress(string wsdlXml, string endpointUrl) { try { var doc = SafeXml.Parse(wsdlXml); var addresses = doc.Descendants() .Where(e => e.Name.LocalName == "address" && e.Name.NamespaceName.Contains("wsdl/soap", StringComparison.OrdinalIgnoreCase)) .ToList(); if (addresses.Count == 0) return wsdlXml; foreach (var addr in addresses) addr.SetAttributeValue("location", endpointUrl); return doc.Declaration is null ? doc.ToString() : doc.Declaration + Environment.NewLine + doc.ToString(); } catch { return wsdlXml; } } } Path: redb-route/redb.Route.Soap/redb.Route.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/redb.Route.Soap/redb.Route.Soap.csproj ---- redb.Route.Soap SOAP / WSDL web-service transport for the redb.Route ESB framework: call and host SOAP services with WS-Security, oriented to Apache Camel's camel-cxf. esb;soap;wsdl;webservice;ws-security;redb README.md