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