Create logic responsible for selecting server based on CAName
authorBartosz Gardziejewski <bartosz.gardziejewski@nokia.com>
Wed, 26 Feb 2020 08:08:35 +0000 (09:08 +0100)
committerBartosz Gardziejewski <bartosz.gardziejewski@nokia.com>
Wed, 26 Feb 2020 13:11:34 +0000 (14:11 +0100)
Issue-ID: AAF-995
Signed-off-by: Bartosz Gardziejewski <bartosz.gardziejewski@nokia.com>
Change-Id: I2d3b931862ecca7c1edc52fb61aa8c4dcd29e3ec

certService/src/main/java/org/onap/aaf/certservice/api/CertificationService.java
certService/src/main/java/org/onap/aaf/certservice/certification/CertificationExceptionController.java
certService/src/main/java/org/onap/aaf/certservice/certification/CertificationModelFactory.java
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/Cmpv2ServerProvider.java [new file with mode: 0644]
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/model/Authentication.java
certService/src/main/java/org/onap/aaf/certservice/certification/configuration/model/Cmpv2Server.java
certService/src/main/java/org/onap/aaf/certservice/certification/exception/Cmpv2ServerNotFoundException.java [new file with mode: 0644]
certService/src/test/java/org/onap/aaf/certservice/certification/CertificationExceptionControllerTest.java [moved from certService/src/test/java/org/onap/aaf/certservice/certification/exception/CertificationExceptionControllerTest.java with 72% similarity]
certService/src/test/java/org/onap/aaf/certservice/certification/CertificationModelFactoryTest.java
certService/src/test/java/org/onap/aaf/certservice/certification/configuration/Cmpv2ServerProviderTest.java [new file with mode: 0644]

index d2de1aa..945fc6d 100644 (file)
@@ -76,7 +76,7 @@ public class CertificationService {
         );
         LOGGER.debug("Received CSR meta data: \n{}", csrModel);
         CertificationModel certificationModel = certificationModelFactory
-                .createCertificationModel(csrModel,caName);
+                .createCertificationModel(csrModel, caName);
         return new ResponseEntity<>(new Gson().toJson(certificationModel), HttpStatus.OK);
 
     }
index 4c9d304..130a516 100644 (file)
@@ -21,6 +21,7 @@
 package org.onap.aaf.certservice.certification;
 
 import com.google.gson.Gson;
+import org.onap.aaf.certservice.certification.exception.Cmpv2ServerNotFoundException;
 import org.onap.aaf.certservice.certification.exception.CsrDecryptionException;
 import org.onap.aaf.certservice.certification.exception.ErrorResponseModel;
 import org.onap.aaf.certservice.certification.exception.KeyDecryptionException;
@@ -39,20 +40,27 @@ public class CertificationExceptionController {
     @ExceptionHandler(value = CsrDecryptionException.class)
     public ResponseEntity<String> handle(CsrDecryptionException exception) {
         LOGGER.error("Exception occurred during decoding certificate sign request:", exception);
-        return getErrorResponseEntity("Wrong certificate signing request (CSR) format");
+        return getErrorResponseEntity("Wrong certificate signing request (CSR) format", HttpStatus.BAD_REQUEST);
     }
 
     @ExceptionHandler(value = KeyDecryptionException.class)
     public ResponseEntity<String> handle(KeyDecryptionException exception) {
         LOGGER.error("Exception occurred during decoding key:", exception);
-        return getErrorResponseEntity("Wrong key (PK) format");
+        return getErrorResponseEntity("Wrong key (PK) format", HttpStatus.BAD_REQUEST);
     }
 
-    private ResponseEntity<String> getErrorResponseEntity(String errorMessage) {
+    @ExceptionHandler(value = Cmpv2ServerNotFoundException.class)
+    public ResponseEntity<String> handle(Cmpv2ServerNotFoundException exception) {
+        LOGGER.error("Exception occurred selecting CMPv2 server:", exception);
+        return getErrorResponseEntity("Certification authority not found for given CAName", HttpStatus.NOT_FOUND);
+    }
+
+    private ResponseEntity<String> getErrorResponseEntity(String errorMessage, HttpStatus status) {
         ErrorResponseModel errorResponse = new ErrorResponseModel(errorMessage);
         return new ResponseEntity<>(
                 new Gson().toJson(errorResponse),
-                HttpStatus.BAD_REQUEST
+                status
         );
     }
+
 }
index 507ce3c..69b8346 100644 (file)
 
 package org.onap.aaf.certservice.certification;
 
+import org.onap.aaf.certservice.certification.configuration.Cmpv2ServerProvider;
+import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server;
+import org.onap.aaf.certservice.certification.exception.Cmpv2ServerNotFoundException;
 import org.onap.aaf.certservice.certification.model.CertificationModel;
 import org.onap.aaf.certservice.certification.model.CsrModel;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.util.Arrays;
@@ -38,14 +42,28 @@ public class CertificationModelFactory {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(CertificationModelFactory.class);
 
+    private final Cmpv2ServerProvider cmpv2ServerProvider;
+
+    @Autowired
+    CertificationModelFactory(Cmpv2ServerProvider cmpv2ServerProvider) {
+        this.cmpv2ServerProvider = cmpv2ServerProvider;
+    }
 
     public CertificationModel createCertificationModel(CsrModel csr, String caName) {
         LOGGER.info("Generating certification model for CA named: {}, and certificate signing request:\n{}",
                 caName, csr);
+
+        return cmpv2ServerProvider
+                .getCmpv2Server(caName)
+                .map(this::generateCertificationModel)
+                .orElseThrow(() -> new Cmpv2ServerNotFoundException("No server found for given CA name"));
+    }
+
+    private CertificationModel generateCertificationModel(Cmpv2Server cmpv2Server) {
+        LOGGER.debug("Found server for given CA name: \n{}", cmpv2Server);
         return new CertificationModel(
                 Arrays.asList(ENTITY_CERT, INTERMEDIATE_CERT),
                 Arrays.asList(CA_CERT, EXTRA_CA_CERT)
         );
     }
-
 }
diff --git a/certService/src/main/java/org/onap/aaf/certservice/certification/configuration/Cmpv2ServerProvider.java b/certService/src/main/java/org/onap/aaf/certservice/certification/configuration/Cmpv2ServerProvider.java
new file mode 100644 (file)
index 0000000..755bfeb
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. 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.aaf.certservice.certification.configuration;
+
+import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.Optional;
+
+@Component
+public class Cmpv2ServerProvider {
+
+    private final CmpServersConfig cmpServersConfig;
+
+    @Autowired
+    Cmpv2ServerProvider(CmpServersConfig cmpServersConfig) {
+        this.cmpServersConfig = cmpServersConfig;
+    }
+
+    public Optional<Cmpv2Server> getCmpv2Server(String caName) {
+        return cmpServersConfig.getCmpServers()
+                .stream()
+                .filter(server -> server.getCaName().equals(caName))
+                .findFirst();
+    }
+
+}
index ffd63ec..af254d6 100644 (file)
@@ -45,4 +45,11 @@ public class Authentication {
         this.rv = rv;
     }
 
+    @Override
+    public String toString() {
+        return "Authentication{" +
+                "  iak=*****" +
+                ", rv=*****" +
+                '}';
+    }
 }
index 21349d9..9a9f9c5 100644 (file)
@@ -77,4 +77,15 @@ public class Cmpv2Server {
         this.url = url;
     }
 
+    @Override
+    public String toString() {
+        return "Cmpv2Server{" +
+                "authentication=" + authentication +
+                ", caMode=" + caMode +
+                ", caName='" + caName + '\'' +
+                ", issuerDN='" + issuerDN + '\'' +
+                ", url='" + url + '\'' +
+                '}';
+    }
+
 }
diff --git a/certService/src/main/java/org/onap/aaf/certservice/certification/exception/Cmpv2ServerNotFoundException.java b/certService/src/main/java/org/onap/aaf/certservice/certification/exception/Cmpv2ServerNotFoundException.java
new file mode 100644 (file)
index 0000000..95d4cd6
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. 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.aaf.certservice.certification.exception;
+
+import org.webjars.NotFoundException;
+
+public class Cmpv2ServerNotFoundException extends NotFoundException {
+    public Cmpv2ServerNotFoundException(String message) {
+        super(message);
+    }
+}
  * ============LICENSE_END=========================================================
  */
 
-package org.onap.aaf.certservice.certification.exception;
+package org.onap.aaf.certservice.certification;
 
 import com.google.gson.Gson;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
-import org.onap.aaf.certservice.certification.CertificationExceptionController;
+import org.onap.aaf.certservice.certification.exception.Cmpv2ServerNotFoundException;
+import org.onap.aaf.certservice.certification.exception.CsrDecryptionException;
+import org.onap.aaf.certservice.certification.exception.ErrorResponseModel;
+import org.onap.aaf.certservice.certification.exception.KeyDecryptionException;
 import org.springframework.http.ResponseEntity;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -68,4 +71,18 @@ class CertificationExceptionControllerTest {
         assertEquals(expectedMessage, response.getErrorMessage());
     }
 
+    @Test
+    void shouldReturnResponseEntityWithAppropriateErrorMessageWhenGivenCaNameIsNotPresentInConfig() {
+        // given
+        String expectedMessage = "Certification authority not found for given CAName";
+        Cmpv2ServerNotFoundException csrDecryptionException = new Cmpv2ServerNotFoundException("test Ca exception");
+
+        // when
+        ResponseEntity<String> responseEntity = certificationExceptionController.handle(csrDecryptionException);
+
+        ErrorResponseModel response = new Gson().fromJson(responseEntity.getBody(), ErrorResponseModel.class);
+
+        // then
+        assertEquals(expectedMessage, response.getErrorMessage());
+    }
 }
index 2953af7..50e604e 100644 (file)
@@ -22,36 +22,52 @@ package org.onap.aaf.certservice.certification;
 
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.onap.aaf.certservice.certification.configuration.Cmpv2ServerProvider;
+import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server;
+import org.onap.aaf.certservice.certification.exception.Cmpv2ServerNotFoundException;
 import org.onap.aaf.certservice.certification.model.CertificationModel;
 import org.onap.aaf.certservice.certification.model.CsrModel;
 
+import java.util.Optional;
+
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 import static org.onap.aaf.certservice.certification.CertificationData.CA_CERT;
 import static org.onap.aaf.certservice.certification.CertificationData.ENTITY_CERT;
 import static org.onap.aaf.certservice.certification.CertificationData.INTERMEDIATE_CERT;
 import static org.onap.aaf.certservice.certification.CertificationData.EXTRA_CA_CERT;
 
-
+@ExtendWith(MockitoExtension.class)
 class CertificationModelFactoryTest {
 
+    private static final String TEST_CA = "testCA";
 
     private CertificationModelFactory certificationModelFactory;
 
+    @Mock
+    Cmpv2ServerProvider cmpv2ServerProvider;
+
     @BeforeEach
     void setUp() {
-        certificationModelFactory = new CertificationModelFactory();
+        certificationModelFactory = new CertificationModelFactory(cmpv2ServerProvider);
     }
 
     @Test
     void shouldCreateProperCertificationModelWhenGivenProperCsrModelAndCaName() {
         // given
-        final String testCaName = "testCA";
         CsrModel mockedCsrModel = mock(CsrModel.class);
+        when(cmpv2ServerProvider.getCmpv2Server(TEST_CA)).thenReturn(Optional.of(createTestCmpv2Server()));
 
         // when
-        CertificationModel certificationModel = certificationModelFactory.createCertificationModel(mockedCsrModel ,testCaName);
+        CertificationModel certificationModel =
+                certificationModelFactory.createCertificationModel(mockedCsrModel ,TEST_CA);
 
         //then
         assertEquals(2, certificationModel.getCertificateChain().size());
@@ -60,4 +76,24 @@ class CertificationModelFactoryTest {
         assertThat(certificationModel.getTrustedCertificates()).contains(CA_CERT, EXTRA_CA_CERT);
     }
 
+    @Test
+    void shouldThrowCmpv2ServerNotFoundExceptionWhenGivenWrongCaName() {
+        // given
+        String expectedMessage = "CA not found";
+        CsrModel mockedCsrModel = mock(CsrModel.class);
+        when(cmpv2ServerProvider.getCmpv2Server(TEST_CA)).thenThrow(new Cmpv2ServerNotFoundException(expectedMessage));
+
+        // when
+        Exception exception = assertThrows(
+                Cmpv2ServerNotFoundException.class, () ->
+                        certificationModelFactory.createCertificationModel(mockedCsrModel ,TEST_CA)
+        );
+
+        // then
+        assertTrue(exception.getMessage().contains(expectedMessage));
+    }
+
+    private Cmpv2Server createTestCmpv2Server() {
+        return new Cmpv2Server();
+    }
 }
diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/Cmpv2ServerProviderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/Cmpv2ServerProviderTest.java
new file mode 100644 (file)
index 0000000..d3c09e9
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. 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.aaf.certservice.certification.configuration;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.onap.aaf.certservice.certification.configuration.model.Authentication;
+import org.onap.aaf.certservice.certification.configuration.model.CaMode;
+import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server;
+
+import java.util.Collections;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+class Cmpv2ServerProviderTest {
+
+    private static final String TEST_CA = "testCA";
+
+    private Cmpv2ServerProvider cmpv2ServerProvider;
+
+    @Mock
+    private CmpServersConfig cmpServersConfig;
+
+    @BeforeEach
+    void setUp() {
+        cmpv2ServerProvider =
+                new  Cmpv2ServerProvider(cmpServersConfig);
+    }
+
+    @Test
+    void shouldReturnOptionalWithServerWhenServerWithGivenCaNameIsPresentInConfig() {
+        // given
+        Cmpv2Server testServer = createTestServer();
+        when(cmpServersConfig.getCmpServers()).thenReturn(Collections.singletonList(testServer));
+
+        // when
+        Cmpv2Server receivedServer = cmpv2ServerProvider
+                .getCmpv2Server(TEST_CA)
+                .get();
+
+        // then
+        assertThat(receivedServer).isEqualToComparingFieldByField(testServer);
+    }
+
+
+    @Test
+    void shouldReturnEmptyOptionalWhenServerWithGivenCaNameIsNotPresentInConfig() {
+        // given
+        when(cmpServersConfig.getCmpServers()).thenReturn(Collections.emptyList());
+
+        // when
+        Boolean isEmpty = cmpv2ServerProvider
+                .getCmpv2Server(TEST_CA)
+                .isEmpty();
+
+        // then
+        assertThat(isEmpty).isTrue();
+    }
+
+    private Cmpv2Server createTestServer() {
+        Cmpv2Server testServer = new Cmpv2Server();
+        testServer.setCaName(TEST_CA);
+        testServer.setIssuerDN("testIssuer");
+        testServer.setUrl("http://test.ca.server");
+        Authentication testAuthentication = new Authentication();
+        testAuthentication.setIak("testIak");
+        testAuthentication.setRv("testRv");
+        testServer.setAuthentication(testAuthentication);
+        testServer.setCaMode(CaMode.RA);
+
+        return testServer;
+    }
+}