private async Task Process(Message message)
 {
     SnsMessage        snsMessage        = JsonConvert.DeserializeObject <SnsMessage>(message.Body);
     SpfConfigsUpdated spfConfigsUpdated = JsonConvert.DeserializeObject <SpfConfigsUpdated>(snsMessage.Message);
     List <SpfConfigReadModelEntity> readModelEntities = spfConfigsUpdated.SpfConfigs.Select(Process).ToList();
     await _dao.InsertOrUpdate(readModelEntities);
 }
Exemplo n.º 2
0
    //Build the string to sign for Notification messages.
    public string BuildNotificationStringToSign(SnsMessage msg)
    {
        string stringToSign = null;

        //Build the string to sign from the values in the message.
        //Name and values separated by newline characters
        //The name value pairs are sorted by name
        //in byte sort order.
        stringToSign  = "Message\n";
        stringToSign += msg.Message + "\n";
        stringToSign += "MessageId\n";
        stringToSign += msg.MessageId + "\n";
        if (msg.Subject != null)
        {
            stringToSign += "Subject\n";
            stringToSign += msg.Subject + "\n";
        }
        stringToSign += "Timestamp\n";
        stringToSign += msg.Timestamp + "\n";
        stringToSign += "TopicArn\n";
        stringToSign += msg.TopicArn + "\n";
        stringToSign += "Type\n";
        stringToSign += msg.Type + "\n";
        return(stringToSign);
    }
Exemplo n.º 3
0
        /// <summary>
        /// Sends a message to the given queue
        /// </summary>
        /// <param name="messageString">Message to publish</param>
        /// <param name="type">Type of message to send</param>
        /// <param name="localMessageQueue">Queue to send to</param>
        public void Send(string messageString, Type type, IMessageQueue localMessageQueue)
        {
            string     messageType = type.AssemblyQualifiedName;
            SnsMessage fakeMessage = new SnsMessage()
            {
                Message           = messageString,
                MessageAttributes = new Dictionary <string, MessageAttribute>()
                {
                    { "messageType", new MessageAttribute()
                      {
                          Type = "String", Value = messageType
                      } },
                },
            };

            foreach (var entry in GetCommonMetadata())
            {
                fakeMessage.MessageAttributes.Add(entry.Key, new MessageAttribute()
                {
                    Type = "String", Value = entry.Value
                });
            }

            string messageBody = _messageSerializer.Serialize(fakeMessage);

            localMessageQueue.AddMessage(messageBody);
            _messageLogger.OutboundLogMessage(messageBody, messageType);
        }
Exemplo n.º 4
0
        private async Task <bool> SubscribeSnsWebhookAsync(SnsMessage snsMessage)
        {
            if (snsMessage.Type == null)
            {
                return(false);
            }

            if (!snsMessage.Type.Equals("SubscriptionConfirmation", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (string.IsNullOrEmpty(snsMessage.SubscribeURL))
            {
                //this._logger.LogError($"No subcribe url available {json}");
                return(false);
            }

            using (var httpClient = new HttpClient())
            {
                await httpClient.GetAsync(snsMessage.SubscribeURL);

                return(true);
            }
        }
Exemplo n.º 5
0
    public bool VerifySnsMessage(SnsMessage snsMessage)
    {
        var certificateBytes = GetHttpResponse(snsMessage.SigningCertURL);

        var certificate = new X509Certificate2(certificateBytes);
        var verifier    = (RSACryptoServiceProvider)certificate.PublicKey.Key;

        var msgBytes    = GetMessageBytesToSign(snsMessage);
        var signedBytes = Convert.FromBase64String(snsMessage.Signature);

        return(verifier.VerifyData(msgBytes, CryptoConfig.MapNameToOID("SHA1"), signedBytes));
    }
        public async Task Given_message_created_then_should_receive_by_id(SnsMessage message)
        {
            // Given
            var body = JsonSerializer.Serialize(message);
            await _sut.CreateAsync(body);

            // When
            var result = await _sut.GetAsync(message.MessageId);

            // Then
            result.Should().BeEquivalentTo(message);
        }
Exemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SnsRecord{TMessage}" /> class.
 /// </summary>
 /// <param name="eventSource">The sns record's event source.</param>
 /// <param name="eventSubscriptionArn">The ARN of the record's event subscription.</param>
 /// <param name="eventVersion">The version of the event.</param>
 /// <param name="sns">The sns record's message structure.</param>
 public SnsRecord(
     string eventSource,
     string eventSubscriptionArn,
     string eventVersion,
     SnsMessage <TMessage> sns
     )
 {
     EventSource          = eventSource;
     EventSubscriptionArn = eventSubscriptionArn;
     EventVersion         = eventVersion;
     Sns = sns;
 }
        public async Task Given_message_created_then_should_find_by_message(SnsMessage message)
        {
            // Given
            var body = JsonSerializer.Serialize(message);
            await _sut.CreateAsync(body);

            // When
            var result = await _sut.SearchAsync(message.Message);

            // Then
            result.Should().HaveCount(1);
            result.Single().Should().BeEquivalentTo(message);
        }
Exemplo n.º 9
0
    private byte[] GetMessageBytesToSign(SnsMessage msg)
    {
        string messageToSign = null;

        if (msg.Type == "Notification")
        {
            messageToSign = BuildNotificationStringToSign(msg);
        }
        else if (msg.Type == "SubscriptionConfirmation" || msg.Type == "UnsubscribeConfirmation")
        {
            messageToSign = BuildSubscriptionStringToSign(msg);
        }

        return(Encoding.UTF8.GetBytes(messageToSign));
    }
Exemplo n.º 10
0
        public async Task <string> Handle(SnsMessage <CacheExpirationRequest> request, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ExpireFunction expireFunction = request.Message.Type switch
            {
                CacheExpirationType.User => cache.ExpireUserCache,
                CacheExpirationType.Command => cache.ExpireCommandCache,
                _ => throw new NotSupportedException(),
            };

            var ipAddresses = await dns.GetIPAddresses(options.AdapterUrl, cancellationToken);

            var tasks = ipAddresses.Select(ip => expireFunction(ip, request.Message.Id, cancellationToken));
            await Task.WhenAll(tasks);

            return(string.Empty);
        }
Exemplo n.º 11
0
        public async Task <SesWebhook> ProcessNotificationAsync(SnsMessage snsMessage)
        {
            if (await this.SubscribeSnsWebhookAsync(snsMessage))
            {
                return(null);
            }

            if (snsMessage != null && snsMessage.Type != null)
            {
                if (snsMessage.Type.Equals("Notification", StringComparison.OrdinalIgnoreCase))
                {
                    return(this.Deserialize(snsMessage.Message));
                }

                return(null);
            }

            return(null);
        }
        public void AwsMessagePublisherTests_Send()
        {
            Mock <IMessageQueue> mockQueue = new Mock <IMessageQueue>(MockBehavior.Strict);
            string sentMessage             = null;

            mockQueue.Setup(x => x.AddMessage(It.IsAny <string>())).Callback <string>(x => sentMessage = x);

            AwsMessagePublisher publisher = new AwsMessagePublisher(_mockLogger.Object);

            publisher.Send("message body", typeof(TestMessage), mockQueue.Object);
            mockQueue.Verify(x => x.AddMessage(It.IsAny <string>()), Times.Once());
            Assert.IsNotNull(sentMessage);
            SnsMessage message = JsonConvert.DeserializeObject <SnsMessage>(sentMessage);

            Assert.IsNotNull(message);
            Assert.AreEqual("message body", message.Message);
            Assert.AreEqual("String", message.MessageAttributes["messageType"].Type);
            Assert.AreEqual("JungleBus.Tests.TestMessage, JungleBus.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", message.MessageAttributes["messageType"].Value);
            _mockLogger.Verify(x => x.OutboundLogMessage(It.IsAny <string>(), It.IsAny <string>()), Times.Once());
        }
Exemplo n.º 13
0
        public async Task <string> Handle(SnsMessage <CustomResourceRequest <Response> > request, CancellationToken cancellationToken = default)
        {
            var response = new CustomResourceResponse <Response>
            {
                Status             = CustomResourceResponseStatus.Success,
                RequestId          = request.Message.RequestId,
                StackId            = request.Message.StackId,
                Data               = new Response(),
                LogicalResourceId  = request.Message.LogicalResourceId,
                PhysicalResourceId = string.IsNullOrEmpty(request.Message.PhysicalResourceId) ? Guid.NewGuid().ToString() : request.Message.PhysicalResourceId,
            };

            await httpClient.PutJson(
                requestUri : request.Message.ResponseURL !,
                payload : response,
                contentType : null,
                cancellationToken : cancellationToken
                );

            return("OK");
        }
Exemplo n.º 14
0
            public async Task ShouldClearCommandCache(
                string command,
                IPAddress ip1,
                IPAddress ip2,
                SnsMessage <CacheExpirationRequest> request,
                [Frozen] IDnsService dns,
                [Frozen] ICacheService cache,
                [Frozen] CacheExpirerOptions options,
                [Target] Handler handler,
                CancellationToken cancellationToken
                )
            {
                request.Message.Type = CacheExpirationType.Command;
                request.Message.Id   = command;
                dns.GetIPAddresses(Any <string>(), Any <CancellationToken>()).Returns(new[] { ip1, ip2 });

                await handler.Handle(request, cancellationToken);

                await dns.Received().GetIPAddresses(Is(options.AdapterUrl), Is(cancellationToken));

                await cache.Received().ExpireCommandCache(Is(ip1), Is(command), Is(cancellationToken));

                await cache.Received().ExpireCommandCache(Is(ip2), Is(command), Is(cancellationToken));
            }
Exemplo n.º 15
0
        private static DomainTlsProfileChanged GetSnsMessageBody(Message message)
        {
            SnsMessage snsMessage = DeserializeObject <SnsMessage>(message.Body);

            return(DeserializeObject <DomainTlsProfileChanged>(snsMessage.Message));
        }
Exemplo n.º 16
0
 public bool TryCreate(string key, SnsMessage value)
 {
     return(_storage.TryAdd(key, value));
 }
Exemplo n.º 17
0
        public virtual Task <TestLambdaMessage> Handle(SnsMessage <TestLambdaMessage> request, CancellationToken cancellationToken = default)
        {
            Request = request;

            return(Task.FromResult <TestLambdaMessage>(null !));
        }
Exemplo n.º 18
0
 public virtual void Validate(SnsMessage <TestLambdaMessage> request)
 {
 }
 public AwsController(SnsMessage snsMessage, SqsMessage sqsMessage)
 {
     _snsMessage = snsMessage;
     _sqsMessage = sqsMessage;
 }
Exemplo n.º 20
0
        public async Task <object> FunctionHandler(SQSEvent sqsEvent, ILambdaContext context)
        {
            try
            {
                Console.WriteLine($"SQS Record Count {sqsEvent.Records.Count}");

                foreach (var record in sqsEvent.Records)
                {
                    var sqsMessage   = record.Body;
                    var innerMessage = SnsMessage.FromJson(sqsMessage);

                    if (innerMessage.RootEntityUrl == null)
                    {
                        Console.WriteLine("There is no root entity in this message.");
                        Console.WriteLine("Lambda processing aborted");
                        return(new { body = "SQS Event Processing Completed at " + DateTime.Now.ToString(), statusCode = 200 });
                    }

                    var messageGroupID = innerMessage.MessageGroupId;
                    var rootEntityURL  = innerMessage.RootEntityUrl;
                    var entityID       = (int)innerMessage.EntityId;
                    var templateID     = (int)innerMessage.Template.TemplateId;

                    //TODO - Function logic here

                    //SAMPLES
                    //Get a catalog item - assuming it was the message received on the queue
                    var catalogResult = await this._v3.Get("catalog-item", entityID);

                    //Search for the first 25 catalog items with the same template as the one received on the queue
                    var catalogPayload = @"
                        {""query"":
                        {""$and"":[
                        {""$eq"":[""templateid""," + templateID + @"]}]},
                        ""start"":0,""rows"":25,""sortOrders"":[""sequencenumber asc""]}";

                    var catalogResults = await this._v3.Search("catalog-item", catalogPayload);

                    if (catalogResults.Count() == 0)
                    {
                        Console.WriteLine($"Cannot find Catalog Items with template id {templateID}.");
                        Console.WriteLine("Lambda processing aborted");
                    }

                    //Update a catalog item
                    //A sample cannot be given here as every client has different fields in their unique environment
                    //A recommended approach would be to GET the desired catalog item, modify its value(s), serialize it, and pass to the PUT method
                    //The API call will return the EntityModel with its updated data
                    //var updatedCatalogResult = await this._v3.Put("catalog-item", entityID, entityJSON);

                    //Create a catalog item
                    //A sample cannot be given here as every client has different fields in their unique environment
                    //A recommended approach would be to create a new EntityModel, or custom object with the necessary information,
                    //serialize it, and pass to the POST method
                    //The API call will return the ID of the new entity
                    //var newCatalogItemIDResult = await this._v3.Post("catalog-item", entityJSON);

                    //Delete a catalog item
                    //var deleteCatalogItemResult = await this._v3.Delete("catalog-item", newCatalogItemIDResult);

                    //Get all Rights templates and find the Territory LOV on a Rights In template
                    var rightTemplates = await this._v3.GetTemplates("rightset");

                    var             rightsInTemplate = rightTemplates.Templates.Where(t => t.TemplateId == 1).First();
                    List <LovValue> territories      = rightsInTemplate.Fields.Where(f => f.Label == "territory").First().ListOfValues.ToList();
                }
            }
            catch (Exception ex)
            {
                var record = sqsEvent.Records.First();

                Console.WriteLine($"[arn:sqs {DateTime.Now}] ERROR = {ex.Message} {ex.StackTrace}");

                return(new { body = "SQS Event Processing Error at " + DateTime.Now.ToString() + " " + ex.Message, statusCode = 400 });
            }

            return(new { body = "SQS Event Processing Completed at " + DateTime.Now.ToString(), statusCode = 200 });
        }
Exemplo n.º 21
0
 public Task <string> Handle(SnsMessage <CloudFormationStackEvent> request, CancellationToken cancellationToken = default)
 {
     return(Task.FromResult(request.Message.StackId));
 }