Path: redb-route/tests/redb.Route.Tests.As2/As2MicRulesTests.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.As2/As2MicRulesTests.cs ---- using System.Security.Cryptography; using System.Text; using AwesomeAssertions; using MimeKit; using MimeKit.Cryptography; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// The Received-Content-MIC of each profile (RFC 4130 §7.3.1, RFC 5402 §4): signed, over the data that was signed; /// unsigned and encrypted (compressed or not), over the uncompressed part with its MIME headers; unsigned and not /// encrypted (compressed or plain), over the content alone. And a message signed before it was compressed (RFC 5402 /// §3.3/3.6) is verified like one compressed first. /// public class As2MicRulesTests { private const string Payload = "ISA*00*MIC*RULES~"; private static async Task<(RouteContext Context, List<(string Body, bool SignatureValid)> Delivered, int Port)> StartReceiver( Action configure) { var port = FreePort(); var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver(configure)); var delivered = new List<(string, bool)>(); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv")) .Process(e => { lock (delivered) delivered.Add((Encoding.UTF8.GetString((byte[])e.In.Body!), e.In.GetHeader(As2Headers.SignatureValid))); })); await context.Start(); return (context, delivered, port); } private static MdnParser.MdnResult ReadMdn(HttpResponseMessage response) => MdnParser.Parse( response.Content.Headers.ContentType?.ToString(), response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null, response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(), new As2CryptoEngine(), Cert); /// The top-level entity of a built message, as the receiver parses it. private static MimeEntity Parse((string ContentType, string? TransferEncoding, byte[] Body) message) { var head = $"Content-Type: {message.ContentType}\r\n" + (message.TransferEncoding is null ? "" : $"Content-Transfer-Encoding: {message.TransferEncoding}\r\n") + "\r\n"; var stream = new MemoryStream(); stream.Write(Encoding.ASCII.GetBytes(head)); stream.Write(message.Body); stream.Position = 0; return MimeEntity.Load(stream); } /// SHA-256 over a MIME part's headers and content as written, with CRLF line ends. private static string HeadersAndContent(MimeEntity part) { var options = FormatOptions.Default.Clone(); options.NewLineFormat = NewLineFormat.Dos; using var ms = new MemoryStream(); part.WriteTo(options, ms); return Convert.ToBase64String(SHA256.HashData(ms.ToArray())); } [Fact] public async Task EncryptedUnsigned_TheMicIsOverTheDecryptedPart_WithItsHeaders() { var (context, delivered, port) = await StartReceiver(f => f.Sign = false); await using var _ = context; var message = BuildMessage(Payload, signer: null, recipient: Cert); var mdn = ReadMdn(await PostAsync(port, "/in", message)); delivered.Should().ContainSingle().Which.Body.Should().Be(Payload); using var ctx = new TemporarySecureMimeContext(); ctx.Import(Cert); var decrypted = ((ApplicationPkcs7Mime)Parse(message)).Decrypt(ctx); mdn.ReceivedMic!.Value.Digest.Should().Be(HeadersAndContent(decrypted)); mdn.ReceivedMic!.Value.Digest.Should().NotBe(Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Payload))), "an encrypted message is not hashed over its content alone"); } [Fact] public async Task CompressedEncryptedUnsigned_TheMicIsOverTheDecompressedPart_WithItsHeaders() { var (context, delivered, port) = await StartReceiver(f => f.Sign = false); await using var _ = context; var message = BuildMessage(Payload, signer: null, recipient: Cert, compress: true); var mdn = ReadMdn(await PostAsync(port, "/in", message)); delivered.Should().ContainSingle().Which.Body.Should().Be(Payload); using var ctx = new TemporarySecureMimeContext(); ctx.Import(Cert); var decrypted = ((ApplicationPkcs7Mime)Parse(message)).Decrypt(ctx); var decompressed = ((ApplicationPkcs7Mime)decrypted).Decompress(ctx); mdn.ReceivedMic!.Value.Digest.Should().Be(HeadersAndContent(decompressed)); } [Fact] public async Task CompressedUnsigned_TheMicIsOverTheContentAlone() { var (context, delivered, port) = await StartReceiver(f => { f.Sign = false; f.Encrypt = false; }); await using var _ = context; var message = BuildMessage(Payload, signer: null, recipient: null, compress: true); var mdn = ReadMdn(await PostAsync(port, "/in", message)); delivered.Should().ContainSingle().Which.Body.Should().Be(Payload); // Not encrypted: RFC 4130 §7.3.1, and what OpenAS2 4.9.0 computes (RFC 5402 §4.3 would add the headers). mdn.ReceivedMic!.Value.Digest.Should().Be(Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Payload)))); } [Fact] public async Task Plain_TheMicIsOverTheContentAlone() { var (context, delivered, port) = await StartReceiver(f => { f.Sign = false; f.Encrypt = false; }); await using var _ = context; var mdn = ReadMdn(await PostAsync(port, "/in", BuildMessage(Payload, signer: null, recipient: null))); delivered.Should().ContainSingle(); mdn.ReceivedMic!.Value.Digest.Should().Be(Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Payload)))); } [Theory] [InlineData(true)] [InlineData(false)] public async Task SignedThenCompressed_IsVerified_AndItsMicIsOverTheSignedPayload(bool encrypt) { var (context, delivered, port) = await StartReceiver(f => f.Encrypt = encrypt); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage(Payload, signer: Cert, recipient: encrypt ? Cert : null, compress: true, compressAfterSign: true)); var routed = delivered.Should().ContainSingle().Subject; routed.Body.Should().Be(Payload, "the payload, not the multipart/signed around it"); routed.SignatureValid.Should().BeTrue(); var mdn = ReadMdn(response); mdn.IsPositive.Should().BeTrue(); // What was signed is the payload part itself, prepared for signing as the sender prepared it. var signedPart = new MimePart("application", "edi-x12") { Content = new MimeContent(new MemoryStream(Encoding.UTF8.GetBytes(Payload))), ContentTransferEncoding = ContentEncoding.Binary, }; mdn.ReceivedMic!.Value.Digest.Should().Be(new As2CryptoEngine().ComputeMic(signedPart, "sha-256", includeHeaders: true).Digest); } [Theory] [InlineData(true, false)] [InlineData(false, true)] [InlineData(true, true)] public async Task UnsignedProfiles_SentByRedb_AreConfirmedByRedb(bool encrypt, bool compress) { var (context, delivered, port) = await StartReceiver(f => { f.Sign = false; f.Encrypt = encrypt; }); await using var _ = context; context.AddToRegistry("send", Sender(f => { f.Sign = false; f.Encrypt = encrypt; f.Compress = compress; })); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/in").ConnectionFactory("send")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(Payload) { ContentType = "application/edi-x12" }); await producer.Process(exchange); delivered.Should().ContainSingle().Which.Body.Should().Be(Payload); exchange.Out!.GetHeader(As2Headers.MdnMicStatus).Should().Be("matched"); exchange.Out!.GetHeader(As2Headers.MdnConfirmed).Should().BeTrue(); } }