Пример #1
0
        public async Task ThenReceivedMultihopUserMessageIsSetAsIntermediaryAndForwarded()
        {
            // Arrange
            var userMessage = new UserMessage(
                "test-" + Guid.NewGuid(),
                new
                CollaborationInfo(
                    agreement: new AgreementReference(
                        value: "http://agreements.europa.org/agreement",
                        pmodeId: "Forward_Push_Multihop"),
                    service: new Service(
                        value: "Forward_Push_Multihop_Service",
                        type: "eu:europa:services"),
                    action: "Forward_Push_Multihop_Action",
                    conversationId: "eu:europe:conversation"));
            var multihopPMode = new SendingProcessingMode {
                MessagePackaging = { IsMultiHop = true }
            };
            AS4Message multihopMessage = AS4Message.Create(userMessage, multihopPMode);

            // Act
            HttpResponseMessage response = await StubSender.SendAS4Message(_receiveAgentUrl, multihopMessage);

            // Assert
            Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

            InMessage inUserMessage = _databaseSpy.GetInMessageFor(m => m.EbmsMessageId == userMessage.MessageId);

            Assert.NotNull(inUserMessage);
            Assert.True(inUserMessage.Intermediary);
            Assert.Equal(Operation.ToBeForwarded, inUserMessage.Operation);
        }
            public Property Then_Service_Has_Only_Type_When_Defined(
                Guid value,
                Maybe <Guid> type)
            {
                // Arrange
                var user = new UserMessage(
                    $"user-{Guid.NewGuid()}",
                    new AS4.Model.Core.CollaborationInfo(
                        agreement: new AgreementReference("agreement"),
                        service: new Service(
                            value.ToString(),
                            type.Select(t => t.ToString())),
                        action: "action",
                        conversationId: "conversation"));

                // Act
                XmlDocument doc = SerializeSoapMessage(AS4Message.Create(user));

                // Assert
                XmlNode serviceNode = doc.UnsafeSelectEbmsNode(
                    "/s12:Envelope/s12:Header/eb:Messaging/eb:UserMessage/eb:CollaborationInfo/eb:Service");

                XmlAttribute serviceTypeAttr = serviceNode?.Attributes?["type"];

                return((serviceNode?.FirstChild?.Value == value.ToString())
                       .Label("Equal value")
                       .And(serviceTypeAttr == null && type == Maybe <Guid> .Nothing)
                       .Label("No service type present")
                       .Or(type.Select(t => t.ToString() == serviceTypeAttr?.Value).GetOrElse(false))
                       .Label("Equal service type"));
            }
Пример #3
0
        public async Task ReturnsErrorMessageWhenDecryptionCertificateCannotBeFound()
        {
            var userMessage = new UserMessage(
                Guid.NewGuid().ToString(),
                new CollaborationInfo(
                    agreement: new AgreementReference(
                        value: "http://agreements.europa.org/agreement",
                        pmodeId: "receiveagent-non_existing_decrypt_cert-pmode"),
                    service: new Service(
                        value: "errorhandling",
                        type: "as4.net:receive_agent:componenttest"),
                    action: "as4.net:receive_agent:decryption_failed",
                    conversationId: "as4.net:receive_agent:conversation"));

            var as4Message = CreateAS4MessageWithAttachment(userMessage);

            var encryptedMessage = AS4MessageUtils.EncryptWithCertificate(as4Message, new StubCertificateRepository().GetStubCertificate());

            // Act
            HttpResponseMessage response = await StubSender.SendAS4Message(_receiveAgentUrl, encryptedMessage);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var contentType = response.Content.Headers.ContentType.MediaType;
            var result      = await SerializerProvider.Default.Get(contentType)
                              .DeserializeAsync(await response.Content.ReadAsStreamAsync(), contentType);

            Assert.True(result.IsSignalMessage);

            var errorMessage = result.FirstSignalMessage as Error;

            Assert.NotNull(errorMessage);
            Assert.Equal(ErrorCode.Ebms0102, errorMessage.ErrorLines.First().ErrorCode);
        }
        private static Receipt CreateReceiptWithRelatedUserMessageInfo()
        {
            string ebmsMessageId = $"user-{Guid.NewGuid()}";
            var    userMessage   = new UserMessage(ebmsMessageId);

            return(Receipt.CreateFor($"receipt-{Guid.NewGuid()}", userMessage));
        }
Пример #5
0
        private static AS4Message CreateAS4MessageWithAttachment(UserMessage msg)
        {
            var as4Message = AS4Message.Create(msg);

            // Arrange
            byte[] attachmentContents = Encoding.UTF8.GetBytes("some random attachment");
            var    attachment         = new Attachment("attachment-id", new MemoryStream(attachmentContents), "text/plain");

            as4Message.AddAttachment(attachment);

            return(as4Message);
        }
            public async void ThenParseUserMessageSenderCorrectly()
            {
                using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(Samples.UserMessage)))
                {
                    // Act
                    AS4Message message = await DeserializeAsSoap(memoryStream);

                    // Assert
                    UserMessage userMessage = message.UserMessages.First();
                    Assert.Equal("org:eu:europa:as4:example", userMessage.Sender.PartyIds.First().Id);
                    Assert.Equal("Sender", userMessage.Sender.Role);
                }
            }
            public async void ThenParseUserMessageReceiverCorrectly()
            {
                using (var memoryStream = new MemoryStream(Encoding.UTF32.GetBytes(Samples.UserMessage)))
                {
                    // Act
                    AS4Message message = await DeserializeAsSoap(memoryStream);

                    // Assert
                    UserMessage userMessage = message.UserMessages.First();
                    string      receiverId  = userMessage.Receiver.PartyIds.First().Id;
                    Assert.Equal("org:holodeckb2b:example:company:B", receiverId);
                    Assert.Equal("Receiver", userMessage.Receiver.Role);
                }
            }
Пример #8
0
        private async Task CorrectHandlingOnSynchronouslyReceivedMultiHopReceipt(
            bool actAsIntermediaryMsh,
            string receivePModeId,
            OutStatus expectedOutStatus,
            Operation expectedSignalOperation)
        {
            // Arrange
            SendingProcessingMode pmode             = CreateMultihopPMode(StubListenLocation);
            UserMessage           simpleUserMessage = CreateMultihopUserMessage(receivePModeId, pmode);

            AS4Message as4Message = AS4Message.Create(simpleUserMessage, pmode);

            var signal     = new ManualResetEvent(false);
            var serializer = new SoapEnvelopeSerializer();

            StubHttpServer.StartServer(
                StubListenLocation,
                res =>
            {
                res.StatusCode  = 200;
                res.ContentType = Constants.ContentTypes.Soap;

                var receipt = Receipt.CreateFor(
                    $"receipt-{Guid.NewGuid()}",
                    as4Message.FirstUserMessage,
                    userMessageSendViaMultiHop: true);

                serializer.Serialize(AS4Message.Create(receipt), res.OutputStream);
            },
                signal);

            // Act
            PutMessageToSend(as4Message, pmode, actAsIntermediaryMsh);

            // Assert
            signal.WaitOne();

            OutMessage sentMessage = await PollUntilPresent(
                () => _databaseSpy.GetOutMessageFor(m => m.EbmsMessageId == simpleUserMessage.MessageId),
                timeout : TimeSpan.FromSeconds(10));

            Assert.Equal(expectedOutStatus, sentMessage.Status.ToEnum <OutStatus>());

            InMessage receivedMessage = await PollUntilPresent(
                () => _databaseSpy.GetInMessageFor(m => m.EbmsRefToMessageId == simpleUserMessage.MessageId),
                timeout : TimeSpan.FromSeconds(10));

            Assert.Equal(MessageType.Receipt, receivedMessage.EbmsMessageType);
            Assert.Equal(expectedSignalOperation, receivedMessage.Operation);
        }
            public async void ThenParseUserMessageCollaborationInfoCorrectly()
            {
                using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(Samples.UserMessage)))
                {
                    // Act
                    AS4Message message = await DeserializeAsSoap(memoryStream);

                    // Assert
                    UserMessage userMessage = message.UserMessages.First();
                    Assert.Equal(ServiceNamespace, userMessage.CollaborationInfo.Service.Value);
                    Assert.Equal(ActionNamespace, userMessage.CollaborationInfo.Action);
                    Assert.Equal("eu:edelivery:as4:sampleconversation", userMessage.CollaborationInfo.ConversationId);
                }
            }
            public async Task ThenParseUserMessagePropertiesParsedCorrectlyAsync()
            {
                using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(Samples.UserMessage)))
                {
                    // Act
                    AS4Message message = await DeserializeAsSoap(memoryStream);

                    // Assert
                    UserMessage userMessage = message.UserMessages.First();
                    Assert.NotNull(message);
                    Assert.Single(message.UserMessages);
                    Assert.Equal(1472800326948, userMessage.Timestamp.ToUnixTimeMilliseconds());
                }
            }
Пример #11
0
        /// <summary>
        /// Start determine the Receiving Processing Mode
        /// </summary>
        /// <param name="messagingContext"></param>
        /// <returns></returns>
        public async Task <StepResult> ExecuteAsync(MessagingContext messagingContext)
        {
            if (messagingContext == null)
            {
                throw new ArgumentNullException(nameof(messagingContext));
            }

            if (messagingContext.AS4Message == null)
            {
                throw new InvalidOperationException(
                          $"{nameof(DeterminePModesStep)} requires an AS4Message but no AS4Message is present in the MessagingContext");
            }

            AS4Message as4Message = messagingContext.AS4Message;
            bool       containsSignalThatNotPullRequest = as4Message.SignalMessages.Any(s => !(s is Model.Core.PullRequest));

            if (containsSignalThatNotPullRequest && (as4Message.IsMultiHopMessage || messagingContext.SendingPMode == null))
            {
                messagingContext.SendingPMode = await DetermineSendingPModeForSignalMessageAsync(as4Message);
            }

            if (messagingContext.ReceivingPMode != null)
            {
                Logger.Debug(
                    $"Will not determine ReceivingPMode: incoming message has already a ReceivingPMode: {messagingContext.ReceivingPMode.Id} configured. "
                    + $"{Environment.NewLine} This happens when the Receive Agent is configured as a \"Static Receive Agent\"");
            }
            else if (as4Message.HasUserMessage || as4Message.SignalMessages.Any(s => s.IsMultihopSignal))
            {
                Logger.Trace("Incoming message hasn't yet a ReceivingPMode, will determine one");
                UserMessage userMessage = GetUserMessageFromFirstMessageUnitOrRoutingInput(messagingContext.AS4Message);
                IEnumerable <ReceivePMode> possibilities = GetMatchingReceivingPModeForUserMessage(userMessage);

                if (possibilities.Any() == false)
                {
                    return(NoMatchingPModeFoundFailure(messagingContext));
                }

                if (possibilities.Count() > 1)
                {
                    return(TooManyPossibilitiesFailure(messagingContext, possibilities));
                }

                ReceivePMode pmode = possibilities.First();
                Logger.Info($"Found ReceivingPMode \"{pmode.Id}\" to further process the incoming message");
                messagingContext.ReceivingPMode = pmode;
            }

            return(StepResult.Success(messagingContext));
        }
            public void ThenSerializeWithoutAttachmentsReturnsSoapMessage(Guid mpc)
            {
                // Act
                UserMessage userMessage = CreateUserMessage();
                AS4Message  message     = BuildAS4Message(mpc.ToString(), userMessage);

                using (var soapStream = new MemoryStream())
                {
                    XmlDocument document        = SerializeSoapMessage(message, soapStream);
                    XmlNode     envelopeElement = document.DocumentElement;

                    // Assert
                    Assert.NotNull(envelopeElement);
                    Assert.Equal(Constants.Namespaces.Soap12, envelopeElement.NamespaceURI);
                }
            }
            public void ThenSaveToUserMessageCorrectlySerialized()
            {
                // Arrange
                UserMessage userMessage = CreateUserMessage();
                AS4Message  message     = AS4Message.Create(userMessage);

                // Act
                using (var soapStream = new MemoryStream())
                {
                    XmlDocument document = SerializeSoapMessage(message, soapStream);

                    // Assert
                    Assert.NotNull(document.DocumentElement);
                    Assert.Contains("Envelope", document.DocumentElement.Name);
                }
            }
            public Property Then_AgreementReference_Is_Present_When_Defined(
                Maybe <Guid> value,
                Maybe <Guid> type)
            {
                // Arrange
                var a = value.Select(x =>
                                     new AgreementReference(
                                         value: x.ToString(),
                                         type: type.Select(t => t.ToString()),
                                         pmodeId: Maybe <string> .Nothing));

                var user = new UserMessage(
                    $"user-{Guid.NewGuid()}",
                    new AS4.Model.Core.CollaborationInfo(
                        a, Service.TestService, Constants.Namespaces.TestAction, "1"));

                // Act
                XmlDocument doc = SerializeSoapMessage(AS4Message.Create(user));

                // Assert
                XmlNode agreementNode = doc.UnsafeSelectEbmsNode(
                    "/s12:Envelope/s12:Header/eb:Messaging/eb:UserMessage/eb:CollaborationInfo/eb:AgreementRef");

                XmlAttribute agreementTypeAttr = agreementNode?.Attributes?["type"];

                Property noAgreementTagProp =
                    (agreementNode == null && value == Maybe <Guid> .Nothing)
                    .Label("No agreement tag");

                Property equalValueProp =
                    value.Select(v => v.ToString() == agreementNode?.InnerText)
                    .GetOrElse(false)
                    .Label("Equal agreement value");

                Property noTypeProp =
                    (agreementTypeAttr == null && type == Maybe <Guid> .Nothing)
                    .Label("No agreement type");

                Property equalTypeProp =
                    type.Select(t => t.ToString() == agreementTypeAttr?.Value)
                    .GetOrElse(false)
                    .Label("Equal agreement type");

                return(noAgreementTagProp.Or(equalValueProp.And(noTypeProp).Or(equalTypeProp)));
            }
Пример #15
0
        private IEnumerable <ReceivePMode> GetMatchingReceivingPModeForUserMessage(UserMessage userMessage)
        {
            IEnumerable <PModeParticipant> participants =
                _config.GetReceivingPModes()
                .Select(pmode => new PModeParticipant(pmode, userMessage))
                .Select(PModeRuleEngine.ApplyRules);

            IEnumerable <int> scoresToConsider = participants.Select(p => p.Points).Where(p => p >= 10);

            if (scoresToConsider.Any() == false)
            {
                return(Enumerable.Empty <ReceivePMode>());
            }

            int maxPoints = scoresToConsider.Max();

            return(participants.Where(p => p.Points == maxPoints).Select(p => p.PMode));
        }
            public void ThenPullRequestCorrectlySerialized(Guid mpc)
            {
                // Arrange
                UserMessage userMessage = CreateUserMessage();

                AS4Message message = BuildAS4Message(mpc.ToString(), userMessage);

                // Act
                using (var soapStream = new MemoryStream())
                {
                    XmlDocument document = SerializeSoapMessage(message, soapStream);

                    // Assert
                    XmlAttribute mpcAttribute = GetMpcAttribute(document);
                    Assert.NotNull(mpcAttribute);
                    Assert.Equal(mpc.ToString(), mpcAttribute.Value);
                }
            }
            public void Then_PayloadInfo_Is_Present_When_Defined()
            {
                // Arrange
                var user = new UserMessage(
                    $"user-{Guid.NewGuid()}",
                    new AS4.Model.Core.PartInfo("cid:earth"));

                // Act
                XmlDocument doc = SerializeSoapMessage(AS4Message.Create(user));

                // Assert
                XmlNode payloadInfoTag = doc.UnsafeSelectEbmsNode(
                    "/s12:Envelope/s12:Header/eb:Messaging/eb:UserMessage/eb:PayloadInfo");

                Assert.NotNull(payloadInfoTag);
                XmlNode partInfoTag = payloadInfoTag.FirstChild;

                Assert.Equal("cid:earth", partInfoTag.Attributes?["href"]?.Value);
            }
        private static void AssertIfSenderAndReceiverAreReversed(AS4Message expectedAS4Message, XmlNode doc)
        {
            XmlNode routingInputNode = doc.UnsafeSelectEbmsNode("/s12:Envelope/s12:Header/mh:RoutingInput");

            Assert.NotNull(routingInputNode);
            var routingInput = AS4XmlSerializer.FromString <RoutingInput>(routingInputNode.OuterXml);

            RoutingInputUserMessage actualUserMessage   = routingInput.UserMessage;
            UserMessage             expectedUserMessage = expectedAS4Message.FirstUserMessage;

            Assert.Equal(expectedUserMessage.Sender.Role, actualUserMessage.PartyInfo.To.Role);
            Assert.Equal(
                expectedUserMessage.Sender.PartyIds.First().Id,
                actualUserMessage.PartyInfo.To.PartyId.First().Value);
            Assert.Equal(expectedUserMessage.Receiver.Role, actualUserMessage.PartyInfo.From.Role);
            Assert.Equal(
                expectedUserMessage.Receiver.PartyIds.First().Id,
                actualUserMessage.PartyInfo.From.PartyId.First().Value);
        }
Пример #19
0
        private static SignalMessage CreateMultihopSignalMessage(string refToMessageId, string pmodeId)
        {
            var userMessage = new UserMessage(
                refToMessageId,
                "some-mpc",
                new CollaborationInfo(
                    new AgreementReference("http://agreements.europa.org/agreement", pmodeId),
                    new Service("Forward_Push_Service", "eu:europe:services"),
                    "Forward_Push_Action",
                    CollaborationInfo.DefaultConversationId),
                new Party("Sender", new PartyId("org:eu:europa:as4:example:accesspoint:A")),
                new Party("Receiver", new PartyId("org:eu:europa:as4:example:accesspoint:B")),
                new PartInfo[0],
                new MessageProperty[0]);

            return(Receipt.CreateFor(
                       $"receipt-{Guid.NewGuid()}",
                       userMessage,
                       userMessageSendViaMultiHop: true));
        }
            public void ThenMpcAttributeIsCorrectlySerialized()
            {
                var userMessage = new UserMessage("some-message-id", "the-specified-mpc");
                var as4Message  = AS4Message.Create(userMessage);

                using (var messageStream = new MemoryStream())
                {
                    var sut = new SoapEnvelopeSerializer();

                    // Act
                    sut.Serialize(as4Message, messageStream);

                    // Assert
                    messageStream.Position = 0;
                    var xmlDocument = new XmlDocument();
                    xmlDocument.Load(messageStream);

                    var userMessageNode = xmlDocument.SelectSingleNode("//*[local-name()='UserMessage']");
                    Assert.NotNull(userMessageNode);
                    Assert.Equal(userMessage.Mpc, userMessageNode.Attributes["mpc"].InnerText);
                }
            }
Пример #21
0
        public async Task ThenReceivedMultihopUserMessageIsntSetToIntermediaryButDeliveredWithCorrespondingSentReceipt()
        {
            // Arrange
            var userMessage = new UserMessage(
                "test-" + Guid.NewGuid(),
                new CollaborationInfo(
                    agreement: new AgreementReference(
                        value: "http://agreements.europa.org/agreement",
                        pmodeId: "ComponentTest_ReceiveAgent_Sample1"),
                    service: new Model.Core.Service(
                        value: "getting:started",
                        type: "eu:europa:services"),
                    action: "eu:sample:01",
                    conversationId: "eu:europa:conversation"));
            var multihopPMode = new SendingProcessingMode {
                MessagePackaging = { IsMultiHop = true }
            };
            AS4Message multihopMessage = AS4Message.Create(userMessage, multihopPMode);

            // Act
            HttpResponseMessage response = await StubSender.SendAS4Message(_receiveAgentUrl, multihopMessage);

            // Assert
            AS4Message responseReceipt = await response.DeserializeToAS4Message();

            AssertMessageMultihopAttributes(responseReceipt.EnvelopeDocument);
            Assert.True(responseReceipt.IsMultiHopMessage);

            InMessage inUserMessage = _databaseSpy.GetInMessageFor(m => m.EbmsMessageId == userMessage.MessageId);

            Assert.NotNull(inUserMessage);
            Assert.False(inUserMessage.Intermediary);
            Assert.Equal(Operation.ToBeDelivered, inUserMessage.Operation);

            OutMessage outReceipt = _databaseSpy.GetOutMessageFor(m => m.EbmsRefToMessageId == userMessage.MessageId);

            Assert.Equal(OutStatus.Sent, outReceipt.Status.ToEnum <OutStatus>());
        }
            public void Bundled_UserMessage_With_Signal_Gets_Decompressed(SignalMessage signal)
            {
                // Arrange
                string      attachmentId = $"attachment-{Guid.NewGuid()}";
                UserMessage user         = UserMessageWithCompressedInfo(attachmentId);
                Attachment  attachment   = CompressedAttachment(attachmentId);
                AS4Message  as4Message   = AS4Message.Create(user);

                as4Message.AddMessageUnit(signal);
                as4Message.AddAttachment(attachment);

                // 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));
            }
Пример #23
0
        public async Task Received_Bundled_User_And_Receipt_Message_Should_Process_All_Messages()
        {
            // Arrange
            string ebmsMessageId = "test-" + Guid.NewGuid();

            StoreToBeAckOutMessage(ebmsMessageId, CreateSendingPMode());

            var userMessage = new UserMessage(
                "usermessage-" + Guid.NewGuid(),
                new CollaborationInfo(
                    agreement: new AgreementReference(
                        value: "http://agreements.europa.org/agreement",
                        pmodeId: "receive_bundled_message_pmode"),
                    service: new Service(
                        value: "bundling",
                        type: "as4.net:receive_agent:componenttest"),
                    action: "as4.net:receive_agent:bundling",
                    conversationId: "as4.net:receive_agent:conversation"));

            var receipt = new Receipt($"receipt-{Guid.NewGuid()}", ebmsMessageId);

            var bundled = AS4Message.Create(userMessage);

            bundled.AddMessageUnit(receipt);

            // Act
            HttpResponseMessage response = await StubSender.SendAS4Message(_receiveAgentUrl, bundled);

            // Assert
            AS4Message receivedReceipt = await response.DeserializeToAS4Message();

            Assert.IsType <Receipt>(receivedReceipt.FirstSignalMessage);
            Assert.Equal(userMessage.MessageId, receivedReceipt.FirstSignalMessage.RefToMessageId);

            AssertIfInMessageExistsForSignalMessage(ebmsMessageId);
            AssertIfInMessageIsStoredFor(userMessage.MessageId, Operation.ToBeDelivered);
        }
Пример #24
0
        public async Task ThenInMessageSignalIsStoredWithPModeUrl()
        {
            // Arrange
            var userMessage = new UserMessage(
                $"user-{Guid.NewGuid()}",
                new CollaborationInfo(
                    new AgreementReference(
                        "http://eu.europe.agreements",
                        "callback-pmode")));

            // Act
            await StubSender.SendAS4Message(_receiveAgentUrl, AS4Message.Create(userMessage));

            // Assert
            OutMessage storedReceipt =
                await PollUntilPresent(
                    () => _databaseSpy.GetOutMessageFor(m => m.EbmsRefToMessageId == userMessage.MessageId &&
                                                        m.EbmsMessageType == MessageType.Receipt),
                    timeout : TimeSpan.FromSeconds(20));

            ReceivingProcessingMode pmode = _as4Msh.GetConfiguration().GetReceivingPModes().First(p => p.Id == "callback-pmode");

            Assert.Equal(pmode.ReplyHandling.ResponseConfiguration.Protocol.Url, storedReceipt.Url);
        }