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