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