public void LmiWebhookReceiverServiceExtractEventReturnsExpected(string eventType, WebhookCommand webhookCommand, string api)
        {
            // Arrange
            var eventGridEventData = new EventGridEventData
            {
                ItemId = Guid.NewGuid().ToString(),
                Api    = api,
            };
            var eventGridEvents = BuildValidEventGridEvent(eventType, eventGridEventData);
            var expectedResult  = new WebhookRequestModel
            {
                WebhookCommand = webhookCommand,
                EventId        = Guid.Parse(eventGridEvents.First().Id),
                EventType      = eventGridEvents.First().EventType,
                ContentId      = Guid.Parse(eventGridEventData.ItemId),
                Url            = new Uri(eventGridEventData.Api, UriKind.Absolute),
                SubscriptionValidationResponse = null,
            };
            var requestBody = JsonConvert.SerializeObject(eventGridEvents);

            // Act
            var result = lmiWebhookReceiverService.ExtractEvent(requestBody);

            // Assert
            Assert.Equal(expectedResult.WebhookCommand, result.WebhookCommand);
            Assert.Equal(expectedResult.EventType, result.EventType);
            Assert.Equal(expectedResult.ContentId, result.ContentId);
            Assert.Equal(expectedResult.Url, result.Url);
            Assert.Null(result.SubscriptionValidationResponse?.ValidationResponse);
        }
        public async Task LmiWebhookHttpTriggerPostForSubscriptionValidationReturnsExpectedResultCode(WebhookCommand webhookCommand)
        {
            // Arrange
            var expectedResult      = HttpStatusCode.Accepted;
            var function            = new LmiWebhookHttpTrigger(fakeLogger, draftEnvironmentValues, fakeLmiWebhookReceiverService);
            var request             = BuildRequestWithValidBody("a request body");
            var webhookRequestModel = new WebhookRequestModel
            {
                WebhookCommand = webhookCommand,
            };

            A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).Returns(webhookRequestModel);
            A.CallTo(() => fakeDurableOrchestrationClient.StartNewAsync(A <string> .Ignored, A <SocRequestModel> .Ignored)).Returns("An instance id");
            A.CallTo(() => fakeDurableOrchestrationClient.CreateCheckStatusResponse(A <HttpRequest> .Ignored, A <string> .Ignored, A <bool> .Ignored)).Returns(new AcceptedResult());

            // Act
            var result = await function.Run(request, fakeDurableOrchestrationClient).ConfigureAwait(false);

            // Assert
            A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).MustHaveHappenedOnceExactly();
            A.CallTo(() => fakeDurableOrchestrationClient.StartNewAsync(A <string> .Ignored, A <SocRequestModel> .Ignored)).MustHaveHappenedOnceExactly();
            A.CallTo(() => fakeDurableOrchestrationClient.CreateCheckStatusResponse(A <HttpRequest> .Ignored, A <string> .Ignored, A <bool> .Ignored)).MustHaveHappenedOnceExactly();
            var statusResult = Assert.IsType <AcceptedResult>(result);

            Assert.Equal((int)expectedResult, statusResult.StatusCode);
        }
        public async Task LmiWebhookHttpTriggerPostForSubscriptionValidationReturnsExpectedResultCode(WebhookCommand webhookCommand, int forAllCount, int forSocCount)
        {
            // Arrange
            var expectedResult      = HttpStatusCode.Created;
            var function            = new LmiWebhookHttpTrigger(fakeLogger, draftEnvironmentValues, fakeLmiWebhookReceiverService);
            var request             = BuildRequestWithValidBody("a request body");
            var webhookRequestModel = new WebhookRequestModel
            {
                WebhookCommand = webhookCommand,
                ContentId      = Guid.NewGuid(),
            };

            A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).Returns(webhookRequestModel);
            A.CallTo(() => fakeLmiWebhookReceiverService.ReportAll()).Returns(HttpStatusCode.Created);
            A.CallTo(() => fakeLmiWebhookReceiverService.ReportSoc(A <Guid> .Ignored)).Returns(HttpStatusCode.Created);

            // Act
            var result = await function.Run(request).ConfigureAwait(false);

            // Assert
            A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).MustHaveHappenedOnceExactly();
            A.CallTo(() => fakeLmiWebhookReceiverService.ReportAll()).MustHaveHappened(forAllCount, Times.Exactly);
            A.CallTo(() => fakeLmiWebhookReceiverService.ReportSoc(A <Guid> .Ignored)).MustHaveHappened(forSocCount, Times.Exactly);
            var statusResult = Assert.IsType <StatusCodeResult>(result);

            Assert.Equal((int)expectedResult, statusResult.StatusCode);
        }
Example #4
0
        public async void Post([FromBody] WebhookRequestModel request)
        {
            // Retornar StatusCode 20X em caso de processamento com sucesso. Qualquer outro código será considerado erro e a mensagem reenviada.
            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetAsync(request.Url);

                if (response.IsSuccessStatusCode)
                {
                    // Processar salvamento do arquivo.
                }
                else
                {
                    // Processar retorno de erro.
                }
            }
        }
        public async Task <ActionResult <DeploymentModel> > Post([FromBody] WebhookRequestModel webhook)
        {
            var imageName   = string.Format("{0}/{1}", webhook.Repository.Namespace, webhook.Repository.Name);
            var callbackUrl = webhook.CallbackUrl;

            if (webhook.PushData.Tag == LATEST_TAG)
            {
                await _callbackService.SendCallback(true, $"Did not deploy {imageName} since it is using the 'latest' tag.", callbackUrl);

                return(Accepted());
            }

            var deploymentName = await _mappingService.GetDeploymentNameFromImage(imageName);

            var deployment = await _kubernetesService.SetDeploymentImage(deploymentName, _kubernetesNamespace, imageName, webhook.PushData.Tag);

            await _callbackService.SendCallback(true, $"Deployed {imageName} to {deployment.Name}", callbackUrl);

            return(Ok(deployment));
        }
        public void LmiWebhookReceiverServiceExtractEventReturnsExpectedSubscriptionRequest()
        {
            // Arrange
            var subscriptionValidationEventData = new SubscriptionValidationEventData("a validation code", "a validation url");
            var expectedResult = new WebhookRequestModel
            {
                WebhookCommand = WebhookCommand.SubscriptionValidation,
                SubscriptionValidationResponse = new SubscriptionValidationResponse {
                    ValidationResponse = subscriptionValidationEventData.ValidationCode
                },
            };
            var eventGridEvents = BuildValidEventGridEvent(Microsoft.Azure.EventGrid.EventTypes.EventGridSubscriptionValidationEvent, subscriptionValidationEventData);
            var requestBody     = JsonConvert.SerializeObject(eventGridEvents);

            // Act
            var result = lmiWebhookReceiverService.ExtractEvent(requestBody);

            // Assert
            Assert.Equal(expectedResult.WebhookCommand, result.WebhookCommand);
            Assert.Equal(expectedResult.SubscriptionValidationResponse.ValidationResponse, result.SubscriptionValidationResponse?.ValidationResponse);
        }
        public void LmiWebhookReceiverServiceExtractEventReturnsNone()
        {
            // Arrange
            var eventGridEventData = new EventGridEventData
            {
                ItemId = Guid.NewGuid().ToString(),
                Api    = "https://somewhere.com/api/",
            };
            var eventGridEvents = BuildValidEventGridEvent(EventTypePublished, eventGridEventData);
            var expectedResult  = new WebhookRequestModel
            {
                WebhookCommand = WebhookCommand.None,
            };
            var requestBody = JsonConvert.SerializeObject(eventGridEvents);

            // Act
            var result = lmiWebhookReceiverService.ExtractEvent(requestBody);

            // Assert
            Assert.Equal(expectedResult.WebhookCommand, result.WebhookCommand);
        }
        public async Task LmiWebhookHttpTriggerPostForSubscriptionValidationReturnsBadRequestForPublishedEnvironment(WebhookCommand webhookCommand)
        {
            // Arrange
            var expectedResult      = HttpStatusCode.BadRequest;
            var function            = new LmiWebhookHttpTrigger(fakeLogger, publishedEnvironmentValues, fakeLmiWebhookReceiverService);
            var request             = BuildRequestWithValidBody("a request body");
            var webhookRequestModel = new WebhookRequestModel
            {
                WebhookCommand = webhookCommand,
            };

            A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).Returns(webhookRequestModel);

            // Act
            var result = await function.Run(request).ConfigureAwait(false);

            // Assert
            A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).MustHaveHappenedOnceExactly();
            A.CallTo(() => fakeLmiWebhookReceiverService.ReportAll()).MustNotHaveHappened();
            A.CallTo(() => fakeLmiWebhookReceiverService.ReportSoc(A <Guid> .Ignored)).MustNotHaveHappened();
            var statusResult = Assert.IsType <BadRequestResult>(result);

            Assert.Equal((int)expectedResult, statusResult.StatusCode);
        }
        public async Task LmiWebhookHttpTriggerPostForSubscriptionValidationReturnsOk()
        {
            // Arrange
            var expectedResult      = new StatusCodeResult((int)HttpStatusCode.OK);
            var function            = new LmiWebhookHttpTrigger(fakeLogger, fakeLmiWebhookReceiverService);
            var request             = BuildRequestWithValidBody("a request body");
            var webhookRequestModel = new WebhookRequestModel
            {
                WebhookCommand = WebhookCommand.SubscriptionValidation,
            };

            A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).Returns(webhookRequestModel);

            // Act
            var result = await function.Run(request, fakeDurableOrchestrationClient).ConfigureAwait(false);

            // Assert
            A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).MustHaveHappenedOnceExactly();
            A.CallTo(() => fakeDurableOrchestrationClient.StartNewAsync(A <string> .Ignored, A <SocRequestModel> .Ignored)).MustNotHaveHappened();
            A.CallTo(() => fakeDurableOrchestrationClient.CreateCheckStatusResponse(A <HttpRequest> .Ignored, A <string> .Ignored, A <bool> .Ignored)).MustNotHaveHappened();
            var statusResult = Assert.IsType <OkObjectResult>(result);

            Assert.Equal(expectedResult.StatusCode, statusResult.StatusCode);
        }
Example #10
0
        public WebhookRequestModel ExtractEvent(string requestBody)
        {
            var webhookRequestModel = new WebhookRequestModel();

            logger.LogInformation($"Received events: {requestBody}");

            var eventGridSubscriber = new EventGridSubscriber();

            foreach (var key in acceptedEventTypes.Keys)
            {
                eventGridSubscriber.AddOrUpdateCustomEventMapping(key, typeof(EventGridEventData));
            }

            var eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestBody);

            foreach (var eventGridEvent in eventGridEvents)
            {
                if (!Guid.TryParse(eventGridEvent.Id, out Guid eventId))
                {
                    throw new InvalidDataException($"Invalid Guid for EventGridEvent.Id '{eventGridEvent.Id}'");
                }

                if (eventGridEvent.Data is SubscriptionValidationEventData subscriptionValidationEventData)
                {
                    logger.LogInformation($"Got SubscriptionValidation event data, validationCode: {subscriptionValidationEventData!.ValidationCode},  validationUrl: {subscriptionValidationEventData.ValidationUrl}, topic: {eventGridEvent.Topic}");

                    webhookRequestModel.WebhookCommand = WebhookCommand.SubscriptionValidation;
                    webhookRequestModel.SubscriptionValidationResponse = new SubscriptionValidationResponse()
                    {
                        ValidationResponse = subscriptionValidationEventData.ValidationCode,
                    };

                    return(webhookRequestModel);
                }
                else if (eventGridEvent.Data is EventGridEventData eventGridEventData)
                {
                    if (!Guid.TryParse(eventGridEventData.ItemId, out Guid contentId))
                    {
                        throw new InvalidDataException($"Invalid Guid for EventGridEvent.Data.ItemId '{eventGridEventData.ItemId}'");
                    }

                    if (!Uri.TryCreate(eventGridEventData.Api, UriKind.Absolute, out Uri? url))
                    {
                        throw new InvalidDataException($"Invalid Api url '{eventGridEventData.Api}' received for Event Id: {eventId}");
                    }

                    var cacheOperation = acceptedEventTypes[eventGridEvent.EventType];

                    logger.LogInformation($"Got Event Id: {eventId}: {eventGridEvent.EventType}: Cache operation: {cacheOperation} {url}");

                    var messageContentType = DetermineMessageContentType(url.ToString());
                    if (messageContentType == MessageContentType.None)
                    {
                        logger.LogError($"Event Id: {eventId} got unknown message content type - {messageContentType} - {url}");
                        return(webhookRequestModel);
                    }

                    webhookRequestModel.WebhookCommand = DetermineWebhookCommand(messageContentType, cacheOperation);
                    webhookRequestModel.EventId        = eventId;
                    webhookRequestModel.EventType      = eventGridEvent.EventType;
                    webhookRequestModel.ContentId      = contentId;
                    webhookRequestModel.Url            = url;
                }
                else
                {
                    throw new InvalidDataException($"Invalid event type '{eventGridEvent.EventType}' received for Event Id: {eventId}, should be one of '{string.Join(",", acceptedEventTypes.Keys)}'");
                }
            }

            return(webhookRequestModel);
        }