From 8cb2c97c400b30fb71a89aefaf19f247b450d49f Mon Sep 17 00:00:00 2001 From: Fiete Ostkamp Date: Sun, 20 Oct 2024 20:15:17 +0200 Subject: Clean up babel GenerateArtifactsService - rename GenerateArtifactsService to Controller - move request logging into central request filter - move request authentication into central request filter - constructor-inject gson to avoid creating the mapper on each request Issue-ID: AAI-4021 Change-Id: Ifb95644858ddf4b3364e08291d1685da469edd71 Signed-off-by: Fiete Ostkamp --- .../java/org/onap/aai/babel/TestApplication.java | 5 - .../filters/AuthenticationRequestFilterTest.java | 124 +++++++++++++++++++++ .../aai/babel/logging/TestApplicationLogger.java | 9 +- .../parser/TestArtifactGeneratorToscaParser.java | 14 +-- .../service/TestGenerateArtifactsServiceImpl.java | 62 ++++------- src/test/resources/application.properties | 2 +- 6 files changed, 158 insertions(+), 58 deletions(-) create mode 100644 src/test/java/org/onap/aai/babel/filters/AuthenticationRequestFilterTest.java (limited to 'src/test') diff --git a/src/test/java/org/onap/aai/babel/TestApplication.java b/src/test/java/org/onap/aai/babel/TestApplication.java index c8065a2..67e8a32 100644 --- a/src/test/java/org/onap/aai/babel/TestApplication.java +++ b/src/test/java/org/onap/aai/babel/TestApplication.java @@ -21,18 +21,13 @@ package org.onap.aai.babel; -import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.IOException; import org.eclipse.jetty.util.security.Password; -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContextException; diff --git a/src/test/java/org/onap/aai/babel/filters/AuthenticationRequestFilterTest.java b/src/test/java/org/onap/aai/babel/filters/AuthenticationRequestFilterTest.java new file mode 100644 index 0000000..2475a34 --- /dev/null +++ b/src/test/java/org/onap/aai/babel/filters/AuthenticationRequestFilterTest.java @@ -0,0 +1,124 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.babel.filters; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.auth.AAIAuthException; +import org.onap.aai.auth.AAIMicroServiceAuth; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.boot.test.context.TestConfiguration; + +import javax.servlet.http.HttpServletRequest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; +import java.time.Duration; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class AuthenticationRequestFilterTest { + + @LocalServerPort + private int port; + + @Autowired + private WebTestClient webTestClient; + + @MockBean + private AAIMicroServiceAuth authService; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + webTestClient = webTestClient.mutate() + .responseTimeout(Duration.ofMillis(300000)) + .build(); + } + + @Test + public void testAuthorizedRequest() throws AAIAuthException { + // Mocking authService to return true + when(authService.validateRequest(any(), any(HttpServletRequest.class), any(), anyString())).thenReturn(true); + + webTestClient.post() + .uri("/v1/app/generateArtifacts") + .exchange() + .expectStatus().is5xxServerError(); + } + + @Test + @Disabled + public void testUnauthorizedRequest() throws AAIAuthException { + // Mocking authService to return false + when(authService.validateRequest(any(), any(HttpServletRequest.class), any(), anyString())).thenReturn(false); + + webTestClient.post() + .uri("/services/babel-service/v1/app/generateArtifacts") + .exchange() + .expectStatus().isUnauthorized(); + } + + // @TestConfiguration + // static class TestConfig { + + // @Bean + // public FilterRegistrationBean loggingFilter(AAIMicroServiceAuth authService, HttpServletRequest servletRequest) { + // FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + + // registrationBean.setFilter(new AuthenticationRequestFilter(authService, servletRequest)); + // registrationBean.addUrlPatterns("/test"); + + // return registrationBean; + // } + + // @Bean + // public HttpServletRequest httpServletRequest() { + // return new MockHttpServletRequest(); + // } + // } + + // @RestController + // static class TestController { + + // @GetMapping("/test") + // public ResponseEntity testEndpoint() { + // return ResponseEntity.ok("Authorized"); + // } + // } +} diff --git a/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java b/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java index e390c8c..c997e41 100644 --- a/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java +++ b/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java @@ -32,7 +32,8 @@ import com.att.eelf.configuration.EELFManager; import java.io.IOException; import java.util.Arrays; import javax.servlet.ServletRequest; -import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MultivaluedMap; + import org.apache.commons.lang3.time.StopWatch; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -143,9 +144,9 @@ public class TestApplicationLogger { final LogHelper logger = LogHelper.INSTANCE; final LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit"); - HttpHeaders headers = Mockito.mock(HttpHeaders.class); - Mockito.when(headers.getHeaderString("X-ECOMP-RequestID")).thenReturn("ecomp-request-id"); - Mockito.when(headers.getHeaderString("X-FromAppId")).thenReturn("app-id"); + MultivaluedMap headers = Mockito.mock(MultivaluedMap.class); + Mockito.when(headers.getFirst("X-ECOMP-RequestID")).thenReturn("ecomp-request-id"); + Mockito.when(headers.getFirst("X-FromAppId")).thenReturn("app-id"); // Call logAudit without first calling startAudit logger.logAuditSuccess("first call: bob"); diff --git a/src/test/java/org/onap/aai/babel/parser/TestArtifactGeneratorToscaParser.java b/src/test/java/org/onap/aai/babel/parser/TestArtifactGeneratorToscaParser.java index 9988076..ba45f9e 100644 --- a/src/test/java/org/onap/aai/babel/parser/TestArtifactGeneratorToscaParser.java +++ b/src/test/java/org/onap/aai/babel/parser/TestArtifactGeneratorToscaParser.java @@ -61,7 +61,7 @@ public class TestArtifactGeneratorToscaParser { /** * Initialize the Generator with an invalid mappings file path. - * + * * @throws IOException * if the file content could not be read successfully */ @@ -74,7 +74,7 @@ public class TestArtifactGeneratorToscaParser { /** * Initialize the Generator with no Widget Mappings content. - * + * * @throws IOException * if the file content could not be read successfully */ @@ -88,7 +88,7 @@ public class TestArtifactGeneratorToscaParser { /** * Initialize the Generator with invalid Widget Mappings content. - * + * * @throws IOException * if the file content could not be read successfully */ @@ -137,7 +137,7 @@ public class TestArtifactGeneratorToscaParser { /** * Initialize the Artifact Generator Widget Mapping config with incomplete data (no type). - * + * * @throws IOException * if a WidgetMapping is invalid */ @@ -152,7 +152,7 @@ public class TestArtifactGeneratorToscaParser { /** * Initialize the Artifact Generator Widget Mapping config with invalid data (type value). - * + * * @throws IOException * if a WidgetMapping is invalid */ @@ -167,7 +167,7 @@ public class TestArtifactGeneratorToscaParser { /** * Initialize the Artifact Generator Widget Mapping config with incomplete data (no widget name). - * + * * @throws IOException * if a WidgetMapping is invalid */ @@ -207,7 +207,7 @@ public class TestArtifactGeneratorToscaParser { /** * Process a dummy Group object for a Service Resource. - * + * * @throws XmlArtifactGenerationException * if there is no configuration defined for a member Widget of an instance group * @throws IOException diff --git a/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java b/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java index 5ceca17..3070566 100644 --- a/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java +++ b/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java @@ -34,7 +34,6 @@ import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.Optional; -import javax.inject.Inject; import javax.security.auth.x500.X500Principal; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedHashMap; @@ -48,22 +47,23 @@ import org.onap.aai.auth.AAIMicroServiceAuth; import org.onap.aai.babel.service.data.BabelRequest; import org.onap.aai.babel.testdata.CsarTest; import org.onap.aai.babel.util.ArtifactTestUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * Direct invocation of the generate artifacts service implementation. * */ -@SpringJUnitConfig(locations = {"classpath:/babel-beans.xml"}) +@SpringBootTest public class TestGenerateArtifactsServiceImpl { static { System.setProperty("CONFIG_HOME", "src/test/resources"); } - @Inject - private AAIMicroServiceAuth auth; + @Autowired + private Gson gson; @BeforeAll public static void setup() { @@ -81,7 +81,7 @@ public class TestGenerateArtifactsServiceImpl { */ @Test public void testGenerateArtifacts() throws URISyntaxException, IOException { - Response response = processJsonRequest(CsarTest.VNF_VENDOR_CSAR, auth); + Response response = processJsonRequest(CsarTest.VNF_VENDOR_CSAR); assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(response.getEntity(), is(getResponseJson("response.json"))); } @@ -96,11 +96,11 @@ public class TestGenerateArtifactsServiceImpl { */ @Test public void testGenerateArtifactsWithoutRequestId() throws URISyntaxException, IOException { - Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequest(), Optional.empty(), auth); + Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequest(), Optional.empty()); assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(response.getEntity(), is(getResponseJson("response.json"))); } - + /** * Test with a valid request without Minor Artifact version. * @@ -112,11 +112,11 @@ public class TestGenerateArtifactsServiceImpl { @Test public void testGenerateArtifactsWithoutMinorArtifactVersion() throws URISyntaxException, IOException { Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequestWithArtifactVersion("1"), - Optional.of("transaction-id"), auth); + Optional.of("transaction-id")); assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(response.getEntity(), is(getResponseJson("response.json"))); } - + /** * Test with a valid request without Minor Artifact version. * @@ -128,12 +128,12 @@ public class TestGenerateArtifactsServiceImpl { @Test public void testGenerateArtifactsWithInvalidArtifactVersion() throws URISyntaxException, IOException { Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequestWithArtifactVersion("a"), - Optional.of("transaction-id"), auth); + Optional.of("transaction-id")); assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(response.getEntity(), is(getResponseJson("response.json"))); } - - + + /** * Test with a valid request with Artifact version less than 1. * @@ -145,7 +145,7 @@ public class TestGenerateArtifactsServiceImpl { @Test public void testGenerateArtifactsWithArtifactVerLessThan1() throws URISyntaxException, IOException { Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequestWithArtifactVersion("0.1"), - Optional.of("transaction-id"), auth); + Optional.of("transaction-id")); assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(response.getEntity(), is(getResponseJson("responseWithVersionLessThan1.json"))); } @@ -161,7 +161,7 @@ public class TestGenerateArtifactsServiceImpl { */ @Test public void testGenerateArtifactsWithoutVnfConfiguration() throws IOException, URISyntaxException { - Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, auth); + Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR); assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(response.getEntity(), is(getResponseJson("validNoVnfConfigurationResponse.json"))); } @@ -176,31 +176,11 @@ public class TestGenerateArtifactsServiceImpl { */ @Test public void testGenerateArtifactsInvalidCsar() throws IOException, URISyntaxException { - Response response = processJsonRequest(CsarTest.MULTIPLE_VNF_CSAR, auth); + Response response = processJsonRequest(CsarTest.MULTIPLE_VNF_CSAR); assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); assertThat(response.getEntity().toString(), containsString("VNF catalog")); } - @Test - public void testUninitializedService() throws IOException, URISyntaxException, AAIAuthException { - AAIMicroServiceAuth uninitializedAuth = Mockito.mock(AAIMicroServiceAuth.class); - Mockito.when(uninitializedAuth.validateRequest(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenThrow(new AAIAuthException("test")); - Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, uninitializedAuth); - assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); - assertThat(response.getEntity().toString(), containsString("check the Babel service logs")); - } - - @Test - public void testUnauthorizedRequest() throws IOException, URISyntaxException, AAIAuthException { - AAIMicroServiceAuth uninitializedAuth = Mockito.mock(AAIMicroServiceAuth.class); - Mockito.when(uninitializedAuth.validateRequest(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(false); - Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, uninitializedAuth); - assertThat(response.getStatus(), is(Response.Status.UNAUTHORIZED.getStatusCode())); - assertThat(response.getEntity().toString(), containsString("User not authorized")); - } - @Test public void testInvalidCsarFile() throws URISyntaxException, IOException { BabelRequest request = new BabelRequest(); @@ -262,9 +242,9 @@ public class TestGenerateArtifactsServiceImpl { * @throws IOException * if the resource cannot be loaded */ - private Response processJsonRequest(CsarTest csar, AAIMicroServiceAuth auth) + private Response processJsonRequest(CsarTest csar) throws URISyntaxException, IOException { - return invokeService(csar.getJsonRequest(), Optional.of("transaction-id"), auth); + return invokeService(csar.getJsonRequest(), Optional.of("transaction-id")); } /** @@ -277,7 +257,7 @@ public class TestGenerateArtifactsServiceImpl { * if the URI cannot be created */ private Response invokeService(String jsonRequest) throws URISyntaxException { - return invokeService(jsonRequest, Optional.of("transaction-id"), auth); + return invokeService(jsonRequest, Optional.of("transaction-id")); } /** @@ -293,7 +273,7 @@ public class TestGenerateArtifactsServiceImpl { * @throws URISyntaxException * if the URI cannot be created */ - private Response invokeService(String jsonString, Optional transactionId, AAIMicroServiceAuth auth) + private Response invokeService(String jsonString, Optional transactionId) throws URISyntaxException { UriInfo mockUriInfo = Mockito.mock(UriInfo.class); Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked) @@ -329,7 +309,7 @@ public class TestGenerateArtifactsServiceImpl { servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] {mockCertificate}); servletRequest.setAttribute("javax.servlet.request.cipher_suite", ""); - GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth); + GenerateArtifactsControllerImpl service = new GenerateArtifactsControllerImpl(gson); return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString); } diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 2f24f8b..8c3bd59 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -1 +1 @@ -spring.sleuth.enabled=true \ No newline at end of file +spring.sleuth.enabled=false -- cgit 1.2.3-korg