()).Which;
error.Code.Should().Be(As4ErrorCode.InvalidReceipt);
error.Message.Should().Contain("HTTP 403").And.Contain("text/html: \"403 Forbidden Forbidden
Request rejected, support ID 4711
");
}
[Fact]
public void Options_Validate_NonPositiveResponseLimit_Throws()
{
var act = () => new As4EndpointOptions { ConnectionFactory = "node", MaxResponseBodySize = 0 }.Validate();
act.Should().Throw();
}
[Fact]
public void Options_Validate_NonPositiveInFlightClaimTimeout_Throws()
{
var act = () => new As4EndpointOptions { ConnectionFactory = "node", InFlightClaimTimeout = 0 }.Validate();
act.Should().Throw().WithMessage("*inFlightClaimTimeout*");
}
[Fact]
public async Task Send_ReceiptEchoesOtherDigests_IsInvalidReceipt()
{
await using var fake = new FakePartner(Answer.WrongDigest);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var act = () => producer.Process(NewExchange());
var thrown = (await act.Should().ThrowAsync()).Which;
thrown.Code.Should().Be(As4ErrorCode.InvalidReceipt);
thrown.Detail.Should().Contain("non-repudiation");
}
[Fact]
public async Task Send_AnUnsignedReceipt_IsInvalidReceipt_NotAProofOfReceipt()
{
// The receipt names the right digests, but nobody signed it: anyone on the path could have written it.
await using var fake = new FakePartner(Answer.Unsigned);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var act = () => producer.Process(NewExchange());
(await act.Should().ThrowAsync()).Which.Code.Should().Be(As4ErrorCode.InvalidReceipt);
}
[Fact]
public async Task Send_ReceiptSignedByAStranger_IsInvalidReceipt()
{
await using var fake = new FakePartner(Answer.SignedByStranger);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var act = () => producer.Process(NewExchange());
var thrown = (await act.Should().ThrowAsync()).Which;
thrown.Code.Should().Be(As4ErrorCode.InvalidReceipt);
thrown.Detail.Should().Contain("signature");
}
[Fact]
public async Task Send_WithoutFourCornerProperties_IsRefusedBeforeSending()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" });
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync().WithMessage("*originalSender*");
fake.Received.Should().BeNull();
}
[Fact]
public async Task TA16_APing_IsAUserMessageForTheEbmsTestService()
{
// ebMS 3.0 Core §5.2.2: the test service and action; an agreement for them is all a ping needs.
const string testService = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/service";
const string testAction = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/test";
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port, p => { p.Service = testService; p.Action = testAction; });
await using var _ = context;
var exchange = NewExchange();
await producer.Process(exchange);
exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue();
var collaboration = fake.Received!.UserMessages.Single().CollaborationInfo;
collaboration.Service.Value.Should().Be(testService);
collaboration.Action.Should().Be(testAction);
}
[Fact]
public async Task TA18_Send_WithoutAConversationId_GeneratesOne_AndAGivenOneIsKept()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
await producer.Process(NewExchange());
fake.Received!.UserMessages.Single().CollaborationInfo.ConversationId.Should().NotBeNullOrWhiteSpace();
var given = NewExchange();
given.In.Headers[As4Headers.ConversationId] = "conversation-42";
await producer.Process(given);
fake.Received!.UserMessages.Single().CollaborationInfo.ConversationId.Should().Be("conversation-42");
}
[Fact]
public async Task Send_WithoutFourCornerProperties_IsSent_WhenTheAgreementDoesNotRequireThem()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port, p => p.RequireFourCornerProperties = false);
await using var _ = context;
var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" });
await producer.Process(exchange);
exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue();
fake.Received!.UserMessages.Single().MessageProperties.Should().BeEmpty();
}
[Fact]
public async Task Send_APropertyTypeHeader_SetsTheTypeOfThatProperty()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var exchange = NewExchange();
exchange.In.Headers[As4Headers.PropertyTypePrefix + "finalRecipient"] = "urn:example:type";
await producer.Process(exchange);
var properties = fake.Received!.UserMessages.Single().MessageProperties;
properties.Select(p => p.Name).Should().Equal("finalRecipient", "originalSender");
properties.Single(p => p.Name == "finalRecipient").Type.Should().Be("urn:example:type");
properties.Single(p => p.Name == "originalSender").Type.Should().BeNull();
}
[Fact]
public async Task Send_AListOfPayloads_KeepsTheirOrder_ContentIdsAndPartProperties()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var exchange = NewExchange();
exchange.In.Body = new List
{
new("xmlpayload@gitb", "application/xml", new MemoryStream(Encoding.UTF8.GetBytes("")),
new Dictionary { ["CharacterSet"] = "utf-8", ["MimeType"] = "ignored/ours" }),
new("custompayload@gitb", "application/octet-stream", new MemoryStream([1, 2, 3]), new Dictionary()),
new(null, "application/octet-stream", new MemoryStream([4, 5]), new Dictionary()),
};
await producer.Process(exchange);
exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue();
fake.Parts.Should().HaveCount(3);
fake.Parts[0].ContentId.Should().Be("xmlpayload@gitb");
fake.Parts[1].ContentId.Should().Be("custompayload@gitb");
fake.Parts[2].ContentId.Should().EndWith("@us.example");
Encoding.UTF8.GetString(fake.Parts[0].Content).Should().Be("");
fake.Parts[1].Content.Should().Equal(1, 2, 3);
fake.Parts[2].Content.Should().Equal(4, 5);
// The leading document: its own media type and character set, next to the compression the connector applied.
var leading = fake.Parts[0].Info;
leading.PropertyValue("MimeType").Should().Be("application/xml");
leading.PropertyValue("CompressionType").Should().Be("application/gzip");
leading.PropertyValue("CharacterSet").Should().Be("utf-8");
leading.Properties.Count(p => p.Name == "MimeType").Should().Be(1);
}
[Fact]
public async Task Send_AnEmptyPayloadList_IsASimpleSoapMessageWithoutPayloads()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var exchange = NewExchange();
exchange.In.Body = Array.Empty();
await producer.Process(exchange);
exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue();
fake.Parts.Should().BeEmpty();
fake.Received!.UserMessages.Single().PayloadInfo.Should().BeEmpty();
fake.WireContentType.Should().StartWith("application/soap+xml");
}
[Fact]
public async Task Send_ACharacterSetThatIsNotAnEncodingName_IsRefusedBeforeSending()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var exchange = NewExchange();
exchange.In.Body = new List
{
new(null, "application/xml", new MemoryStream([1]), new Dictionary { ["CharacterSet"] = "!utf*" }),
};
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync().WithMessage("*CharacterSet*!utf**");
fake.Received.Should().BeNull();
}
[Fact]
public async Task Send_TwoPayloadsWithTheSameContentId_IsRefusedBeforeSending()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var exchange = NewExchange();
exchange.In.Body = new List
{
new("same@gitb", "application/xml", new MemoryStream([1]), new Dictionary()),
new("same@gitb", "application/xml", new MemoryStream([2]), new Dictionary()),
};
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync().WithMessage("*same@gitb*");
fake.Received.Should().BeNull();
}
[Fact]
public async Task Send_WithOurSigningCertificateExpired_IsRefusedBeforeSending()
{
await using var fake = new FakePartner(Answer.Receipt);
var expired = As4TestMessages.KeyPair("CN=us.as4.test", DateTimeOffset.UtcNow.AddYears(-2), DateTimeOffset.UtcNow.AddDays(-1));
var (context, producer) = await Start(fake.Port, node: n => n.SigningCertificate = expired);
await using var _ = context;
var act = () => producer.Process(NewExchange());
await act.Should().ThrowAsync().WithMessage("*signing certificate*has expired*");
fake.Received.Should().BeNull();
}
[Fact]
public async Task Send_ToAPartnerWhoseEncryptionCertificateExpired_IsRefusedBeforeSending()
{
await using var fake = new FakePartner(Answer.Receipt);
var expired = As4TestMessages.PublicOnly(
As4TestMessages.KeyPair("CN=acme.as4.test", DateTimeOffset.UtcNow.AddYears(-2), DateTimeOffset.UtcNow.AddDays(-1)));
var (context, producer) = await Start(fake.Port, p => p.PartnerEncryptionCertificate = expired);
await using var _ = context;
var act = () => producer.Process(NewExchange());
await act.Should().ThrowAsync().WithMessage("*encryption certificate*has expired*");
fake.Received.Should().BeNull();
}
[Fact]
public async Task Send_OverridingTheActionWithoutPermission_IsRefused()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port);
await using var _ = context;
var exchange = NewExchange();
exchange.In.Headers[As4Headers.Action] = "Refund";
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync().WithMessage("*does not allow overriding the action*");
}
[Fact]
public async Task Send_WithRefToMessageId_UsesTheReplyLeg()
{
await using var fake = new FakePartner(Answer.Receipt);
var (context, producer) = await Start(fake.Port, p => p.ReplyLeg = new As4Leg { Service = "urn:example:reply", Action = "Confirm" });
await using var _ = context;
var exchange = NewExchange();
exchange.In.Headers[As4Headers.RefToMessageId] = "request-1@acme.example";
await producer.Process(exchange);
var user = fake.Received!.UserMessages.Single();
user.MessageInfo.RefToMessageId.Should().Be("request-1@acme.example");
user.CollaborationInfo.Service.Value.Should().Be("urn:example:reply");
user.CollaborationInfo.Action.Should().Be("Confirm");
}
// ── Fixtures ─────────────────────────────────────────────────────────────
private static Exchange NewExchange()
{
var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" });
exchange.In.Headers[As4Headers.OriginalSender] = "C1";
exchange.In.Headers[As4Headers.FinalRecipient] = "C4";
return exchange;
}
private static async Task<(RouteContext Context, As4Producer Producer)> Start(int port, Action? configure = null,
Action? node = null)
{
var context = NewContext(configure, node);
var producer = (As4Producer)context.GetEndpoint($"as4://127.0.0.1:{port}/as4?connectionFactory=node&partner=acme&timeout=15000").CreateProducer();
await producer.Start();
return (context, producer);
}
private static RouteContext NewContext(Action? configure = null, Action? node = null)
{
var context = new RouteContext();
context.AddComponent(new As4Component());
var partner = new As4Partner
{
Name = "acme",
PartyId = "urn:redb:acme",
Service = "urn:example",
Action = "Submit",
PartnerSigningCertificates = { As4TestMessages.PublicOnly(Partner) },
PartnerEncryptionCertificate = As4TestMessages.PublicOnly(Partner),
};
configure?.Invoke(partner);
var factory = new As4ConnectionFactory
{
OurPartyId = "urn:redb:us",
ExternalHostName = "us.example",
SigningCertificate = Us,
DecryptionCertificates = { Us },
Partners = { partner },
};
node?.Invoke(factory);
context.AddToRegistry("node", factory);
return context;
}
///
/// A loopback AS4 partner answering one way or another — request by request, the last answer repeating;
/// it records what it received.
///
private sealed class FakePartner : IAsyncDisposable
{
private readonly HttpListener _listener = new();
private readonly Answer[] _answers;
private readonly Task _loop;
public FakePartner(params Answer[] answers)
{
_answers = answers;
Port = global::redb.Route.Tests.Shared.TestPorts.Next();
_listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
_listener.Start();
_loop = Task.Run(ServeAsync);
}
public int Port { get; }
public EbmsMessaging? Received { get; private set; }
/// The envelope of the last request, decrypted.
public System.Xml.XmlDocument? Envelope { get; private set; }
public byte[]? Payload { get; private set; }
/// The payloads of the last request in the order of eb:PartInfo, decrypted and decompressed.
public List<(string ContentId, PartInfo Info, byte[] Content)> Parts { get; private set; } = [];
/// Content-Type of the last request as it came on the wire.
public string? WireContentType { get; private set; }
/// Path and query of the last request.
public string? RequestPathAndQuery { get; private set; }
/// MessageId of every user message received, in order.
public List ReceivedIds { get; } = [];
/// SHA-256 of every raw request body, in order: a retransmission is the same bytes.
public List RequestHashes { get; } = [];
private async Task ServeAsync()
{
while (_listener.IsListening)
{
HttpListenerContext http;
try { http = await _listener.GetContextAsync(); }
catch (HttpListenerException) { return; } // listener stopped
catch (ObjectDisposedException) { return; } // listener disposed
catch (ArgumentException) when (!_listener.IsListening) { return; } // stopped before the first wait (net10: invalid handle)
using var body = new MemoryStream();
await http.Request.InputStream.CopyToAsync(body);
RequestHashes.Add(Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(body.ToArray())));
var request = SwaMessage.Read(http.Request.ContentType!, body.ToArray(), 1024 * 1024);
As4SecurityEngine.Decrypt(request, [Partner]);
var verification = As4SecurityEngine.Verify(request, [As4TestMessages.PublicOnly(Us)], TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow);
Received = MessagingReader.Read(request.Envelope);
Envelope = request.Envelope;
Parts = Received.UserMessages.Single().PayloadInfo
.Select(info =>
{
var id = Uri.UnescapeDataString(info.Href!["cid:".Length..]);
return (id, info, As4TestMessages.Gunzip(request.Parts[id].ToArray()));
})
.ToList();
WireContentType = http.Request.ContentType;
RequestPathAndQuery = http.Request.Url!.PathAndQuery;
Payload = Parts.Count == 1 ? Parts[0].Content : null;
var messageId = Received.UserMessages.Single().MessageInfo.MessageId;
var mode = _answers[Math.Min(ReceivedIds.Count, _answers.Length - 1)];
ReceivedIds.Add(messageId);
if (mode == Answer.Huge)
{
// A proxy error page of no known length: chunked, far over any receipt.
http.Response.StatusCode = 200;
http.Response.ContentType = "text/html";
http.Response.SendChunked = true;
var junk = new byte[1 << 20];
try
{
for (var i = 0; i < 20; i++) await http.Response.OutputStream.WriteAsync(junk);
}
catch (Exception e) when (e is HttpListenerException or ObjectDisposedException or IOException) { } // the sender stops reading at its limit; the listener may be stopping
// The test may dispose the listener between the check and the call: Abort then throws ObjectDisposedException.
try { if (_listener.IsListening) http.Response.Abort(); }
catch (ObjectDisposedException) { } // the listener stopped: nothing left to abort
continue;
}
if (mode == Answer.Late)
continue; // never answers; the listener aborts it on dispose
if (mode == Answer.Nothing)
{
http.Response.StatusCode = 202;
http.Response.Close();
continue;
}
if (mode == Answer.Forbidden)
{
// A gateway's refusal page in front of the partner's access point.
var page = System.Text.Encoding.UTF8.GetBytes(
"403 Forbidden\r\nForbidden
\r\nRequest rejected, support ID 4711
\r\n
");
http.Response.StatusCode = 403;
http.Response.ContentType = "text/html; charset=utf-8";
await http.Response.OutputStream.WriteAsync(page);
http.Response.Close();
continue;
}
var info = new MessageInfo(DateTimeOffset.UtcNow, MessageIdFactory.New("acme.example"), messageId);
SignalMessage signal = mode switch
{
Answer.Error => new SignalMessage(info, null,
[new EbmsError("EBMS:0010", As4ErrorSeverity.Failure, "Processing", "ebms", messageId, "ProcessingModeMismatch", null, "no P-Mode")],
null),
// The receipt taken out of the signal, as the conformance test driver simulates a lost one.
Answer.ReceiptTakenOut => new SignalMessage(info, null, [], null),
_ => new SignalMessage(info, Receipts.NonRepudiation(mode == Answer.WrongDigest ? Tampered(verification.References) : verification.References), [], null),
};
var answer = SwaMessage.Create(MessagingWriter.CreateEnvelope(signal));
if (mode != Answer.Unsigned)
As4SecurityEngine.Sign(answer, mode == Answer.SignedByStranger ? Stranger : Partner,
As4KeyReference.BinarySecurityToken, timestampTtl: null, DateTimeOffset.UtcNow);
var (contentType, bytes) = answer.Write();
http.Response.StatusCode = 200;
http.Response.ContentType = contentType;
await http.Response.OutputStream.WriteAsync(bytes);
http.Response.Close();
}
}
private static IReadOnlyList Tampered(IReadOnlyList references)
{
var copies = references.Select(r => (System.Xml.XmlElement)r.CloneNode(deep: true)).ToList();
copies[0].GetElementsByTagName("DigestValue", WsSecurityNames.Ds)[0]!.InnerText = Convert.ToBase64String(new byte[32]);
return copies;
}
public async ValueTask DisposeAsync()
{
_listener.Stop();
_listener.Close();
await _loop.ConfigureAwait(false);
}
}
}
/// A stream that reads forward only, as a network body does, and records whether it was closed.
internal sealed class ForwardOnlyStream(byte[] content) : Stream
{
private readonly MemoryStream _inner = new(content, writable: false);
public bool Disposed { get; private set; }
public override bool CanRead => !Disposed;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override int Read(byte[] buffer, int offset, int count) => _inner.Read(buffer, offset, count);
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
Disposed = true;
base.Dispose(disposing);
}
}
Path: redb-route/tests/redb.Route.Tests.As4/As4RestartTests.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.As4/As4RestartTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.As4;
using redb.Route.As4.Messaging;
using redb.Route.As4.Mime;
using redb.Route.As4.Security;
using redb.Route.Components;
using redb.Route.Core;
using redb.Route.Processors;
using As4Dsl = redb.Route.As4.Fluent.As4;
namespace redb.Route.Tests.As4;
///
/// An AS4 consumer and producer keep working after Stop() and Start() of the same route context (issue
/// redb-route #12: a component keeps its endpoints for the life of the context, so a stop must not close for good what
/// the next start needs). The stop gives the listener path back to the shared server, the start registers it again on
/// the cached endpoint; the duplicate store lives in the registry and still knows the messages taken before the stop;
/// a spooled body is written and read on both runs. AS4 has no pending-receipt table and no pull queue to outlive a
/// stop: the receipt is the HTTP response of the same request, and a pull request is answered EBMS:0010.
///
public class As4RestartTests
{
private const string Payload = "10";
private static readonly X509Certificate2 NodeA = As4TestMessages.KeyPair("CN=a.restart.as4.test");
private static readonly X509Certificate2 NodeB = As4TestMessages.KeyPair("CN=b.restart.as4.test");
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Consumer_and_producer_work_after_the_context_is_stopped_and_started_again(bool streamBody)
{
var port = global::redb.Route.Tests.Shared.TestPorts.Next();
await using var context = new RouteContext();
context.AddComponent(new As4Component());
context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository());
context.AddToRegistry("b", Node("b", NodeB, Partner("a", NodeA)));
context.AddToRegistry("a", Node("a", NodeA, Partner("b", NodeB)));
var delivered = new List<(string MessageId, string Body)>();
var receive = As4Dsl.Receive("/as4/in").Host("127.0.0.1").Port(port).ConnectionFactory("b").IdempotentRepository("dedup");
if (streamBody) receive.StreamBody();
var receiveUri = receive.Build();
context.AddRoutes(r => r.From(receiveUri).RouteId("as4-in")
.Process(async (e, ct) =>
{
// A streamed body comes from the spool: it is read here, inside the exchange, as a route reads it.
var body = e.In.Body is Stream stream
? await new StreamReader(stream, Encoding.UTF8).ReadToEndAsync(ct)
: Encoding.UTF8.GetString((byte[])e.In.Body!);
lock (delivered) delivered.Add((e.In.GetHeader(As4Headers.MessageId)!, body));
}));
context.AddRoutes(r => r.From("direct://send").RouteId("as4-out")
.To(As4Dsl.Send($"http://127.0.0.1:{port}/as4/in").ConnectionFactory("a").Partner("b").Timeout(15000)));
async Task SendAsync()
{
var producer = context.GetEndpoint("direct://send").CreateProducer();
await producer.Start();
var exchange = NewExchange();
await producer.Process(exchange);
exchange.Exception.Should().BeNull("the message goes out and its receipt comes back on every run");
(exchange.Out ?? exchange.In).GetHeader(As4Headers.ReceiptValid).Should().BeTrue();
return exchange.In.GetHeader(As4Headers.MessageId)!;
}
// A message as a partner's access point sends it, kept as bytes so that it can be sent again unchanged.
var (resend, resendId) = SecuredMessage();
await context.Start();
var first = await SendAsync();
(await PostAsync(port, resend)).Should().Be((HttpStatusCode.OK, (string?)null, true));
await context.Stop();
await context.Start();
context.GetRoute("as4-in")!.Status.Should().Be(RouteStatus.Started);
context.GetRoute("as4-out")!.Status.Should().Be(RouteStatus.Started);
var second = await SendAsync();
// Sent again after the restart: the duplicate store still knows it, so it gets its receipt and is not delivered.
(await PostAsync(port, resend)).Should().Be((HttpStatusCode.OK, (string?)null, true));
lock (delivered)
{
delivered.Select(d => d.MessageId).Should().Equal([first, resendId, second]);
delivered.Should().OnlyContain(d => d.Body == Payload);
}
((IEndpointStatistics)context.GetEndpoint(receiveUri)).Errors.Should().Be(0);
}
private static Exchange NewExchange()
{
var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" });
exchange.In.Headers[As4Headers.OriginalSender] = "C1";
exchange.In.Headers[As4Headers.FinalRecipient] = "C4";
return exchange;
}
/// A user message from A to B, compressed, signed and encrypted as A sends it; the bytes resend unchanged.
private static ((string ContentType, byte[] Body) Message, string MessageId) SecuredMessage()
{
const string contentId = "p1@a.example";
var message = SwaMessage.Create(As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@a.example", contentId,
from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: "Submit"));
message.AddPart(contentId, "application/gzip", As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload)));
var messageId = MessagingReader.Read(message.Envelope).UserMessages.Single().MessageInfo.MessageId;
As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow);
As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken);
return (message.Write(), messageId);
}
/// Posts a message as raw bytes and reads the signal that answers it.
private static async Task<(HttpStatusCode Status, string? ErrorCode, bool Receipt)> PostAsync(int port,
(string ContentType, byte[] Body) message)
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
var content = new ByteArrayContent(message.Body);
content.Headers.ContentType = MediaTypeHeaderValue.Parse(message.ContentType);
using var response = await http.PostAsync($"http://127.0.0.1:{port}/as4/in", content);
var body = await response.Content.ReadAsByteArrayAsync();
var answer = SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), body, 1024 * 1024);
var signals = MessagingReader.Read(answer.Envelope).SignalMessages;
var error = signals.SelectMany(s => s.Errors).FirstOrDefault();
return (response.StatusCode, error?.ErrorCode, signals.Any(s => s.IsReceipt));
}
private static As4Partner Partner(string name, X509Certificate2 certificate) => new()
{
Name = name,
PartyId = "urn:redb:" + name,
Service = "urn:example",
Action = "Submit",
PartnerSigningCertificates = { As4TestMessages.PublicOnly(certificate) },
PartnerEncryptionCertificate = As4TestMessages.PublicOnly(certificate),
};
private static As4ConnectionFactory Node(string name, X509Certificate2 key, params As4Partner[] partners)
{
var node = new As4ConnectionFactory
{
OurPartyId = "urn:redb:" + name,
ExternalHostName = name + ".example",
SigningCertificate = key,
DecryptionCertificates = { key },
};
foreach (var partner in partners) node.Partners.Add(partner);
return node;
}
}
Path: redb-route/tests/redb.Route.Tests.As4/As4RevocationTests.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.As4/As4RevocationTests.cs
----
using System.Net;
using System.Numerics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using redb.Route.As4.Security;
namespace redb.Route.Tests.As4;
///
/// Revocation of pinned certificates, against a real CRL a local CA publishes over HTTP (with its certificate at the
/// AIA caIssuers address, so the chain to the CRL signer can be built). The policy is phase4's and Domibus':
/// hard-fail when the status cannot be determined unless soft-fail is chosen; a certificate that names no CRL
/// distribution point and no AIA passes, as in Domibus. Off by default, as in Camel/CXF, Holodeck and phase4.
///
public sealed class As4RevocationTests : IAsyncLifetime
{
private readonly HttpListener _listener = new();
private readonly int _port = global::redb.Route.Tests.Shared.TestPorts.Next();
private readonly string _prefix = "/" + Guid.NewGuid().ToString("N"); // fresh URLs: the OS caches CRLs by URL
private readonly Dictionary _files = new(StringComparer.Ordinal);
private readonly Task _loop;
public As4RevocationTests()
{
_listener.Prefixes.Add($"http://127.0.0.1:{_port}/");
_listener.Start();
_loop = Task.Run(ServeAsync);
}
[Fact]
public void NotRevoked_Passes()
{
var (_, leaf) = Pki(revoke: false);
CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", Online()).Should().BeNull();
}
[Fact]
public void Revoked_IsRefused()
{
var (_, leaf) = Pki(revoke: true);
CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", Online())
.Should().Contain("revoked");
}
[Fact]
public void Revoked_ButNotChecked_Passes()
{
var (_, leaf) = Pki(revoke: true);
CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", RevocationPolicy.None).Should().BeNull();
}
[Fact]
public void UnreachableCrl_IsRefused_UnlessSoftFail()
{
var (_, leaf) = Pki(revoke: false, publish: false);
CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", Online())
.Should().Contain("could not be determined");
CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", Online() with { SoftFail = true })
.Should().BeNull();
}
[Fact]
public void CertificateWithoutRevocationPointers_Passes()
{
var selfSigned = As4TestMessages.KeyPair("CN=no-crl.as4.test");
CertificateValidity.Problem(selfSigned, DateTimeOffset.UtcNow, "The partner certificate", Online()).Should().BeNull();
}
[Fact]
public void MessageSignedWithARevokedCertificate_FailsVerification()
{
var (_, leaf) = Pki(revoke: true);
var message = redb.Route.As4.Mime.SwaMessage.Create(As4TestMessages.UserMessage("m-1@redb.test", "p1@redb.test"));
message.AddPart("p1@redb.test", "application/gzip", As4TestMessages.Gzip(""u8.ToArray()));
As4SecurityEngine.Sign(message, leaf, redb.Route.As4.As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow);
var act = () => As4SecurityEngine.Verify(message, [As4TestMessages.PublicOnly(leaf)], TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow, Online());
act.Should().Throw().WithMessage("*revoked*");
}
// ── Fixtures ─────────────────────────────────────────────────────────────
private static RevocationPolicy Online() => new(X509RevocationMode.Online, SoftFail: false);
/// A CA and a leaf it issued whose CDP and AIA point at this test's listener; the CRL lists the leaf when revoked.
private (X509Certificate2 Ca, X509Certificate2 Leaf) Pki(bool revoke, bool publish = true)
{
var crlUrl = $"http://127.0.0.1:{_port}{_prefix}/ca.crl";
var caUrl = $"http://127.0.0.1:{_port}{_prefix}/ca.cer";
using var caKey = RSA.Create(2048);
var caRequest = new CertificateRequest("CN=Test CA " + _prefix, caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true));
caRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(caRequest.PublicKey, false));
var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-2), DateTimeOffset.UtcNow.AddYears(1));
using var leafKey = RSA.Create(2048);
var leafRequest = new CertificateRequest("CN=partner.as4.test", leafKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
leafRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));
leafRequest.CertificateExtensions.Add(CertificateRevocationListBuilder.BuildCrlDistributionPointExtension([crlUrl]));
leafRequest.CertificateExtensions.Add(new X509AuthorityInformationAccessExtension(null, [caUrl]));
var serial = RandomNumberGenerator.GetBytes(16);
// Positive and without a redundant leading byte (DER INTEGER): a first byte of zero followed by one below 0x80
// is refused by CertificateRevocationListBuilder.AddEntry, which a plain "& 0x7F" produced about once in 512.
serial[0] = (byte)((serial[0] & 0x7F) | 0x40);
using var issued = leafRequest.Create(ca, DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddMonths(6), serial);
var leaf = issued.CopyWithPrivateKey(leafKey);
if (publish)
{
var crl = new CertificateRevocationListBuilder();
if (revoke)
crl.AddEntry(serial, DateTimeOffset.UtcNow.AddHours(-1), X509RevocationReason.KeyCompromise);
_files[$"{_prefix}/ca.crl"] = crl.Build(ca, BigInteger.One, DateTimeOffset.UtcNow.AddDays(7), HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1, DateTimeOffset.UtcNow.AddMinutes(-5));
_files[$"{_prefix}/ca.cer"] = ca.Export(X509ContentType.Cert);
}
return (ca, leaf);
}
// ── A certification path (eDelivery AS4 1.16 §4.3.3) ─────────────────────
[Fact]
public void Path_NotRevoked_Passes()
{
var pki = PathPki();
PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Root], []), DateTimeOffset.UtcNow, Online());
}
[Fact]
public void Path_WithARevokedSigner_IsRefused()
{
var pki = PathPki(revokeSigner: true);
var act = () => PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Root], []), DateTimeOffset.UtcNow, Online());
act.Should().Throw().WithMessage("The signing certificate CN=signer*has been revoked.");
}
[Fact]
public void Path_WithARevokedIntermediateAuthority_IsRefused()
{
var pki = PathPki(revokeIntermediate: true);
var act = () => PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Root], []), DateTimeOffset.UtcNow, Online());
act.Should().Throw().WithMessage("The certification authority CN=Issuing CA*has been revoked.");
}
[Fact]
public void Path_WithARevokedSigner_UnderAnIntermediateAnchor_IsRefused()
{
// .NET checks no revocation under an intermediate trust anchor (a partial chain, on Windows and on Linux): the
// root the token carries above the anchor completes the chain for the check.
var pki = PathPki(revokeSigner: true);
var act = () => PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Intermediate], []), DateTimeOffset.UtcNow, Online());
act.Should().Throw().WithMessage("*has been revoked.");
}
[Fact]
public void Path_WithARevokedSigner_UnderAnIntermediateAnchor_TokenWithoutTheRoot_IsRefused()
{
// The token stops at the anchor: the root is found from the anchor's authority information access.
var pki = PathPki(revokeSigner: true);
var act = () => PkiPath.EnsureTrusted([pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Intermediate], []), DateTimeOffset.UtcNow, Online());
act.Should().Throw().WithMessage("*has been revoked.");
}
[Fact]
public void Path_UnderAnIntermediateAnchor_WithNoRootToBeFound_IsUndetermined_UnlessSoftFail()
{
var pki = PathPki(intermediateNamesItsIssuer: false);
var trust = new PkiPathTrust([pki.Intermediate], []);
var act = () => PkiPath.EnsureTrusted([pki.Intermediate, pki.Signer], trust, DateTimeOffset.UtcNow, Online());
act.Should().Throw().WithMessage("*could not be determined (no self-signed root above the trust anchor*");
PkiPath.EnsureTrusted([pki.Intermediate, pki.Signer], trust, DateTimeOffset.UtcNow, Online() with { SoftFail = true });
}
[Fact]
public void Path_WithAnUnreachableCrl_IsUndetermined_UnlessSoftFail()
{
var pki = PathPki(publishSignerCrl: false);
var trust = new PkiPathTrust([pki.Root], []);
var act = () => PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], trust, DateTimeOffset.UtcNow, Online());
act.Should().Throw().WithMessage("The signing certificate*could not be determined*");
PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], trust, DateTimeOffset.UtcNow, Online() with { SoftFail = true });
}
[Fact]
public void Path_WithARevokedSigner_PassesWhenRevocationIsNotChecked()
{
var pki = PathPki(revokeSigner: true);
PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Root], []), DateTimeOffset.UtcNow, RevocationPolicy.None);
}
[Fact]
public void MessageSignedWithAPathToARevokedSigner_FailsVerification()
{
var pki = PathPki(revokeSigner: true);
var message = redb.Route.As4.Mime.SwaMessage.Create(As4TestMessages.UserMessage("m-1@redb.test", "p1@redb.test"));
message.AddPart("p1@redb.test", "application/gzip", As4TestMessages.Gzip(""u8.ToArray()));
As4SecurityEngine.Sign(message, pki.Signer, redb.Route.As4.As4KeyReference.PkiPath, null, DateTimeOffset.UtcNow,
[pki.Root, pki.Intermediate, pki.Signer]);
var act = () => As4SecurityEngine.Verify(message, [], TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow, Online(),
pkiPath: new PkiPathTrust([pki.Root], []));
act.Should().Throw().WithMessage("*revoked*");
}
///
/// root -> issuing CA -> signer, published by this test's listener: each CRL at its issuer's distribution point, each
/// issuer's certificate at the caIssuers address of the certificates it issued.
///
private (X509Certificate2 Root, X509Certificate2 Intermediate, X509Certificate2 Signer) PathPki(bool revokeSigner = false,
bool revokeIntermediate = false, bool publishSignerCrl = true, bool intermediateNamesItsIssuer = true)
{
string Url(string file) => $"http://127.0.0.1:{_port}{_prefix}/{file}";
using var rootKey = RSA.Create(2048);
var rootRequest = new CertificateRequest("CN=Path Root CA " + _prefix, rootKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
rootRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
rootRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true));
rootRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(rootRequest.PublicKey, false));
var root = rootRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-2), DateTimeOffset.UtcNow.AddYears(1));
using var intermediateKey = RSA.Create(2048);
var intermediateRequest = new CertificateRequest("CN=Issuing CA " + _prefix, intermediateKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
intermediateRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
intermediateRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true));
intermediateRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(intermediateRequest.PublicKey, false));
if (intermediateNamesItsIssuer)
{
intermediateRequest.CertificateExtensions.Add(CertificateRevocationListBuilder.BuildCrlDistributionPointExtension([Url("root.crl")]));
intermediateRequest.CertificateExtensions.Add(new X509AuthorityInformationAccessExtension(null, [Url("root.cer")]));
}
var intermediateSerial = Serial();
using var intermediateIssued = intermediateRequest.Create(root, DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddMonths(6), intermediateSerial);
var intermediate = intermediateIssued.CopyWithPrivateKey(intermediateKey);
using var signerKey = RSA.Create(2048);
var signerRequest = new CertificateRequest("CN=signer.as4.test", signerKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
signerRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));
signerRequest.CertificateExtensions.Add(CertificateRevocationListBuilder.BuildCrlDistributionPointExtension([Url("issuing.crl")]));
signerRequest.CertificateExtensions.Add(new X509AuthorityInformationAccessExtension(null, [Url("issuing.cer")]));
var signerSerial = Serial();
using var signerIssued = signerRequest.Create(intermediate, DateTimeOffset.UtcNow.AddHours(-12), DateTimeOffset.UtcNow.AddMonths(3), signerSerial);
var signer = signerIssued.CopyWithPrivateKey(signerKey);
_files[$"{_prefix}/root.cer"] = root.Export(X509ContentType.Cert);
_files[$"{_prefix}/issuing.cer"] = intermediate.Export(X509ContentType.Cert);
_files[$"{_prefix}/root.crl"] = Crl(root, revokeIntermediate ? intermediateSerial : null);
if (publishSignerCrl)
_files[$"{_prefix}/issuing.crl"] = Crl(intermediate, revokeSigner ? signerSerial : null);
return (As4TestMessages.PublicOnly(root), As4TestMessages.PublicOnly(intermediate), signer);
static byte[] Serial()
{
var serial = RandomNumberGenerator.GetBytes(16);
// Positive and without a redundant leading byte (DER INTEGER): a first byte of zero followed by one below 0x80
// is refused by CertificateRevocationListBuilder.AddEntry, which a plain "& 0x7F" produced about once in 512.
serial[0] = (byte)((serial[0] & 0x7F) | 0x40);
return serial;
}
static byte[] Crl(X509Certificate2 issuer, byte[]? revoked)
{
var crl = new CertificateRevocationListBuilder();
if (revoked is not null)
crl.AddEntry(revoked, DateTimeOffset.UtcNow.AddHours(-1), X509RevocationReason.KeyCompromise);
return crl.Build(issuer, BigInteger.One, DateTimeOffset.UtcNow.AddDays(7), HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1, DateTimeOffset.UtcNow.AddMinutes(-5));
}
}
private async Task ServeAsync()
{
while (_listener.IsListening)
{
HttpListenerContext http;
try { http = await _listener.GetContextAsync(); }
catch (HttpListenerException) { return; }
catch (ObjectDisposedException) { return; }
catch (ArgumentException) when (!_listener.IsListening) { return; }
if (_files.TryGetValue(http.Request.Url!.AbsolutePath, out var content))
{
http.Response.StatusCode = 200;
http.Response.ContentType = http.Request.Url.AbsolutePath.EndsWith(".crl") ? "application/pkix-crl" : "application/pkix-cert";
await http.Response.OutputStream.WriteAsync(content);
}
else
{
http.Response.StatusCode = 404;
}
http.Response.Close();
}
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
_listener.Stop();
_listener.Close();
await _loop.ConfigureAwait(false);
}
}
Path: redb-route/tests/redb.Route.Tests.As4/As4RouteXmlTests.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.As4/As4RouteXmlTests.cs
----
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using redb.Route.As4;
using redb.Route.As4.Messaging;
using redb.Route.As4.Mime;
using redb.Route.As4.Security;
using redb.Route.Components;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.Xml;
namespace redb.Route.Tests.As4;
///
/// The AS4 node is written in Route-XML as its README shows — a <bean> whose Partners is a
/// <list> of <ref> partners, certificates loaded by nested beans — and an as4: route from
/// XML receives a message and answers with a receipt. The Route-XML grammar is the one XmlBeanListAndRefTests covers.
///
public sealed class As4RouteXmlTests : IDisposable
{
private const string Password = "xml-test";
private static readonly X509Certificate2 NodeA = As4TestMessages.KeyPair("CN=a.as4.test");
private static readonly X509Certificate2 NodeB = As4TestMessages.KeyPair("CN=b.as4.test");
private readonly string _dir = Directory.CreateTempSubdirectory("redb-as4-xml-").FullName;
public void Dispose() => Directory.Delete(_dir, recursive: true);
[Fact]
public async Task NodeAndRouteFromXml_ReceiveAMessage_AndAnswerWithAReceipt()
{
// The PFX through the X509Certificate2 constructor, the overload named by , which the README
// shows with X509CertificateLoader; both are calls the markup has to reach.
File.WriteAllBytes(Path.Combine(_dir, "b.pfx"), NodeB.Export(X509ContentType.Pfx, Password));
File.WriteAllBytes(Path.Combine(_dir, "a.cer"), NodeA.Export(X509ContentType.Cert));
var port = global::redb.Route.Tests.Shared.TestPorts.Next();
const string certificate = "System.Security.Cryptography.X509Certificates.X509Certificate2, System.Security.Cryptography";
await using var context = new RouteContext();
context.AddComponent(new As4Component());
var delivered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
context.AddRoutes(r => r.From("direct://as4-inbound").Process(e => delivered.TrySetResult(e.In.GetHeader(As4Headers.Partner)!)));
context.AddXmlContextFromContent($"""
""");
context.AddXmlRoutesFromContent($"""
""");
await context.Start();
var (errorCode, receipt) = await Post(port);
errorCode.Should().BeNull();
receipt.Should().BeTrue();
(await delivered.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("a");
}
[Fact]
public async Task APartnerWithAnAddressInXml_IsSentToThere_FromAnEndpointWithoutOne()
{
// The address belongs to the agreement, as Protocol.Address belongs to a P-Mode: the markup sends to as4:?partner=a.
File.WriteAllBytes(Path.Combine(_dir, "b.pfx"), NodeB.Export(X509ContentType.Pfx, Password));
File.WriteAllBytes(Path.Combine(_dir, "a.cer"), NodeA.Export(X509ContentType.Cert));
var port = global::redb.Route.Tests.Shared.TestPorts.Next();
const string certificate = "System.Security.Cryptography.X509Certificates.X509Certificate2, System.Security.Cryptography";
await using var context = new RouteContext();
context.AddComponent(new As4Component());
// Node a, in C#: it receives what node b sends.
context.AddToRegistry("a", new As4ConnectionFactory
{
OurPartyId = "urn:redb:a",
ExternalHostName = "a.example",
SigningCertificate = NodeA,
DecryptionCertificates = { NodeA },
Partners =
{
new As4Partner
{
Name = "b",
PartyId = "urn:redb:b",
Service = "urn:example",
Action = "Submit",
PartnerSigningCertificates = { As4TestMessages.PublicOnly(NodeB) },
PartnerEncryptionCertificate = As4TestMessages.PublicOnly(NodeB),
RequireFourCornerProperties = false,
},
},
});
context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository());
var delivered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
context.AddRoutes(r => r.From($"as4:/as4/in?host=127.0.0.1&port={port}&connectionFactory=a&idempotentRepository=dedup")
.Process(e => delivered.TrySetResult(e.In.GetHeader(As4Headers.Partner)!)));
context.AddXmlContextFromContent($"""
""");
context.AddXmlRoutesFromContent("""
""");
await context.Start();
var template = new ProducerTemplate(context);
template.Start();
await template.SendAsync("direct://as4-outbound", "");
(await delivered.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("b");
}
private async Task<(string? ErrorCode, bool Receipt)> Post(int port)
{
const string contentId = "p1@a.example";
using var message = SwaMessage.Create(As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@a.example", contentId,
from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: "Submit"));
message.AddPart(contentId, "application/gzip", As4TestMessages.Gzip(Encoding.UTF8.GetBytes("")));
As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow);
As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken);
var (contentType, body) = message.Write();
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
var content = new ByteArrayContent(body);
content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
using var response = await http.PostAsync($"http://127.0.0.1:{port}/as4/in", content);
var answer = SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), await response.Content.ReadAsByteArrayAsync(), 1024 * 1024);
var signals = MessagingReader.Read(answer.Envelope).SignalMessages;
return (signals.SelectMany(s => s.Errors).FirstOrDefault()?.ErrorCode, signals.Any(s => s.IsReceipt));
}
}
Path: redb-route/tests/redb.Route.Tests.As4/As4SecurityRoundTripTests.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.As4/As4SecurityRoundTripTests.cs
----
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using redb.Route.As4;
using redb.Route.As4.Mime;
using redb.Route.As4.Security;
namespace redb.Route.Tests.As4;
///
/// What we sign and encrypt, we decrypt and verify — through the wire format (serialized, parsed back),
/// for every key reference form, and every tampering is refused for its own reason. Keys are generated
/// in memory; no harness needed.
///
public class As4SecurityRoundTripTests
{
private static readonly X509Certificate2 Sender = KeyPair("CN=sender.as4.test");
private static readonly X509Certificate2 Receiver = KeyPair("CN=receiver.as4.test");
private static readonly X509Certificate2 Stranger = KeyPair("CN=stranger.as4.test");
private static readonly TimeSpan Tolerance = TimeSpan.FromMinutes(5);
private static readonly byte[] Payload = Encoding.UTF8.GetBytes("42");
[Theory]
[InlineData(As4KeyReference.BinarySecurityToken)]
[InlineData(As4KeyReference.IssuerSerial)]
[InlineData(As4KeyReference.KeyIdentifier)]
public void SignEncrypt_ThenDecryptVerify_ReturnsThePayload(As4KeyReference form)
{
var received = Transfer(Build(form, timestamp: true));
var decrypted = As4SecurityEngine.Decrypt(received, [Receiver]);
var verification = As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow);
decrypted.Should().ContainSingle();
verification.Signer.Thumbprint.Should().Be(Sender.Thumbprint);
verification.References.Should().HaveCount(4); // eb:Messaging, Body, wsu:Timestamp, attachment
var part = received.Parts[decrypted[0]];
part.ContentType.Should().Be("application/gzip");
Gunzip(part.ToArray()).Should().Equal(Payload);
}
[Fact]
public void WhatWeSend_NamesExactlyTheAlgorithmsAndTransformsOfTheProfile()
{
// What a conformance test driver reads off a message the SUT sent (eDelivery AS4 1.16 §3.2.6; testing service
// 2026.06: encryption algorithm, signature algorithm, attachment signing and encryption transforms, WSS 1.1).
var envelope = Build(As4KeyReference.BinarySecurityToken, timestamp: false).Message.Envelope;
string[] Algorithms(string localName, string ns) => envelope.GetElementsByTagName(localName, ns)
.Cast().Select(e => e.GetAttribute("Algorithm")).ToArray();
envelope.DocumentElement!.NamespaceURI.Should().Be("http://www.w3.org/2003/05/soap-envelope", "SOAP 1.2");
// Payloads travel as attachments: the SOAP body is empty, and it is signed all the same (AS4_CP_TA05, TA12).
var body = (XmlElement)envelope.GetElementsByTagName("Body", "http://www.w3.org/2003/05/soap-envelope")[0]!;
body.HasChildNodes.Should().BeFalse();
var bodyId = body.GetAttribute("Id", WsSecurityNames.Wsu);
envelope.GetElementsByTagName("Reference", WsSecurityNames.Ds).Cast().Select(r => r.GetAttribute("URI"))
.Should().Contain("#" + bodyId);
// Signature: RSA-SHA256 over SHA-256 digests, exclusive canonicalization; the attachment by its content.
Algorithms("SignatureMethod", WsSecurityNames.Ds).Should().Equal("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
Algorithms("CanonicalizationMethod", WsSecurityNames.Ds).Should().Equal("http://www.w3.org/2001/10/xml-exc-c14n#");
Algorithms("DigestMethod", WsSecurityNames.Ds).Should().OnlyContain(a => a == "http://www.w3.org/2001/04/xmlenc#sha256");
var references = envelope.GetElementsByTagName("Reference", WsSecurityNames.Ds).Cast().ToList();
references.Select(r => r.GetAttribute("URI")).Should().Contain("cid:payload-1@redb.test");
references.Single(r => r.GetAttribute("URI").StartsWith("cid:", StringComparison.Ordinal))
.GetElementsByTagName("Transform", WsSecurityNames.Ds).Cast().Select(t => t.GetAttribute("Algorithm"))
.Should().Equal("http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Signature-Transform");
// Key transport: RSA-OAEP with MGF1-SHA256 and a SHA-256 digest (XML Encryption 1.1).
var encryptedKey = (XmlElement)envelope.GetElementsByTagName("EncryptedKey", WsSecurityNames.Xenc)[0]!;
var keyMethod = (XmlElement)encryptedKey.GetElementsByTagName("EncryptionMethod", WsSecurityNames.Xenc)[0]!;
keyMethod.GetAttribute("Algorithm").Should().Be("http://www.w3.org/2009/xmlenc11#rsa-oaep");
((XmlElement)keyMethod.GetElementsByTagName("MGF", WsSecurityNames.Xenc11)[0]!).GetAttribute("Algorithm")
.Should().Be("http://www.w3.org/2009/xmlenc11#mgf1sha256");
((XmlElement)keyMethod.GetElementsByTagName("DigestMethod", WsSecurityNames.Ds)[0]!).GetAttribute("Algorithm")
.Should().Be("http://www.w3.org/2001/04/xmlenc#sha256");
// Payload: AES-128-GCM, the ciphertext in place of the attachment's content, the attachment content only.
var encryptedData = (XmlElement)envelope.GetElementsByTagName("EncryptedData", WsSecurityNames.Xenc)[0]!;
encryptedData.GetAttribute("Type").Should().Be("http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Only");
((XmlElement)encryptedData.GetElementsByTagName("EncryptionMethod", WsSecurityNames.Xenc)[0]!).GetAttribute("Algorithm")
.Should().Be("http://www.w3.org/2009/xmlenc11#aes128-gcm");
var cipherReference = (XmlElement)encryptedData.GetElementsByTagName("CipherReference", WsSecurityNames.Xenc)[0]!;
cipherReference.GetAttribute("URI").Should().Be("cid:payload-1@redb.test");
cipherReference.GetElementsByTagName("Transform", WsSecurityNames.Ds).Cast().Select(t => t.GetAttribute("Algorithm"))
.Should().Equal("http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Ciphertext-Transform");
// Only the payload is encrypted: the ebMS header travels in the clear (profile §3.2.6).
envelope.GetElementsByTagName("Messaging", WsSecurityNames.Eb).Count.Should().Be(1);
envelope.GetElementsByTagName("EncryptedData", WsSecurityNames.Xenc).Count.Should().Be(1);
}
[Fact]
public void Sign_ReturnsTheReferencesTheReceiverSees()
{
var sent = Build(As4KeyReference.BinarySecurityToken, timestamp: false);
var sentReferences = sent.References.Select(r => r.OuterXml).ToList();
var received = Transfer(sent.Message);
As4SecurityEngine.Decrypt(received, [Receiver]);
var verification = As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow);
verification.References.Select(r => r.OuterXml).Should().Equal(sentReferences);
}
[Fact]
public void Verify_TamperedHeaderAfterSigning_IsRefused()
{
var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false));
As4SecurityEngine.Decrypt(received, [Receiver]);
((XmlElement)received.Envelope.GetElementsByTagName("Action", WsSecurityNames.Eb)[0]!).InnerText = "Refund";
var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow);
act.Should().Throw().WithMessage("*digest of*does not match*");
}
[Fact]
public void Verify_TamperedSignedInfo_IsRefused()
{
var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false));
As4SecurityEngine.Decrypt(received, [Receiver]);
// Rewriting a digest value together with the element it covers leaves the references consistent; only
// the signature over SignedInfo can notice.
var digest = (XmlElement)received.Envelope.GetElementsByTagName("DigestValue", WsSecurityNames.Ds)[0]!;
digest.InnerText = Convert.ToBase64String(new byte[32]);
var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow);
act.Should().Throw().WithMessage("The signature does not verify.");
}
[Theory]
// The signature over SignedInfo is checked first, and a DigestValue is part of SignedInfo.
[InlineData("SignatureValue", "ds:SignatureValue is not valid base64.")]
[InlineData("DigestValue", "The signature does not verify.")]
public void Verify_ValueThatIsNotBase64_IsRefusedAsASecurityFailure(string element, string reason)
{
// A security failure (EBMS:0101), not an unexpected failure of the receiver (AS4_CP_TA66).
var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false));
As4SecurityEngine.Decrypt(received, [Receiver]);
((XmlElement)received.Envelope.GetElementsByTagName(element, WsSecurityNames.Ds)[0]!).InnerText = "not*base64!";
var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow);
act.Should().Throw