예제 #1
0
        public async Task Received_Bundled_Response_Should_Process_All_Messages()
        {
            // Arrange
            string pullSenderUrl = RetrievePullingUrlFromConfig();

            string storedMessageId = "stored-" + Guid.NewGuid();

            StoreToBeAckOutMessage(storedMessageId);
            AS4Message bundled = CreateBundledMultipleUserMessagesWithRefTo();

            bundled.AddMessageUnit(new Receipt($"receipt-{Guid.NewGuid()}", storedMessageId));

            // Act
            await RespondToPullRequestAsync(
                pullSenderUrl,
                response =>
            {
                response.ContentType = bundled.ContentType;
                response.StatusCode  = 200;
                using (Stream output = response.OutputStream)
                {
                    SerializerProvider.Default
                    .Get(bundled.ContentType)
                    .Serialize(bundled, output);
                }
            });

            // Assert
            IEnumerable <InMessage> storedBundled =
                await PollUntilPresent(
                    () => _databaseSpy.GetInMessages(bundled.UserMessages.Select(u => u.MessageId).ToArray())
                    .Where(m => m.Operation == Operation.ToBeDelivered),
                    timeout : TimeSpan.FromSeconds(20));

            Assert.Collection(
                storedBundled,
                userMessage1 =>
            {
                Assert.Equal(MessageExchangePattern.Pull, userMessage1.MEP);
                Assert.Equal(InStatus.Received, userMessage1.Status.ToEnum <InStatus>());
                Assert.Equal(Operation.ToBeDelivered, userMessage1.Operation);
            },
                userMessage2 =>
            {
                Assert.Equal(MessageExchangePattern.Pull, userMessage2.MEP);
                Assert.Equal(InStatus.Received, userMessage2.Status.ToEnum <InStatus>());
                Assert.Equal(Operation.ToBeDelivered, userMessage2.Operation);
            });
            Assert.Collection(
                _databaseSpy.GetInMessages(bundled.SignalMessages.Select(s => s.MessageId).ToArray()),
                signal =>
            {
                Assert.Equal(MessageExchangePattern.Pull, signal.MEP);
                Assert.Equal(InStatus.Received, signal.Status.ToEnum <InStatus>());
                Assert.Equal(Operation.ToBeNotified, signal.Operation);
            });
            Assert.Collection(
                _databaseSpy.GetOutMessages(storedMessageId),
                stored => Assert.Equal(OutStatus.Ack, stored.Status.ToEnum <OutStatus>()));
        }
        public async Task Fails_To_Store_SignalMessage_When_ReplyPattern_Response_For_Pulled_UserMessage()
        {
            // Arrange
            string userMessageId = $"user-{Guid.NewGuid()}";

            GetDataStoreContext.InsertInMessage(
                new InMessage(userMessageId)
            {
                MEP = MessageExchangePattern.Pull
            });

            var receipt = new Receipt($"receipt-{Guid.NewGuid()}", userMessageId);
            var context = new MessagingContext(
                AS4Message.Create(receipt),
                MessagingContextMode.Receive)
            {
                SendingPMode = new SendingProcessingMode {
                    Id = "shortcut-send-pmode-retrieval"
                },
                ReceivingPMode = new ReceivingProcessingMode
                {
                    ReplyHandling = { ReplyPattern = ReplyPattern.Response }
                }
            };

            // Act / Assert
            await Assert.ThrowsAsync <InvalidOperationException>(
                () => ExerciseStoreSignalMessageAsync(context));
        }
        protected MessagingContext CreateEncryptedAS4Message()
        {
            Stream attachmentStream = new MemoryStream(Encoding.UTF8.GetBytes("Hello, encrypt me"));
            var    attachment       = new Attachment("attachment-id", attachmentStream, "text/plain");

            AS4Message as4Message = AS4Message.Empty;

            as4Message.AddMessageUnit(new UserMessage($"user-{Guid.NewGuid()}"));
            as4Message.AddAttachment(attachment);

            var message = new MessagingContext(as4Message, MessagingContextMode.Unknown)
            {
                SendingPMode = new SendingProcessingMode()
            };

            message.SendingPMode.Security.Encryption.IsEnabled       = true;
            message.SendingPMode.Security.Encryption.Algorithm       = "http://www.w3.org/2009/xmlenc11#aes128-gcm";
            message.SendingPMode.Security.Encryption.CertificateType = PublicKeyCertificateChoiceType.CertificateFindCriteria;
            message.SendingPMode.Security.Encryption.EncryptionCertificateInformation = new CertificateFindCriteria()
            {
                CertificateFindType  = X509FindType.FindBySerialNumber,
                CertificateFindValue = "some dummy value"
            };

            return(message);
        }
예제 #4
0
        public async Task CanCreateMessageWithPModeWithoutToParty()
        {
            // Arrange
            var sendingParty = CreatePModeParty("sender", "c2", "eu.edelivery.services");

            var pmode = CreateSendingPMode(fromParty: sendingParty, toParty: null);

            var receivingParty = CreateSubmitMessageParty("receiver", "type", "c3");

            var submitMessage = CreateSubmitMessage(pmode, fromParty: null, toParty: receivingParty);

            var context = new MessagingContext(submitMessage)
            {
                SendingPMode = pmode
            };

            // Act
            var result = await ExerciseCreation(context);

            // Assert
            Assert.True(result.Succeeded);
            AS4Message as4Message = result.MessagingContext.AS4Message;

            Assert.False(as4Message.IsEmpty);
            Assert.True(as4Message.IsUserMessage);
            Assert.Equal(receivingParty.Role, as4Message.FirstUserMessage.Receiver.Role);
            Assert.Equal(receivingParty.PartyIds.First().Id, as4Message.FirstUserMessage.Receiver.PartyIds.First().Id);
            Assert.Equal(receivingParty.PartyIds.First().Type, as4Message.FirstUserMessage.Receiver.PartyIds.First().Type.UnsafeGet);
        }
예제 #5
0
        private static VerifySignatureConfig CreateVerifyOptionsForAS4Message(AS4Message as4Message, SigningVerification v)
        {
            bool allowUnknownRootCertificateAuthority =
                v?.AllowUnknownRootCertificate ?? new SigningVerification().AllowUnknownRootCertificate;

            return(new VerifySignatureConfig(allowUnknownRootCertificateAuthority, as4Message.Attachments));
        }
            public async Task TestIfAttachmentContentTypeIsSetBackToOriginal()
            {
                // Arrange
                AS4Message as4Message = await GetEncryptedAS4MessageAsync();

                var context = new MessagingContext(as4Message, MessagingContextMode.Receive)
                {
                    ReceivingPMode = new ReceivingProcessingMode
                    {
                        Security = { Decryption                        =
                                     {
                                         Encryption                    = Limit.Allowed,
                                         DecryptCertificateInformation = new CertificateFindCriteria {
                                             CertificateFindType       = X509FindType.FindBySerialNumber
                                         }
                                     } }
                    }
                };

                // Act
                StepResult result = await ExerciseDecryption(context);

                // Assert
                IEnumerable <Attachment> attachments = result.MessagingContext.AS4Message.Attachments;

                Assert.All(attachments, a => Assert.Equal("image/jpeg", a.ContentType));
            }
        private async Task <StepResult> ExerciseVerifyNRRReceipt(
            IAS4MessageBodyStore messageStore,
            AS4Message signedReceiptResult,
            bool verifyNrr)
        {
            var verifyNrrPMode = new SendingProcessingMode {
                ReceiptHandling = { VerifyNRR = verifyNrr }
            };
            var verifySignaturePMode = new ReceivingProcessingMode {
                Security = { SigningVerification = { Signature = Limit.Required } }
            };

            var step = new VerifySignatureAS4MessageStep(
                GetDataStoreContext,
                messageStore);

            return(await step.ExecuteAsync(
                       new MessagingContext(
                           signedReceiptResult,
                           MessagingContextMode.Receive)
            {
                SendingPMode = verifyNrrPMode,
                ReceivingPMode = verifySignaturePMode
            }));
        }
            public Property Multiple_UserMessages_Their_Attachments_Gets_Decompressed(NonEmptyArray <Guid> attachmentIds)
            {
                Action act = () =>
                {
                    // Arrange
                    AS4Message as4Message = attachmentIds.Get.Distinct().Aggregate(
                        AS4Message.Empty,
                        (as4, id) =>
                    {
                        as4.AddMessageUnit(UserMessageWithCompressedInfo(id.ToString()));
                        as4.AddAttachment(CompressedAttachment(id.ToString()));
                        return(as4);
                    });

                    // Act
                    StepResult result = ExerciseDecompress(as4Message);

                    // Assert
                    Assert.All(
                        result.MessagingContext.AS4Message.Attachments,
                        a => Assert.NotEqual("application/gzip", a.ContentType));

                    Assert.All(
                        result.MessagingContext.AS4Message.UserMessages.SelectMany(u => u.PayloadInfo),
                        p => Assert.Equal("application/gzip", p.CompressionType));
                };

                return(act.When(attachmentIds.Get.Distinct().Any()));
            }
        /// <summary>
        /// Determines whether a pull-request is authorized
        /// </summary>
        /// <param name="pullRequestMessage">An AS4 Message for which the primary signal-message is a PullRequest.</param>
        /// <returns>True if the PullRequest is allowed to be processed.</returns>
        public bool IsPullRequestAuthorized(AS4Message pullRequestMessage)
        {
            if (pullRequestMessage == null)
            {
                throw new ArgumentNullException(nameof(pullRequestMessage));
            }

            if (pullRequestMessage.IsPullRequest == false)
            {
                throw new InvalidMessageException("The AS4 Message is not a PullRequest message");
            }

            var mpc = ((PullRequest)pullRequestMessage.FirstSignalMessage).Mpc;

            var authorizationEntries = _mapProvider.RetrievePullRequestAuthorizationEntriesForMpc(mpc);

            if (authorizationEntries == null || authorizationEntries.Any() == false)
            {
                return(true);
            }

            if (pullRequestMessage.SecurityHeader.IsSigned == false && authorizationEntries.Any())
            {
                return(false);
            }

            var certificateThumbPrint = RetrieveSigningCertificateThumbPrint(pullRequestMessage, _certificateRepository);

            var authorizationEntriesForCertificate =
                authorizationEntries.Where(a => StringComparer.OrdinalIgnoreCase.Equals(a.CertificateThumbprint, certificateThumbPrint));

            return(authorizationEntriesForCertificate.Any() && authorizationEntriesForCertificate.All(a => a.Allowed));
        }
예제 #10
0
        /// <summary>
        /// Execute the step for a given <paramref name="messagingContext" />.
        /// </summary>
        /// <param name="messagingContext">Message used during the step execution.</param>
        /// <returns></returns>
        public async Task <StepResult> ExecuteAsync(MessagingContext messagingContext)
        {
            var pullRequest = messagingContext?.AS4Message?.FirstSignalMessage as PullRequest;

            if (pullRequest == null)
            {
                throw new InvalidMessageException(
                          "The received message is not a PullRequest message, " +
                          "therefore no UserMessage can be selected to return to the sender");
            }

            (bool hasMatch, OutMessage match) = RetrieveUserMessageForPullRequest(pullRequest);
            if (hasMatch)
            {
                // Retrieve the existing MessageBody and put that stream in the MessagingContext.
                // The HttpReceiver processor will make sure that it gets serialized to the http response stream.
                Stream messageBody = await match.RetrieveMessageBody(_messageBodyStore).ConfigureAwait(false);

                messagingContext.ModifyContext(
                    new ReceivedMessage(messageBody, match.ContentType),
                    MessagingContextMode.Send);

                messagingContext.SendingPMode = AS4XmlSerializer.FromString <SendingProcessingMode>(match.PMode);

                return(StepResult.Success(messagingContext));
            }

            AS4Message pullRequestWarning = AS4Message.Create(Error.CreatePullRequestWarning(IdentifierFactory.Instance.Create()));

            messagingContext.ModifyContext(pullRequestWarning);

            return(StepResult.Success(messagingContext).AndStopExecution());
        }
예제 #11
0
        /// <summary>
        /// Creates a <see cref="JournalLogEntry"/> based on a given <see cref="AS4Message"/>.
        /// </summary>
        /// <param name="msg">The message to create a log entry from.</param>
        /// <param name="details">The log details collected with the message.</param>
        public static JournalLogEntry CreateFrom(AS4Message msg, string details)
        {
            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg));
            }

            if (msg.IsEmpty)
            {
                throw new NotSupportedException(
                          $"Can't create {nameof(JournalLogEntry)} from an AS4Message without message units");
            }

            if (msg.PrimaryMessageUnit is UserMessage um)
            {
                return(new JournalLogEntry(
                           um.MessageId,
                           um.RefToMessageId,
                           um.CollaborationInfo.Service.Value,
                           um.CollaborationInfo.Action,
                           um.Receiver.PrimaryPartyId,
                           um.Sender.PrimaryPartyId,
                           new [] { details }));
            }

            return(new JournalLogEntry(
                       msg.PrimaryMessageUnit.MessageId,
                       msg.PrimaryMessageUnit.RefToMessageId,
                       new[] { details }));
        }
        private void InsertUserMessage(string mpc, MessageExchangePattern pattern, Operation operation)
        {
            var sendingPMode = new SendingProcessingMode()
            {
                Id = "SomePModeId",
                MessagePackaging = { Mpc = mpc }
            };

            UserMessage userMessage = SendingPModeMap.CreateUserMessage(sendingPMode);
            AS4Message  as4Message  = AS4Message.Create(userMessage, sendingPMode);

            var om = new OutMessage(userMessage.MessageId)
            {
                MEP             = pattern,
                Mpc             = mpc,
                ContentType     = as4Message.ContentType,
                EbmsMessageType = MessageType.UserMessage,
                Operation       = operation,
                MessageLocation =
                    InMemoryMessageBodyStore.Default.SaveAS4Message(location: "some-location", message: as4Message)
            };

            om.SetPModeInformation(sendingPMode);
            GetDataStoreContext.InsertOutMessage(om);
        }
예제 #13
0
        /// <summary>
        /// Sends an AS4 Message to the endpoint that listens at the specified url.
        /// </summary>
        /// <param name="url">The url of the endpoint to send the message to.</param>
        /// <param name="as4Message">The AS4Message that must be sent.</param>
        /// <returns></returns>
        public static async Task <HttpResponseMessage> SendAS4Message(string url, AS4Message as4Message)
        {
            var request = await CreatePostRequestMessage(url, as4Message);

            Console.WriteLine($@"Send AS4Message as HTTP POST request to: {url}, Content-Type: {as4Message.ContentType}");
            return(await Client.SendAsync(request));
        }
예제 #14
0
        private static AS4Message CreateBundledMultipleUserMessagesWithRefTo()
        {
            var userMessage1 = new UserMessage(
                messageId: "user1-" + Guid.NewGuid(),
                collaboration: new CollaborationInfo(
                    agreement: new AgreementReference(
                        value: "http://agreements.europa.org/agreement",
                        pmodeId: "pullreceive_bundled_pmode"),
                    service: new Service(
                        value: "bundling",
                        type: "as4:net:pullreceive:bundling"),
                    action: "as4:net:pullreceive:bundling",
                    conversationId: "as4:net:pullreceive:conversation"));

            var userMessage2 = new UserMessage(
                messageId: "user2-" + Guid.NewGuid(),
                collaboration: new CollaborationInfo(
                    agreement: new AgreementReference(
                        value: "http://agreements.europa.org/agreement",
                        pmodeId: "some-other-pmode-id"),
                    service: new Service(
                        value: "bundling",
                        type: "as4:net:pullreceive:bundling"),
                    action: "as4:net:pullreceive:bundling",
                    conversationId: "as4:net:pullreceive:conversation"));

            var bundled = AS4Message.Create(userMessage1);

            bundled.AddMessageUnit(userMessage2);

            return(bundled);
        }
        private static AS4Message UserMessageWithAttachment(string argRefPModeId)
        {
            var user = new UserMessage(
                Guid.NewGuid().ToString(),
                HolodeckCollaboration(argRefPModeId),
                new Party(Constants.Namespaces.EbmsDefaultFrom, new PartyId(Constants.Namespaces.EbmsDefaultFrom)),
                new Party(HolodeckPartyRole, new PartyId(HolodeckBId, HolodeckBId)),
                new[]
            {
                new PartInfo(
                    href: "cid:earth",
                    properties: new Dictionary <string, string>
                {
                    ["Part Property"] = "Some Holodeck required Part Property"
                },
                    schemas: new Schema[0])
            },
                new Model.Core.MessageProperty[0]);

            AS4Message userMessage = AS4Message.Create(user, new SendingProcessingMode {
                MessagePackaging = { IsMultiHop = true }
            });

            userMessage.AddAttachment(ImageAttachment(id: "earth"));

            return(userMessage);
        }
예제 #16
0
        public async Task ForwardingWithPushOnPull()
        {
            // Arrange
            const string messageId     = "user-message-id";
            var          tobeForwarded = AS4Message.Create(CreateForwardPushUserMessage(messageId));

            // Act
            InsertToBeForwardedInMessage(
                pmodeId: "Forward_Push",
                mep: MessageExchangePattern.Pull,
                tobeForwarded: tobeForwarded);

            // Assert: if an OutMessage is created with the correct status and operation
            await PollUntilPresent(
                () => _databaseSpy.GetInMessageFor(m =>
                                                   m.EbmsMessageId == messageId &&
                                                   m.Operation == Operation.Forwarded),
                TimeSpan.FromSeconds(20));

            OutMessage outMessage = await PollUntilPresent(
                () => _databaseSpy.GetOutMessageFor(m => m.EbmsMessageId == messageId),
                TimeSpan.FromSeconds(5));

            var sendingPMode = AS4XmlSerializer.FromString <SendingProcessingMode>(outMessage.PMode);

            Assert.NotNull(sendingPMode);
            Assert.Equal(Operation.ToBeProcessed, outMessage.Operation);
            Assert.Equal(MessageExchangePattern.Push, outMessage.MEP);
            Assert.Equal(sendingPMode.MessagePackaging.Mpc, outMessage.Mpc);
        }
            public async Task ThenExecuteStepSucceedsAsync()
            {
                // Arrange
                AS4Message as4Message = await GetEncryptedAS4MessageAsync();

                var context = new MessagingContext(as4Message, MessagingContextMode.Receive)
                {
                    ReceivingPMode = new ReceivingProcessingMode
                    {
                        Security = { Decryption                        =
                                     {
                                         Encryption                    = Limit.Allowed,
                                         DecryptCertificateInformation = new CertificateFindCriteria
                                         {
                                             CertificateFindValue = "",
                                             CertificateFindType  = X509FindType.FindByIssuerName
                                         }
                                     } }
                    }
                };

                // Act
                StepResult stepResult = await ExerciseDecryption(context);

                // Assert
                Assert.False(stepResult.MessagingContext.AS4Message.IsEncrypted);
            }
예제 #18
0
        public async Task OutMessageIsCreatedForToBeForwardedMessage()
        {
            // Arrange
            const string messageId  = "message-id";
            var          as4Message = AS4Message.Create(CreateForwardPushUserMessage(messageId));

            // Act
            InsertToBeForwardedInMessage(
                pmodeId: "Forward_Push",
                mep: MessageExchangePattern.Push,
                tobeForwarded: as4Message);

            // Assert: if an OutMessage is created with the correct status and operation.
            InMessage inMessage = await PollUntilPresent(
                () => _databaseSpy.GetInMessageFor(
                    m => m.EbmsMessageId == messageId &&
                    m.Operation == Operation.Forwarded),
                TimeSpan.FromSeconds(15));

            Assert.NotNull(AS4XmlSerializer.FromString <ReceivingProcessingMode>(inMessage.PMode));

            OutMessage outMessage = await PollUntilPresent(
                () => _databaseSpy.GetOutMessageFor(m => m.EbmsMessageId == messageId),
                timeout : TimeSpan.FromSeconds(5));

            Assert.True(outMessage.Intermediary);
            Assert.Equal(Operation.ToBeProcessed, outMessage.Operation);
            Assert.NotNull(AS4XmlSerializer.FromString <SendingProcessingMode>(outMessage.PMode));
        }
            public async Task Takes_Sending_PMode_Into_Account_When_Verifies_Non_Multihop_Signal()
            {
                // Arrange
                var as4Msg = AS4Message.Create(new Receipt($"receipt-{Guid.NewGuid()}", $"reftoid-{Guid.NewGuid()}"));

                as4Msg.AddMessageUnit(new UserMessage(messageId: $"user-{Guid.NewGuid()}"));

                var ctx = new MessagingContext(as4Msg, MessagingContextMode.Receive)
                {
                    ReceivingPMode = new ReceivingProcessingMode
                    {
                        Security = { SigningVerification = { Signature = Limit.Required } }
                    },
                    SendingPMode = new SendingProcessingMode
                    {
                        Security = { SigningVerification = { Signature = Limit.Ignored } }
                    }
                };

                // Act
                StepResult result = await ExerciseVerify(ctx);

                // Assert
                Assert.True(result.CanProceed);
            }
예제 #20
0
        public async Task SignalMessage_Gets_Saved_As_Duplicate_When_InMessage_Exists_With_Same_EbmsRefToMessageId()
        {
            // Arrange
            string ebmsMessageId      = $"receipt-{Guid.NewGuid()}";
            string ebmsRefToMessageId = $"user-{Guid.NewGuid()}";

            GetDataStoreContext.InsertInMessage(
                new InMessage(ebmsMessageId)
            {
                EbmsRefToMessageId = ebmsRefToMessageId
            });

            var receipt = new Receipt(ebmsMessageId, ebmsRefToMessageId);
            var context = new MessagingContext(
                AS4Message.Create(receipt),
                new ReceivedMessage(Stream.Null),
                MessagingContextMode.Receive);

            // Act
            await Step.ExecuteAsync(context);

            // Assert
            InMessage actual = GetDataStoreContext.GetInMessage(
                m => m.EbmsMessageId == ebmsMessageId &&
                m.EbmsRefToMessageId == ebmsRefToMessageId &&
                m.IsDuplicate);

            Assert.True(actual != null, "Saved Receipt should be marked as duplicate");
        }
예제 #21
0
        private static async Task WriteAS4MessageToResponseAsync(AS4Message message, HttpListenerResponse response)
        {
            try
            {
                using (Stream responseStream = response.OutputStream)
                {
                    if (message.IsEmpty == false)
                    {
                        ISerializer serializer = SerializerProvider.Default.Get(message.ContentType);

                        await serializer.SerializeAsync(message, responseStream);
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Error($"An error occured while writing the Response to the ResponseStream: {exception.Message}");
                if (Logger.IsTraceEnabled)
                {
                    Logger.Trace(exception.StackTrace);
                }

                throw;
            }
        }
예제 #22
0
        public async Task ThenExecuteStepUpdatesDuplicateReceiptMessage()
        {
            // Arrange
            SignalMessage signalMessage = new Receipt($"receipt-{Guid.NewGuid()}", "ref-to-message-id");

            signalMessage.IsDuplicate = false;

            using (MessagingContext messagingContext =
                       CreateReceivedMessagingContext(AS4Message.Create(signalMessage), null))
            {
                // Act
                // Execute the step twice.
                StepResult stepResult = await Step.ExecuteAsync(messagingContext);

                Assert.False(stepResult.MessagingContext.AS4Message.FirstSignalMessage.IsDuplicate);
            }

            using (MessagingContext messagingContext =
                       CreateReceivedMessagingContext(AS4Message.Create(signalMessage), null))
            {
                StepResult stepResult = await Step.ExecuteAsync(messagingContext);

                // Assert
                Assert.True(stepResult.MessagingContext.AS4Message.FirstSignalMessage.IsDuplicate);
            }
        }
예제 #23
0
        /// <summary>
        /// Transform to a <see cref="MessagingContext" />
        /// with a <see cref="AS4Message" /> included
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task <MessagingContext> TransformAsync(ReceivedMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (message.UnderlyingStream == null)
            {
                throw new InvalidDataException(
                          $"The incoming stream from {message.Origin} is not an ebMS Message");
            }

            if (!ContentTypeSupporter.IsContentTypeSupported(message.ContentType))
            {
                throw new InvalidDataException(
                          $"ContentType {nameof(message.ContentType)} is not supported");
            }

            VirtualStream messageStream = await CopyIncomingStreamToVirtualStream(message);

            AS4Message as4Message = await DeserializeMessage(message.ContentType, messageStream, CancellationToken.None);

            return(new MessagingContext(as4Message, message, MessagingContextMode.Unknown));
        }
예제 #24
0
        public async Task Deliver_Message_Only_When_Referenced_Payloads_Are_Delivered()
        {
            AS4Message as4Message = await CreateAS4MessageFrom(deliveragent_message);

            string deliverLocation = DeliverPayloadLocationOf(as4Message.Attachments.First());

            CleanDirectoryAt(Path.GetDirectoryName(deliverLocation));

            // Act
            IPMode pmode = CreateReceivedPMode(
                deliverMessageLocation: DeliveryRoot,
                deliverPayloadLocation: @"%# \ (+_O) / -> Not a valid path");

            InMessage inMessage = CreateInMessageRepresentingUserMessage(as4Message.GetPrimaryMessageId(), as4Message, pmode);

            await InsertInMessageAsync(inMessage);

            // Assert
            var       spy    = DatabaseSpy.Create(_as4Msh.GetConfiguration());
            InMessage actual = await PollUntilPresent(
                () => spy.GetInMessageFor(im => im.Id == inMessage.Id && im.Status == InStatus.Exception.ToString()),
                TimeSpan.FromSeconds(10));

            Assert.Empty(Directory.EnumerateFiles(DeliveryRoot));
            Assert.Equal(InStatus.Exception, actual.Status.ToEnum <InStatus>());
            Assert.Equal(Operation.DeadLettered, actual.Operation);
        }
            public async Task ThenAgreementRefIsNotEnoughAsync(string name, string type)
            {
                // Arrange
                var agreementRef = new AS4.Model.PMode.AgreementReference {
                    Value = name, Type = type, PModeId = "pmode-id"
                };

                ArrangePModeThenAgreementRefIsNotEnough(agreementRef);

                var userMessage = new UserMessage(
                    Guid.NewGuid().ToString(),
                    new AS4.Model.Core.CollaborationInfo(
                        agreement: new AgreementReference(name, type, "pmode-id"),
                        service: new Service("service"),
                        action: "action",
                        conversationId: "1"));

                var messagingContext = new MessagingContext(AS4Message.Create(userMessage), MessagingContextMode.Receive);

                // Act
                StepResult result = await _step.ExecuteAsync(messagingContext);

                // Assert
                Assert.False(result.Succeeded);
                ErrorResult errorResult = result.MessagingContext.ErrorResult;

                Assert.Equal(ErrorCode.Ebms0010, errorResult.Code);
            }
        /// <summary>
        /// Execute the step for a given <paramref name="messagingContext" />.
        /// </summary>
        /// <param name="messagingContext">Message used during the step execution.</param>
        /// <returns></returns>
        public Task <StepResult> ExecuteAsync(MessagingContext messagingContext)
        {
            if (messagingContext == null)
            {
                throw new ArgumentNullException(nameof(messagingContext));
            }

            if (messagingContext.AS4Message == null)
            {
                throw new InvalidOperationException(
                          $"{nameof(VerifyPullRequestAuthorizationStep)} requires a MessagingContext with a AS4Message to verify the PullRequest");
            }

            AS4Message as4Message = messagingContext.AS4Message;

            var authorizationMap = new PullAuthorizationMapService(_pullAuthorizationMapProvider);

            if (authorizationMap.IsPullRequestAuthorized(as4Message))
            {
                return(StepResult.SuccessAsync(messagingContext));
            }

            string mpc = (as4Message.FirstSignalMessage as PullRequest)?.Mpc ?? string.Empty;

            throw new SecurityException(
                      $"{messagingContext.LogTag} PullRequest for MPC {mpc} is not authorized. " +
                      "Either change the PullRequest MPC or add the MPC value to the authorization map");
        }
        private async Task ExerciseLog(AS4Message as4Message, ErrorResult error)
        {
            var sut = new LogReceivedProcessingErrorStep(GetDataStoreContext);

            await sut.ExecuteAsync(
                new MessagingContext(as4Message, MessagingContextMode.Send) { ErrorResult = error });
        }
        private async Task <MessagingContext> InsertReceivedAS4MessageAsync(MessagingContext messagingContext)
        {
            using (DatastoreContext context = _createDatastoreContext())
            {
                MessageExchangePattern messageExchangePattern =
                    messagingContext.Mode == MessagingContextMode.PullReceive
                        ? MessageExchangePattern.Pull
                        : MessageExchangePattern.Push;

                try
                {
                    var        service    = new InMessageService(_config, new DatastoreRepository(context));
                    AS4Message as4Message = await service
                                            .InsertAS4MessageAsync(
                        messagingContext.AS4Message,
                        messagingContext.ReceivedMessage,
                        messagingContext.SendingPMode,
                        messageExchangePattern,
                        _messageBodyStore)
                                            .ConfigureAwait(false);

                    messagingContext.ModifyContext(as4Message);
                    await context.SaveChangesAsync().ConfigureAwait(false);

                    return(messagingContext);
                }
                catch (Exception ex)
                {
                    return(new MessagingContext(ex));
                }
            }
        }
        /// <summary>
        /// Asserts the party information.
        /// </summary>
        /// <param name="expected">The expected.</param>
        /// <param name="actual">The actual.</param>
        public static void AssertPartyInfo(AS4Message expected, MessageEntity actual)
        {
            Func <Party, string> getPartyId = p => p.PartyIds.First().Id;

            Assert.Equal(getPartyId(expected.FirstUserMessage.Sender), actual.FromParty);
            Assert.Equal(getPartyId(expected.FirstUserMessage.Receiver), actual.ToParty);
        }
예제 #30
0
        private async Task <AS4Message> ParseStreamToAS4MessageAsync(
            Stream inputStream,
            string contentType,
            CancellationToken cancellationToken)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException(nameof(inputStream));
            }

            List <MimePart> bodyParts      = TryParseBodyParts(inputStream, cancellationToken);
            Stream          envelopeStream = bodyParts.First().ContentObject?.Open();

            AS4Message message = await _soapSerializer
                                 .DeserializeAsync(envelopeStream, contentType, cancellationToken).ConfigureAwait(false);

            foreach (var userMessage in message.UserMessages)
            {
                IEnumerable <PartInfo> referencedPartInfos =
                    userMessage.PayloadInfo ?? Enumerable.Empty <PartInfo>();

                IEnumerable <Attachment> attachments = BodyPartsAsAttachments(bodyParts, referencedPartInfos);
                message.AddAttachments(attachments);
            }

            return(message);
        }