public void Decorate_Not_Recreate_CollaborationInfo()
        {
            // Arrange
            var smpResponse   = new SmpConfiguration();
            var collaboration = new CollaborationInfo
            {
                AgreementReference = new AgreementReference
                {
                    Value = "http://eu.europe.org/agreements"
                }
            };

            var fixture = new SendingProcessingMode
            {
                MessagePackaging = new SendMessagePackaging
                {
                    CollaborationInfo = collaboration
                }
            };

            // Act
            SendingProcessingMode result = ExerciseDecorate(fixture, smpResponse);

            // Assert
            Assert.Same(collaboration, result.MessagePackaging.CollaborationInfo);
            Assert.Equal(
                collaboration.AgreementReference.Value,
                result.MessagePackaging.CollaborationInfo.AgreementReference.Value);
        }
Пример #2
0
        public void CanCloneSendingProcessingMode()
        {
            var pmode = new SendingProcessingMode()
            {
                Id       = "CloneableTest",
                Security = new AS4.Model.PMode.Security()
                {
                    Encryption = new Encryption
                    {
                        IsEnabled = true,
                        EncryptionCertificateInformation = new PublicKeyCertificate()
                        {
                            Certificate = "ABCDEFGH"
                        },
                        CertificateType = PublicKeyCertificateChoiceType.PublicKeyCertificate
                    }
                }
            };

            var clone = pmode.Clone() as SendingProcessingMode;

            Assert.NotNull(clone);

            Assert.Equal(pmode.Id, clone.Id);
            Assert.Equal(pmode.Security.Encryption.IsEnabled, clone.Security.Encryption.IsEnabled);
            Assert.Equal("ABCDEFGH", ((PublicKeyCertificate)clone.Security.Encryption.EncryptionCertificateInformation).Certificate);
        }
        /// <summary>
        /// Complete the <paramref name="pmode" /> with the SMP metadata that is present in the <paramref name="smpMetaData" />
        /// <see cref="XmlDocument" />
        /// </summary>
        /// <param name="pmode">The <see cref="SendingProcessingMode" /> that must be decorated with the SMP metadata</param>
        /// <param name="smpMetaData">An XmlDocument that contains the SMP MetaData that has been received from an SMP server.</param>
        /// <returns>The completed <see cref="SendingProcessingMode" /></returns>
        public DynamicDiscoveryResult DecoratePModeWithSmpMetaData(SendingProcessingMode pmode, XmlDocument smpMetaData)
        {
            if (pmode == null)
            {
                throw new ArgumentNullException(nameof(pmode));
            }

            if (smpMetaData == null)
            {
                throw new ArgumentNullException(nameof(smpMetaData));
            }

            var smpResponse = AS4XmlSerializer.FromString <SmpConfiguration>(smpMetaData.OuterXml);

            if (smpResponse == null)
            {
                throw new ArgumentNullException(
                          nameof(smpResponse),
                          $@"SMP Response cannot be deserialized correctly to a SmpConfiguration model: {smpMetaData.OuterXml}");
            }

            OverridePushProtocolUrlWithTlsEnabling(pmode, smpResponse);
            OverrideEntireEncryption(pmode, smpResponse);
            OverrideToParty(pmode, smpResponse);
            OverrideCollaborationServiceAction(pmode, smpResponse);
            AddFinalRecipientToMessageProperties(pmode, smpResponse);

            return(DynamicDiscoveryResult.Create(pmode));
        }
        private static void OverrideCollaborationAction(SendingProcessingMode pmode, XmlDocument smpMetaData, XmlNamespaceManager ns)
        {
            XmlNode documentIdentifierNode = smpMetaData.SelectSingleNode("//oasis:ServiceInformation/oasis:DocumentIdentifier", ns);

            if (documentIdentifierNode == null)
            {
                throw new InvalidDataException(
                          "No <DocumentIdentifier/> element in an <ServiceInformation/> element found in SMP meta-data to complete ebMS Action");
            }

            string documentScheme =
                documentIdentifierNode.Attributes
                ?.OfType <XmlAttribute>()
                .FirstOrDefault(a => a.Name.Equals("scheme", StringComparison.OrdinalIgnoreCase))
                ?.Value;

            if (String.IsNullOrEmpty(documentScheme))
            {
                throw new InvalidDataException(
                          "No 'scheme' XML attribute found in <DocumentIdentifier/> element in SMP meta-data to complete ebMS Action");
            }

            string action = $"{documentScheme}::{documentIdentifierNode.InnerText}";

            Logger.Trace($"Override SendingPMode.MessagePackaging.CollaborationInfo.Action with {action}");

            pmode.MessagePackaging = pmode.MessagePackaging ?? new SendMessagePackaging();
            pmode.MessagePackaging.CollaborationInfo        = pmode.MessagePackaging.CollaborationInfo ?? new CollaborationInfo();
            pmode.MessagePackaging.CollaborationInfo.Action = action;
        }
        private static void OverrideToParty(SendingProcessingMode pmode, string certificateBinaries)
        {
            const string defaultResponderRole = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/responder";
            const string defaultUrnTypeValue  = "urn:oasis:names:tc:ebcore:partyid-type:unregistered";

            var encryptionCertificate =
                new X509Certificate2(
                    rawData: Convert.FromBase64String(certificateBinaries),
                    password: (string)null);
            string commonName = encryptionCertificate.GetNameInfo(X509NameType.SimpleName, forIssuer: false);

            Logger.Trace(
                "Override SendingPMode.MessagingPackaging.PartyInfo.ToParty with "
                + $"{{Role={defaultResponderRole}, PartyId={commonName}, PartyIdType={defaultUrnTypeValue}}}");

            pmode.MessagePackaging                   = pmode.MessagePackaging ?? new SendMessagePackaging();
            pmode.MessagePackaging.PartyInfo         = pmode.MessagePackaging.PartyInfo ?? new PartyInfo();
            pmode.MessagePackaging.PartyInfo.ToParty = new Model.PMode.Party
            {
                Role     = defaultResponderRole,
                PartyIds = new List <PartyId>
                {
                    new PartyId {
                        Id = commonName, Type = defaultUrnTypeValue
                    }
                }
            };
        }
Пример #6
0
        public void Use_Submit_MessageProperties_When_SendingPMode_MessageProperties_Are_Empty()
        {
            // Arrange
            var submit = new SubmitMessage
            {
                MessageProperties = new[]
                {
                    new AS4.Model.Common.MessageProperty {
                        Name = "originalSender", Type = "Important", Value = "Holodeck"
                    },
                    new AS4.Model.Common.MessageProperty {
                        Name = "finalRecipient", Value = "AS4.NET"
                    },
                }
            };
            var sendingPMode = new SendingProcessingMode
            {
                MessagePackaging =
                {
                    MessageProperties = null
                }
            };

            // Act
            UserMessage result = SubmitMessageMap.CreateUserMessage(submit, sendingPMode);

            // Assert
            Assert.Collection(
                result.MessageProperties,
                p => Assert.Equal(("originalSender", "Important", "Holodeck"), (p.Name, p.Type, p.Value)),
                p => Assert.Equal(("finalRecipient", "AS4.NET"), (p.Name, p.Value)));
        }
            public async Task SendingPModeWithTlsConfiguration()
            {
                var expected = new ClientCertificateReference
                {
                    ClientCertificateFindType  = X509FindType.FindBySubjectName,
                    ClientCertificateFindValue = "subject"
                };
                var before = new SendingProcessingMode
                {
                    PushConfiguration = new PushConfiguration
                    {
                        TlsConfiguration =
                        {
                            IsEnabled                    = true,
                            ClientCertificateInformation = expected
                        }
                    }
                };

                SendingProcessingMode after = await ExerciseSerializeDeserialize(before);

                var actual = after.PushConfiguration.TlsConfiguration.ClientCertificateInformation as ClientCertificateReference;

                Assert.NotNull(actual);
                Assert.Equal(expected.ClientCertificateFindType, actual.ClientCertificateFindType);
                Assert.Equal(expected.ClientCertificateFindValue, actual.ClientCertificateFindValue);
            }
        private static Method GetNotifyMethodBasedOnNotifyMessage(
            NotifyMessageEnvelope notifyMessage,
            SendingProcessingMode sendingPMode,
            ReceivingProcessingMode receivingPMode)
        {
            switch (notifyMessage.StatusCode)
            {
            case Status.Delivered:
                if (sendingPMode.ReceiptHandling?.NotifyMethod?.Type == null)
                {
                    throw new InvalidOperationException(
                              $"SendingPMode {sendingPMode.Id} should have a ReceiptHandling.NotifyMethod "
                              + "with a <Type/> element indicating the notifying strategy when the NotifyMessage.StatusCode = Delivered. "
                              + "Default strategies are: 'FILE' and 'HTTP'. See 'Notify Uploading' for more information");
                }

                return(sendingPMode.ReceiptHandling.NotifyMethod);

            case Status.Error:
                if (sendingPMode.ErrorHandling?.NotifyMethod?.Type == null)
                {
                    throw new InvalidOperationException(
                              $"SendingPMode {sendingPMode.Id} should have a ErrorHandling.NotifyMethod "
                              + "with a <Type/> element indicating the notifying strategy when the NotifyMessage.StatusCode = Error. "
                              + "Default strategies are: 'FILE' and 'HTTP'. See 'Notify Uploading' for more information");
                }

                return(sendingPMode.ErrorHandling.NotifyMethod);

            case Status.Exception:
                bool isNotifyMessageFormedBySending = sendingPMode?.Id != null;
                if (isNotifyMessageFormedBySending)
                {
                    if (sendingPMode?.ExceptionHandling?.NotifyMethod?.Type == null)
                    {
                        throw new InvalidOperationException(
                                  $"SendingPMode {sendingPMode.Id} should have a ExceptionHandling.NotifyMethod "
                                  + "with a <Type/> element indicating the notifying strategy when the NotifyMessage.StatusCode = Exception. "
                                  + "This means that the NotifyMessage is an Exception occured during a outbound sending operation. "
                                  + "Default strategies are: 'FILE' and 'HTTP'. See 'Notify Uploading' for more information");
                    }

                    return(sendingPMode.ExceptionHandling.NotifyMethod);
                }

                if (receivingPMode?.ExceptionHandling?.NotifyMethod?.Type == null)
                {
                    throw new InvalidOperationException(
                              $"ReceivingPMode {receivingPMode?.Id} should have a ExceptionHandling.NotifyMethod "
                              + "with a <Type/> element indicating the notifying strategy when the NotifyMessage.StatusCode = Exception. "
                              + "This means that the NotifyMessage is an Exception occured during an inbound receiving operation. "
                              + "Default strategies are: 'FILE' and 'HTTP'. See 'Notify Uploading' for more information");
                }

                return(receivingPMode.ExceptionHandling.NotifyMethod);

            default:
                throw new ArgumentOutOfRangeException($"No NotifyMethod not defined for status {notifyMessage.StatusCode}");
            }
        }
        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);
        }
        /// <summary>
        /// Complete the <paramref name="pmode"/> with the SMP metadata that is present in the <paramref name="smpMetaData"/> <see cref="XmlDocument"/>
        /// </summary>
        /// <param name="pmode"></param>
        /// <param name="smpMetaData"></param>
        /// <returns></returns>
        public DynamicDiscoveryResult DecoratePModeWithSmpMetaData(SendingProcessingMode pmode, XmlDocument smpMetaData)
        {
            if (pmode == null)
            {
                throw new ArgumentNullException(nameof(pmode));
            }

            if (smpMetaData == null)
            {
                throw new ArgumentNullException(nameof(smpMetaData));
            }

            XmlNode endpoint        = SelectServiceEndpointNode(smpMetaData);
            XmlNode certificateNode = endpoint.SelectSingleNode("*[local-name()='Certificate']");

            Logger.Debug($"Decorate SendingPMode {pmode.Id} with SMP response from ESens SMP Server");

            OverwritePushProtocolUrl(pmode, endpoint);
            DecorateMessageProperties(pmode, smpMetaData);
            OverwriteCollaborationServiceAction(pmode, smpMetaData);

            if (certificateNode != null)
            {
                OverwriteToParty(pmode, certificateNode);
                OverwriteEncryptionCertificate(pmode, certificateNode);
            }
            else
            {
                Logger.Trace("Don't override MessagePackaging.PartyInfo.ToParty because no <Certificate/> element found in SMP response");
                Logger.Trace("Don't override Encryption Certificate because no <Certificate/> element found in SMP response");
            }

            // TODO: should we specify to override the ToParty here also?
            return(DynamicDiscoveryResult.Create(pmode));
        }
 private static void OverwriteCollaborationServiceAction(SendingProcessingMode pmode, XmlDocument smpMetaData)
 {
     pmode.MessagePackaging = pmode.MessagePackaging ?? new SendMessagePackaging();
     pmode.MessagePackaging.CollaborationInfo         = pmode.MessagePackaging.CollaborationInfo ?? new CollaborationInfo();
     pmode.MessagePackaging.CollaborationInfo.Action  = SelectCollaborationAction(smpMetaData);
     pmode.MessagePackaging.CollaborationInfo.Service = SelectCollaborationService(smpMetaData);
 }
Пример #12
0
        /// <summary>
        /// Start creating a <see cref="AS4Message" />
        /// </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(CreateDefaultAS4MessageStep)} requires an AS4Message to assign the default UserMessage to but no AS4Message is present in the MessagingContext");
            }

            SendingProcessingMode pmode = _config.GetSendingPMode(DefaultPmode);

            IEnumerable <PartInfo> parts =
                messagingContext.AS4Message.Attachments.Select(PartInfo.CreateFor);

            UserMessage userMessage =
                SendingPModeMap.CreateUserMessage(pmode, parts.ToArray());

            messagingContext.AS4Message.AddMessageUnit(userMessage);
            messagingContext.SendingPMode = pmode;

            Logger.Info($"{messagingContext.LogTag} Default AS4Message is created using SendingPMode {pmode.Id}");
            return(await StepResult.SuccessAsync(messagingContext));
        }
Пример #13
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 void Decorate_But_Not_Recreate_PushConfiguration()
        {
            // Arrange
            var smpResponse = new SmpConfiguration
            {
                Url = "http://some/url"
            };

            var push = new PushConfiguration
            {
                TlsConfiguration = new TlsConfiguration
                {
                    CertificateType = TlsCertificateChoiceType.PrivateKeyCertificate,
                    ClientCertificateInformation = new ClientCertificateReference()
                }
            };
            var fixture = new SendingProcessingMode {
                PushConfiguration = push
            };

            // Act
            SendingProcessingMode result = ExerciseDecorate(fixture, smpResponse);

            // Assert
            Assert.Same(push, result.PushConfiguration);
            Assert.Equal(smpResponse.Url, push.Protocol.Url);
            Assert.Same(
                push.TlsConfiguration.ClientCertificateInformation,
                result.PushConfiguration.TlsConfiguration.ClientCertificateInformation);
        }
Пример #15
0
        public void Fails_When_Submit_Tries_To_Override_ToParty()
        {
            // Arrange
            var submit = new SubmitMessage
            {
                PartyInfo =
                {
                    ToParty                       = new AS4.Model.Common.Party
                    {
                        Role     = Guid.NewGuid().ToString(),
                        PartyIds = new[] { new AS4.Model.Common.PartyId {
                                               Id = Guid.NewGuid().ToString()
                                           } }
                    }
                }
            };
            var sendingPMode = new SendingProcessingMode
            {
                AllowOverride    = false,
                MessagePackaging =
                {
                    PartyInfo   = new PartyInfo
                    {
                        ToParty = new Party(Guid.NewGuid().ToString(), new PartyId(Guid.NewGuid().ToString()))
                    }
                }
            };

            // Act / Assert
            Assert.Throws <NotSupportedException>(
                () => SubmitMessageMap.CreateUserMessage(submit, sendingPMode));
        }
        /// <summary>
        /// Transform a given <see cref="ReceivedMessage"/> to a Canonical <see cref="MessagingContext"/> instance.
        /// </summary>
        /// <param name="message">Given message to transform.</param>
        /// <returns></returns>
        public Task <MessagingContext> TransformAsync(ReceivedMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            SendingProcessingMode sendingPMode = _config.GetSendingPMode(id: SendingPMode);

            (string payloadId, string payloadPath) = GetPayloadInfo(message);

            var submit = new SubmitMessage
            {
                MessageInfo   = { MessageId = IdentifierFactory.Instance.Create() },
                Collaboration =
                {
                    AgreementRef = { PModeId = sendingPMode.Id }
                },
                Payloads = new[]
                {
                    new Payload
                    {
                        Id       = payloadId,
                        MimeType = message.ContentType,
                        Location = payloadPath
                    }
                }
            };

            return(Task.FromResult(new MessagingContext(submit)));
        }
Пример #17
0
        public void Resolves_Mpc_From_Either_Submit_Or_SendingPMode(
            bool allowOverride,
            string submitMpc,
            string pmodeMpc,
            Mapped expected)
        {
            // Arrange
            var submit = new SubmitMessage {
                MessageInfo = { Mpc = submitMpc }
            };
            var sendingPMode = new SendingProcessingMode
            {
                AllowOverride    = allowOverride,
                MessagePackaging = { Mpc = pmodeMpc }
            };

            // Act
            UserMessage result = SubmitMessageMap.CreateUserMessage(submit, sendingPMode);

            // Assert
            Mapped actual =
                result.Mpc == pmodeMpc
                    ? Mapped.PMode
                    : result.Mpc == submitMpc
                        ? Mapped.Submit
                        : Mapped.Default;

            Assert.Equal(expected, actual);
        }
Пример #18
0
 private static IEnumerable <PartInfo> ResolvePartInfos(SubmitMessage submit, SendingProcessingMode sendingPMode)
 {
     return((submit?.Payloads ?? Enumerable.Empty <Payload>())
            .Where(p => p != null)
            .Select(p => CreatePartInfo(p, sendingPMode))
            .ToArray());
 }
Пример #19
0
        public void Use_SendingPMode_MessageProperties_When_Submit_MessageProperties_Are_Empty()
        {
            // Arrange
            var submit = new SubmitMessage
            {
                MessageProperties = null
            };
            var sendingPMode = new SendingProcessingMode
            {
                MessagePackaging =
                {
                    MessageProperties = new List <MessageProperty>
                    {
                        new MessageProperty {
                            Name      = "capability",Type  = "info", Value = "receiving"
                        },
                        new MessageProperty {
                            Name      = "endpoint", Value = "international"
                        },
                    }
                }
            };

            // Act
            UserMessage result = SubmitMessageMap.CreateUserMessage(submit, sendingPMode);

            // Assert
            Assert.Collection(
                result.MessageProperties,
                p => Assert.Equal(("capability", "info", "receiving"), (p.Name, p.Type, p.Value)),
                p => Assert.Equal(("endpoint", "international"), (p.Name, p.Value)));
        }
Пример #20
0
 private static IEnumerable <(string propName, string propValue)> CreatePayloadCompressionProperties(
     Payload payload,
     SendingProcessingMode sendingPMode)
 {
     if (sendingPMode.MessagePackaging?.UseAS4Compression == true)
     {
         return(new[]
            public async Task SendingPModeWithEncryptionFindCriteria()
            {
                // Arrange
                var expectedPMode = new SendingProcessingMode {
                    Id = "expected-id"
                };

                expectedPMode.Security.Encryption.CertificateType = PublicKeyCertificateChoiceType.CertificateFindCriteria;
                expectedPMode.Security.Encryption.EncryptionCertificateInformation = new CertificateFindCriteria()
                {
                    CertificateFindType  = X509FindType.FindByCertificatePolicy,
                    CertificateFindValue = "SomeValue"
                };

                // Act
                SendingProcessingMode actualPMode = await ExerciseSerializeDeserialize(expectedPMode);

                // Assert
                Assert.Equal(expectedPMode.Id, actualPMode.Id);
                Assert.Equal(expectedPMode.Security.Encryption.CertificateType, actualPMode.Security.Encryption.CertificateType);

                var expectedPublicKeyCriteria = (CertificateFindCriteria)expectedPMode.Security.Encryption.EncryptionCertificateInformation;
                var actualPublicKeyCriteria   = (CertificateFindCriteria)actualPMode.Security.Encryption.EncryptionCertificateInformation;

                Assert.Equal(expectedPublicKeyCriteria.CertificateFindType, actualPublicKeyCriteria.CertificateFindType);
                Assert.Equal(expectedPublicKeyCriteria.CertificateFindValue, actualPublicKeyCriteria.CertificateFindValue);
            }
Пример #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="submit"></param>
        /// <param name="sendingPMode"></param>
        /// <returns></returns>
        internal static UserMessage CreateUserMessage(SubmitMessage submit, SendingProcessingMode sendingPMode)
        {
            if (submit == null)
            {
                throw new ArgumentNullException(nameof(submit));
            }

            if (sendingPMode == null)
            {
                throw new ArgumentNullException(nameof(sendingPMode));
            }

            var collaboration = new CollaborationInfo(
                ResolveAgreement(submit, sendingPMode),
                ResolveService(submit, sendingPMode),
                ResolveAction(submit, sendingPMode),
                ResolveConversationId(submit));

            return(new UserMessage(
                       messageId: submit.MessageInfo?.MessageId ?? IdentifierFactory.Instance.Create(),
                       refToMessageId: submit.MessageInfo?.RefToMessageId,
                       timestamp: DateTimeOffset.Now,
                       mpc: ResolveMpc(submit, sendingPMode),
                       collaboration: collaboration,
                       sender: ResolveSenderParty(submit, sendingPMode),
                       receiver: ResolveReceiverParty(submit, sendingPMode),
                       partInfos: ResolvePartInfos(submit, sendingPMode).ToArray(),
                       messageProperties: ResolveMessageProperties(submit, sendingPMode).ToArray()));
        }
        private static void OverrideCollaborationService(SendingProcessingMode pmode, XmlDocument smpMetaData, XmlNamespaceManager ns)
        {
            XmlNode processIdentifierNode =
                smpMetaData.SelectSingleNode("//oasis:ProcessList/oasis:Process/oasis:ProcessIdentifier", ns);

            if (processIdentifierNode == null)
            {
                throw new InvalidDataException(
                          "No <ProcessIdentifier/> in an ProcessList.Process element found in SMP meta-data to complete ebMS Service");
            }

            string serviceType =
                processIdentifierNode.Attributes
                ?.OfType <XmlAttribute>()
                .FirstOrDefault(a => a.Name.Equals("scheme", StringComparison.OrdinalIgnoreCase))
                ?.Value;

            Logger.Trace(
                "Override SendingPMode.MessagePackaging.CollaborationInfo.Service with "
                + $"{{Value={processIdentifierNode.InnerText}, Type={serviceType}}}");

            pmode.MessagePackaging = pmode.MessagePackaging ?? new SendMessagePackaging();
            pmode.MessagePackaging.CollaborationInfo         = pmode.MessagePackaging.CollaborationInfo ?? new CollaborationInfo();
            pmode.MessagePackaging.CollaborationInfo.Service = new Service {
                Value = processIdentifierNode.InnerText, Type = serviceType
            };
        }
Пример #24
0
        public void Oasis_DynamicDiscovery_SendingPMode_Completion()
        {
            // Arrange
            var sut     = new OasisDynamicDiscoveryProfile();
            var fixture = new SendingProcessingMode();

            var smpMetaData = new XmlDocument();

            smpMetaData.LoadXml(OasisConnectivityTestResponse);

            // Act
            DynamicDiscoveryResult result = sut.DecoratePModeWithSmpMetaData(fixture, smpMetaData);

            // Assert
            Assert.NotNull(result);
            Assert.True(result.OverrideToParty, "should specify to override ToParty");

            SendingProcessingMode actual = result.CompletedSendingPMode;

            Assert.NotNull(actual);
            Assert.Equal("http://40.115.23.114:8080/domibus/services/msh?domain=dynamic", actual.PushConfiguration.Protocol.Url);
            Assert.Equal("urn:www.cenbii.eu:profile:bii04:ver1.0", actual.MessagePackaging.CollaborationInfo.Service.Value);
            Assert.Equal("connectivity-procid-qns", actual.MessagePackaging.CollaborationInfo.Service.Type);
            Assert.Equal("connectivity-docid-qns::doc_id1", actual.MessagePackaging.CollaborationInfo.Action);
            Assert.Contains(actual.MessagePackaging.MessageProperties, p => p.Name == "originalSender");
            Assert.Contains(actual.MessagePackaging.MessageProperties, p => p.Name == "finalRecipient" && p.Value == "cefsupport1gw");
            Assert.True(actual.Security.Encryption.EncryptionCertificateInformation != null, "no encryption certificate set");
            Assert.True(actual.MessagePackaging.PartyInfo.ToParty != null, "no ToParty set");
            Assert.Equal("urn:oasis:names:tc:ebcore:partyid-type:unregistered", actual.MessagePackaging.PartyInfo.ToParty.PartyIds.First().Type);
        }
        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
            }));
        }
Пример #26
0
            public async Task ThenAgentStoresOutMessageFoReceivedSubmitMessage()
            {
                // Arrange
                string fixture       = SubmitMessageFixture;
                var    submitMessage = AS4XmlSerializer.FromString <SubmitMessage>(fixture);

                Assert.True(submitMessage?.MessageInfo?.MessageId != null, "Send SubmitMessage hasn't got a MessageInfo.MessageId element");
                Assert.True(submitMessage?.Collaboration?.AgreementRef != null, "Send SubmitMessage hasn't got a Collaboration.AgreementRef element");

                // Act
                using (HttpResponseMessage response = await StubSender.SendRequest(HttpSubmitAgentUrl, Encoding.UTF8.GetBytes(fixture), "application/xml"))
                {
                    Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
                    Assert.True(String.IsNullOrWhiteSpace(response.Content.Headers.ContentType?.ToString()));
                }

                // Assert
                IConfig config  = _as4Msh.GetConfiguration();
                string  pmodeId = submitMessage.Collaboration.AgreementRef.PModeId;
                SendingProcessingMode usedSendingPMode = config.GetSendingPMode(pmodeId);

                Assert.True(usedSendingPMode.PushConfiguration?.Protocol != null, "SendingPMode for SubmitMessage hasn't got PushConfiguration.Protocol element");

                var        databaseSpy = new DatabaseSpy(config);
                OutMessage outMessage  = databaseSpy.GetOutMessageFor(
                    m => m.EbmsMessageId == submitMessage.MessageInfo.MessageId);

                Assert.True(outMessage != null, "No OutMessage was stored for send SubmitMessage");
                Assert.Equal(usedSendingPMode.PushConfiguration.Protocol.Url, outMessage.Url);
            }
        private X509Certificate2 RetrieveCertificate(SendingProcessingMode pmode)
        {
            Encryption encryptionSettings = pmode.Security.Encryption;

            if (encryptionSettings.EncryptionCertificateInformation == null)
            {
                throw new ConfigurationErrorsException(
                          $"No encryption certificate information found in SendingPMode {pmode.Id} to perform encryption");
            }

            if (encryptionSettings.EncryptionCertificateInformation is CertificateFindCriteria certFindCriteria)
            {
                return(_certificateRepository.GetCertificate(
                           certFindCriteria.CertificateFindType,
                           certFindCriteria.CertificateFindValue));
            }

            if (encryptionSettings.EncryptionCertificateInformation is PublicKeyCertificate pubKeyCert)
            {
                return(new X509Certificate2(Convert.FromBase64String(pubKeyCert.Certificate), string.Empty));
            }

            throw new NotSupportedException(
                      $"The encryption certificate information specified in the Sending PMode {pmode.Id} could not be used to retrieve the certificate");
        }
Пример #28
0
        private static UserMessage CreateMultihopUserMessage(string receivePModeId, SendingProcessingMode pmode)
        {
            var collaboration =
                new Model.Core.CollaborationInfo(
                    new Model.Core.AgreementReference(
                        value: "http://agreements.europa.org/agreement",
                        pmodeId: receivePModeId),
                    service: new Model.Core.Service(
                        value: "Forward_Push_Service",
                        type: "eu:europa:services"),
                    action: "Forward_Push_Action",
                    conversationId: "eu:europe:conversation");

            IEnumerable <MessageProperty> properties =
                pmode.MessagePackaging?.MessageProperties?.Select(
                    p => new MessageProperty(p.Name, p.Value, p.Type)) ?? new MessageProperty[0];

            Party p1 = pmode.MessagePackaging?.PartyInfo.FromParty;
            Party p2 = pmode.MessagePackaging?.PartyInfo.ToParty;

            return(new UserMessage(
                       $"multihop-message-id-{Guid.NewGuid()}",
                       collaboration,
                       SendingPModeMap.ResolveSender(p1),
                       SendingPModeMap.ResolveSender(p2),
                       new Model.Core.PartInfo[0],
                       properties));
        }
        private static void OverrideEntireEncryption(SendingProcessingMode pmode, SmpConfiguration smpResponse)
        {
            Logger.Trace($"Override SendingPMode.Encryption with {{IsEnabled={smpResponse.EncryptionEnabled}}}");
            Logger.Trace(
                "Override SendingPMode.Encryption with {{"
                + $"Algorithm={smpResponse.EncryptAlgorithm}, "
                + $"AlgorithmKeySize={smpResponse.EncryptAlgorithmKeySize}}}");

            Logger.Trace("Override SendingPMode.Encryption with {{CertificateType=PublicKeyCertificate}}");
            Logger.Trace(
                "Override SendingPMode.Encryption.KeyTransport Algorithms with {{"
                + $"Digest={smpResponse.EncryptKeyDigestAlgorithm}, "
                + $"Mgf={smpResponse.EncryptKeyMgfAlorithm}, "
                + $"Transport={smpResponse.EncryptKeyTransportAlgorithm}}}");

            pmode.Security                             = pmode.Security ?? new Model.PMode.Security();
            pmode.Security.Encryption                  = pmode.Security.Encryption ?? new Encryption();
            pmode.Security.Encryption.IsEnabled        = smpResponse.EncryptionEnabled;
            pmode.Security.Encryption.Algorithm        = smpResponse.EncryptAlgorithm;
            pmode.Security.Encryption.AlgorithmKeySize = smpResponse.EncryptAlgorithmKeySize;
            pmode.Security.Encryption.CertificateType  = PublicKeyCertificateChoiceType.PublicKeyCertificate;
            pmode.Security.Encryption.EncryptionCertificateInformation = new PublicKeyCertificate
            {
                Certificate = TryConvertToBase64String(smpResponse.EncryptPublicKeyCertificate)
            };
            pmode.Security.Encryption.KeyTransport = pmode.Security.Encryption.KeyTransport ?? new KeyEncryption();
            pmode.Security.Encryption.KeyTransport.DigestAlgorithm    = smpResponse.EncryptKeyDigestAlgorithm;
            pmode.Security.Encryption.KeyTransport.MgfAlgorithm       = smpResponse.EncryptKeyMgfAlorithm;
            pmode.Security.Encryption.KeyTransport.TransportAlgorithm = smpResponse.EncryptKeyTransportAlgorithm;
        }
Пример #30
0
        private static async Task <StepResult> ExerciseDynamicDiscovery(SendingProcessingMode pmode)
        {
            var step = new DynamicDiscoveryStep();

            return(await step.ExecuteAsync(
                       new MessagingContext(new SubmitMessage()) { SendingPMode = pmode }));
        }