diff options
Diffstat (limited to 'certService/src/test/java')
22 files changed, 465 insertions, 446 deletions
diff --git a/certService/src/test/java/org/onap/aaf/certservice/CertServiceApplicationTests.java b/certService/src/test/java/org/onap/aaf/certservice/CertServiceApplicationTests.java index ae284da3..0dc60aa5 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/CertServiceApplicationTests.java +++ b/certService/src/test/java/org/onap/aaf/certservice/CertServiceApplicationTests.java @@ -27,8 +27,8 @@ import org.springframework.boot.test.context.SpringBootTest; class CertServiceApplicationTests { @Test - // We are excluding this line in Sonar due to fact that - // this test checks if Spring context is loaded and does not require assertion + // We are excluding this line in Sonar due to fact that + // this test checks if Spring context is loaded and does not require assertion void contextLoads() { // NOSONAR } } diff --git a/certService/src/test/java/org/onap/aaf/certservice/api/CertificationControllerTest.java b/certService/src/test/java/org/onap/aaf/certservice/api/CertificationControllerTest.java index 8ebac689..449670c3 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/api/CertificationControllerTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/api/CertificationControllerTest.java @@ -26,6 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import java.util.Arrays; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/certService/src/test/java/org/onap/aaf/certservice/api/ReadinessControllerTest.java b/certService/src/test/java/org/onap/aaf/certservice/api/ReadinessControllerTest.java index 4000a38b..d3ed7301 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/api/ReadinessControllerTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/api/ReadinessControllerTest.java @@ -42,7 +42,8 @@ public class ReadinessControllerTest { Mockito.when(cmpServersConfig.isReady()).thenReturn(true); // Then - assertThat(new ReadinessController(cmpServersConfig).checkReady().getStatusCode()).isEqualTo(HttpStatus.OK);; + assertThat(new ReadinessController(cmpServersConfig).checkReady().getStatusCode()).isEqualTo(HttpStatus.OK); + ; } @Test @@ -51,7 +52,8 @@ public class ReadinessControllerTest { Mockito.when(cmpServersConfig.isReady()).thenReturn(false); // Then - assertThat(new ReadinessController(cmpServersConfig).checkReady().getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);; + assertThat(new ReadinessController(cmpServersConfig).checkReady().getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + ; } } diff --git a/certService/src/test/java/org/onap/aaf/certservice/api/ReloadConfigControllerTest.java b/certService/src/test/java/org/onap/aaf/certservice/api/ReloadConfigControllerTest.java index 5e0e355c..92c18e16 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/api/ReloadConfigControllerTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/api/ReloadConfigControllerTest.java @@ -66,8 +66,8 @@ public class ReloadConfigControllerTest { // When Exception exception = assertThrows( - CmpServersConfigLoadingException.class, - () -> reloadConfigController.reloadConfiguration()); + CmpServersConfigLoadingException.class, + () -> reloadConfigController.reloadConfiguration()); // Then Assertions.assertThat(exception.getMessage()).isEqualTo(ERROR_MESSAGE); diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationModelFactoryTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationModelFactoryTest.java index 1b896a4b..a63c8e0e 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationModelFactoryTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationModelFactoryTest.java @@ -69,9 +69,9 @@ class CertificationModelFactoryTest { @Mock private Cmpv2ServerProvider cmpv2ServerProvider; @Mock - private CsrModelFactory csrModelFactory; + private CsrModelFactory csrModelFactory; @Mock - private CertificationProvider certificationProvider; + private CertificationProvider certificationProvider; private static String getEncodedString(String testCsr) { @@ -95,7 +95,7 @@ class CertificationModelFactoryTest { // When CertificationModel certificationModel = - certificationModelFactory.createCertificationModel(ENCODED_CSR, ENCODED_PK,TEST_CA); + certificationModelFactory.createCertificationModel(ENCODED_CSR, ENCODED_PK, TEST_CA); // Then assertEquals(2, certificationModel.getCertificateChain().size()); @@ -105,7 +105,7 @@ class CertificationModelFactoryTest { } @Test - void shouldThrowDecryptionExceptionWhenGivenWrongEncodedCSR() + void shouldThrowDecryptionExceptionWhenGivenWrongEncodedCsr() throws DecryptionException { // Given String expectedMessage = "Incorrect CSR, decryption failed"; diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationProviderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationProviderTest.java index aa6f1d08..f75bd608 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationProviderTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationProviderTest.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aaf.certservice.certification; import org.junit.jupiter.api.BeforeEach; diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/CsrModelFactoryTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/CsrModelFactoryTest.java index 772f456f..d2c3c54c 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/CsrModelFactoryTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/CsrModelFactoryTest.java @@ -127,7 +127,7 @@ class CsrModelFactoryTest { } @Test - void shouldThrowKeyDecryptionExceptionWhenPKIsNotInBase64Encoding() { + void shouldThrowKeyDecryptionExceptionWhenPkIsNotInBase64Encoding() { // given String encoderPK = "Not Base64 Key"; String wrongCsr = new String(Base64.encode(TEST_CSR.getBytes())); diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapterTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapterTest.java index 296f63cd..32fd2074 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapterTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapterTest.java @@ -22,7 +22,6 @@ package org.onap.aaf.certservice.certification.adapter; import java.io.IOException; import java.io.InputStream; -import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.security.NoSuchProviderException; import java.security.PrivateKey; @@ -32,6 +31,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; + import org.apache.commons.io.IOUtils; import org.bouncycastle.asn1.x509.Certificate; import org.bouncycastle.cert.X509CertificateHolder; @@ -51,7 +51,7 @@ import org.onap.aaf.certservice.certification.model.CertificationModel; import org.onap.aaf.certservice.certification.model.CsrModel; import org.onap.aaf.certservice.cmpv2client.api.CmpClient; import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException; -import org.onap.aaf.certservice.cmpv2client.external.CSRMeta; +import org.onap.aaf.certservice.cmpv2client.external.CsrMeta; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest @@ -64,7 +64,7 @@ class Cmpv2ClientAdapterTest { @Mock private Cmpv2Server server; @Mock - private RSAContentSignerBuilder rsaContentSignerBuilder; + private RsaContentSignerBuilder rsaContentSignerBuilder; @Mock private X509CertificateBuilder x509CertificateBuilder; @Mock @@ -84,9 +84,9 @@ class Cmpv2ClientAdapterTest { @Mock private CertificateFactoryProvider certificateFactoryProvider; @Mock - private CSRMetaBuilder csrMetaBuilder; + private CsrMetaBuilder csrMetaBuilder; @Mock - private CSRMeta csrMeta; + private CsrMeta csrMeta; @InjectMocks private Cmpv2ClientAdapter adapter; @@ -97,7 +97,7 @@ class Cmpv2ClientAdapterTest { @Test void adapterShouldRethrowClientExceptionOnFailure() throws CmpClientException, IOException, OperatorCreationException, CertificateException, - NoSuchProviderException { + NoSuchProviderException { // Given stubInternalProperties(); @@ -112,7 +112,7 @@ class Cmpv2ClientAdapterTest { @Test void shouldConvertToCertificationModel() throws OperatorCreationException, CertificateException, NoSuchProviderException, IOException, - CmpClientException, Cmpv2ClientAdapterException { + CmpClientException, Cmpv2ClientAdapterException { // Given stubInternalProperties(); @@ -139,7 +139,7 @@ class Cmpv2ClientAdapterTest { @Test void adapterShouldThrowClientAdapterExceptionOnFailure() throws OperatorCreationException, CertificateException, NoSuchProviderException, IOException, - CmpClientException { + CmpClientException { // Given stubInternalProperties(); diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CSRMetaBuilderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilderTest.java index adb89b31..feb4bdba 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CSRMetaBuilderTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilderTest.java @@ -28,7 +28,7 @@ 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 org.onap.aaf.certservice.certification.model.CsrModel; -import org.onap.aaf.certservice.cmpv2client.external.CSRMeta; +import org.onap.aaf.certservice.cmpv2client.external.CsrMeta; import java.security.PrivateKey; import java.security.PublicKey; @@ -39,16 +39,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class CSRMetaBuilderTest { +public class CsrMetaBuilderTest { - private CSRMetaBuilder csrMetaBuilder; + private CsrMetaBuilder csrMetaBuilder; private static final String TEST_CA = "testCA"; private static final X500Name TEST_SUBJECT_DATA = new X500Name("CN=testIssuer"); @BeforeEach void setUp() { - csrMetaBuilder = new CSRMetaBuilder(); + csrMetaBuilder = new CsrMetaBuilder(); } @Test @@ -63,23 +63,23 @@ public class CSRMetaBuilderTest { when(testCsrModel.getPrivateKey()).thenReturn(mockPrivateKey); PublicKey mockPublicKey = mock(PublicKey.class); when(testCsrModel.getPublicKey()).thenReturn(mockPublicKey); - List<String> testSans = Arrays.asList("SAN01","SAN02"); + List<String> testSans = Arrays.asList("SAN01", "SAN02"); when(testCsrModel.getSans()).thenReturn(testSans); when(testCsrModel.getSubjectData()).thenReturn(TEST_SUBJECT_DATA); // When - CSRMeta createdCSRMeta = csrMetaBuilder.build(testCsrModel, testServer); + CsrMeta createdCsrMeta = csrMetaBuilder.build(testCsrModel, testServer); // Then - assertThat(createdCSRMeta.getPassword()).isEqualTo(testServer.getAuthentication().getIak()); - assertThat(createdCSRMeta.getSenderKid()).isEqualTo(testServer.getAuthentication().getRv()); - assertThat(createdCSRMeta.getCaUrl()).isEqualTo(testServer.getUrl()); - assertThat(createdCSRMeta.getSans()).containsAll(testSans); - assertThat(createdCSRMeta.getKeyPair().getPrivate()).isEqualTo(mockPrivateKey); - assertThat(createdCSRMeta.getKeyPair().getPublic()).isEqualTo(mockPublicKey); - assertThat(createdCSRMeta.getX500Name()).isEqualTo(TEST_SUBJECT_DATA); - assertThat(createdCSRMeta.getIssuerX500Name()).isEqualTo(TEST_SUBJECT_DATA); + assertThat(createdCsrMeta.getPassword()).isEqualTo(testServer.getAuthentication().getIak()); + assertThat(createdCsrMeta.getSenderKid()).isEqualTo(testServer.getAuthentication().getRv()); + assertThat(createdCsrMeta.getCaUrl()).isEqualTo(testServer.getUrl()); + assertThat(createdCsrMeta.getSans()).containsAll(testSans); + assertThat(createdCsrMeta.getKeyPair().getPrivate()).isEqualTo(mockPrivateKey); + assertThat(createdCsrMeta.getKeyPair().getPublic()).isEqualTo(mockPublicKey); + assertThat(createdCsrMeta.getX500Name()).isEqualTo(TEST_SUBJECT_DATA); + assertThat(createdCsrMeta.getIssuerX500Name()).isEqualTo(TEST_SUBJECT_DATA); } private Cmpv2Server createTestServer() { diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/RSAContentSignerBuilderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/RsaContentSignerBuilderTest.java index 3c5c534c..44669216 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/RSAContentSignerBuilderTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/RsaContentSignerBuilderTest.java @@ -34,13 +34,13 @@ import java.security.PrivateKey; import static org.assertj.core.api.Assertions.assertThat; import static org.onap.aaf.certservice.certification.TestUtils.createCsrModel; -class RSAContentSignerBuilderTest { +class RsaContentSignerBuilderTest { - private RSAContentSignerBuilder rsaContentSignerBuilder; + private RsaContentSignerBuilder rsaContentSignerBuilder; @BeforeEach void setUp() { - rsaContentSignerBuilder = new RSAContentSignerBuilder(); + rsaContentSignerBuilder = new RsaContentSignerBuilder(); } @Test diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/X509CertificateBuilderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/X509CertificateBuilderTest.java index 26d11fc3..d53c6c72 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/X509CertificateBuilderTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/X509CertificateBuilderTest.java @@ -53,7 +53,7 @@ public class X509CertificateBuilderTest { CsrModel testCsrModel = createCsrModel(); PKCS10CertificationRequest testCertificationRequest = testCsrModel.getCsr(); PrivateKey testPrivateKey = testCsrModel.getPrivateKey(); - RSAContentSignerBuilder rsaContentSignerBuilder = new RSAContentSignerBuilder(); + RsaContentSignerBuilder rsaContentSignerBuilder = new RsaContentSignerBuilder(); ContentSigner createdContentSigner = rsaContentSignerBuilder.build(testCertificationRequest, testPrivateKey); // When diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigLoaderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigLoaderTest.java index c78f6ceb..61970050 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigLoaderTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigLoaderTest.java @@ -25,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; import java.util.Map; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.onap.aaf.certservice.CertServiceApplication; @@ -79,8 +80,8 @@ class CmpServersConfigLoaderTest { void shouldThrowExceptionWhenFileMissing() { // When Exception exception = assertThrows( - CmpServersConfigLoadingException.class, - () -> configLoader.load(NONEXISTENT_CONFIG_FILENAME)); + CmpServersConfigLoadingException.class, + () -> configLoader.load(NONEXISTENT_CONFIG_FILENAME)); // Then assertThat(exception.getMessage()).contains("Exception occurred during CMP Servers configuration loading"); @@ -93,8 +94,8 @@ class CmpServersConfigLoaderTest { // When Exception exception = assertThrows( - CmpServersConfigLoadingException.class, - () -> configLoader.load(path)); + CmpServersConfigLoadingException.class, + () -> configLoader.load(path)); // Then assertThat(exception.getMessage()).contains("Validation of CMPv2 servers configuration failed"); diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigTest.java index 043dbc03..511c3966 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/CmpServersConfigTest.java @@ -26,6 +26,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.startsWith; import java.util.List; + import org.bouncycastle.asn1.x500.X500Name; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -95,12 +96,12 @@ class CmpServersConfigTest { void shouldRethrowExceptionWhenReloaded() throws CmpServersConfigLoadingException { // Given Mockito.when(cmpServersConfigLoader.load(any())).thenThrow(new CmpServersConfigLoadingException( - ERROR_MESSAGE)); + ERROR_MESSAGE)); // Then assertThrows( - CmpServersConfigLoadingException.class, - () -> cmpServersConfig.reloadConfiguration()); + CmpServersConfigLoadingException.class, + () -> cmpServersConfig.reloadConfiguration()); } @Test @@ -110,8 +111,8 @@ class CmpServersConfigTest { // When Exception exception = assertThrows( - CmpServersConfigLoadingException.class, - () -> cmpServersConfig.reloadConfiguration()); + CmpServersConfigLoadingException.class, + () -> cmpServersConfig.reloadConfiguration()); // Then assertThat(exception.getMessage()).isEqualTo(ERROR_MESSAGE); @@ -128,10 +129,10 @@ class CmpServersConfigTest { // Then receivedCmpServers.forEach((server) -> assertThat(server.toString()) - .doesNotContain( - server.getAuthentication().getIak(), - server.getAuthentication().getRv() - )); + .doesNotContain( + server.getAuthentication().getIak(), + server.getAuthentication().getRv() + )); } @Test @@ -141,8 +142,8 @@ class CmpServersConfigTest { // Then assertThrows( - CmpServersConfigLoadingException.class, - () -> cmpServersConfig.loadConfiguration()); + CmpServersConfigLoadingException.class, + () -> cmpServersConfig.loadConfiguration()); } @Test @@ -152,8 +153,8 @@ class CmpServersConfigTest { // When Exception exception = assertThrows( - CmpServersConfigLoadingException.class, - () -> cmpServersConfig.loadConfiguration()); + CmpServersConfigLoadingException.class, + () -> cmpServersConfig.loadConfiguration()); // Then assertThat(exception.getMessage()).isEqualTo(ERROR_MESSAGE); @@ -201,8 +202,8 @@ class CmpServersConfigTest { // When assertThrows( - CmpServersConfigLoadingException.class, - () -> cmpServersConfig.loadConfiguration()); + CmpServersConfigLoadingException.class, + () -> cmpServersConfig.loadConfiguration()); // Then assertThat(cmpServersConfig.isReady()).isFalse(); 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 index 7e14e470..b83fb9aa 100644 --- 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 @@ -51,7 +51,7 @@ class Cmpv2ServerProviderTest { @BeforeEach void setUp() { cmpv2ServerProvider = - new Cmpv2ServerProvider(cmpServersConfig); + new Cmpv2ServerProvider(cmpServersConfig); } @Test diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/Cmpv2ServerConfigurationValidatorTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/Cmpv2ServerConfigurationValidatorTest.java index 10a7ba46..1c021b43 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/Cmpv2ServerConfigurationValidatorTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/Cmpv2ServerConfigurationValidatorTest.java @@ -54,13 +54,13 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldNotThrowExceptionWhenServerConfigurationIsValid() { + void shouldNotThrowExceptionWhenServerConfigurationIsValid() { // Then assertDoesNotThrow(() -> validator.validate(server)); } @Test - public void shouldThrowExceptionWhenWrongProtocolInURL() { + void shouldThrowExceptionWhenWrongProtocolInUrl() { // Given server.setUrl("https://test.test.test:60000/"); @@ -69,7 +69,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenWrongPortInURL() { + void shouldThrowExceptionWhenWrongPortInUrl() { // Given server.setUrl("http://test.test.test:70000/"); @@ -78,7 +78,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenWrongCANameLength() { + void shouldThrowExceptionWhenWrongCaNameLength() { // Given server.setCaName(EMPTY_STRING); @@ -87,7 +87,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenWrongRVLength() { + void shouldThrowExceptionWhenWrongRvLength() { // Given authentication.setRv(EMPTY_STRING); @@ -97,7 +97,7 @@ class Cmpv2ServerConfigurationValidatorTest { @Test - public void shouldThrowExceptionWhenWrongIAKLength() { + void shouldThrowExceptionWhenWrongIakLength() { // Given authentication.setIak(EMPTY_STRING); @@ -106,7 +106,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenCaNameIsNull() { + void shouldThrowExceptionWhenCaNameIsNull() { // Given server.setCaName(null); @@ -115,7 +115,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenIssuerDnIsNull() { + void shouldThrowExceptionWhenIssuerDnIsNull() { // Given server.setIssuerDN(null); @@ -124,7 +124,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenCaModeIsNull() { + void shouldThrowExceptionWhenCaModeIsNull() { // Given server.setCaMode(null); @@ -133,7 +133,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenUrlIsNull() { + void shouldThrowExceptionWhenUrlIsNull() { // Given server.setUrl(null); @@ -142,7 +142,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenAuthenticationIsNull() { + void shouldThrowExceptionWhenAuthenticationIsNull() { // Given server.setAuthentication(null); @@ -151,7 +151,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenIakIsNull() { + void shouldThrowExceptionWhenIakIsNull() { // Given authentication.setIak(null); @@ -160,7 +160,7 @@ class Cmpv2ServerConfigurationValidatorTest { } @Test - public void shouldThrowExceptionWhenRvIsNull() { + void shouldThrowExceptionWhenRvIsNull() { // Given authentication.setRv(null); diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2URLValidatorTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2UrlValidatorTest.java index 78368d8a..7082626f 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2URLValidatorTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/Cmpv2UrlValidatorTest.java @@ -23,33 +23,35 @@ package org.onap.aaf.certservice.certification.configuration.validation.constrai import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -class Cmpv2URLValidatorTest { - private final Cmpv2URLValidator validator = new Cmpv2URLValidator(); +class Cmpv2UrlValidatorTest { + + private final Cmpv2UrlValidator validator = new Cmpv2UrlValidator(); @Test - public void givenCorrectURLWhenValidatingShouldReturnTrue() { + void givenCorrectUrlWhenValidatingShouldReturnTrue() { //given - String URL = "http://127.0.0.1/ejbca/publicweb/cmp/cmp"; + String url = "http://127.0.0.1/ejbca/publicweb/cmp/cmp"; //when - boolean result = validator.isValid(URL, null); + boolean result = validator.isValid(url, null); //then assertTrue(result); } @Test - public void givenIncorrectURLWhenValidatingShouldReturnFalse() { + void givenIncorrectUrlWhenValidatingShouldReturnFalse() { //given - String URL = "httttp://127.0.0.1:80000/ejbca/publicweb/cmp/cmp"; + String url = "httttp://127.0.0.1:80000/ejbca/publicweb/cmp/cmp"; //when - boolean result = validator.isValid(URL, null); + boolean result = validator.isValid(url, null); //then assertFalse(result); } -}
\ No newline at end of file +} diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/PortNumberViolationTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/PortNumberViolationTest.java index d1850473..e729c738 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/PortNumberViolationTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/PortNumberViolationTest.java @@ -18,28 +18,28 @@ * ============LICENSE_END========================================================= */ - package org.onap.aaf.certservice.certification.configuration.validation.constraints.violations; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; class PortNumberViolationTest { private final PortNumberViolation violation = new PortNumberViolation(); @Test - public void givenValidPortShouldReturnTrue() { + void givenValidPortShouldReturnTrue() { //given - String validURL1 = "http://127.0.0.1:8080/ejbca/publicweb/cmp/cmp"; - String validURL2 = "http://127.0.0.1:1/ejbca/publicweb/cmp/cmp"; - String validURL3 = "http://127.0.0.1:65535/ejbca/publicweb/cmp/cmp"; + String validUrl1 = "http://127.0.0.1:8080/ejbca/publicweb/cmp/cmp"; + String validUrl2 = "http://127.0.0.1:1/ejbca/publicweb/cmp/cmp"; + String validUrl3 = "http://127.0.0.1:65535/ejbca/publicweb/cmp/cmp"; //when - boolean result1 = violation.validate(validURL1); - boolean result2 = violation.validate(validURL2); - boolean result3 = violation.validate(validURL3); + boolean result1 = violation.validate(validUrl1); + boolean result2 = violation.validate(validUrl2); + boolean result3 = violation.validate(validUrl3); //then assertTrue(result1); @@ -48,29 +48,29 @@ class PortNumberViolationTest { } @Test - public void givenEmptyPortShouldReturnTrue() { + void givenEmptyPortShouldReturnTrue() { //given - String validURL = "http://127.0.0.1/ejbca/publicweb/cmp/cmp"; + String validUrl = "http://127.0.0.1/ejbca/publicweb/cmp/cmp"; //when - boolean result = violation.validate(validURL); + boolean result = violation.validate(validUrl); //then assertTrue(result); } @Test - public void givenInvalidPortShouldReturnFalse() { + void givenInvalidPortShouldReturnFalse() { //given - String invalidURL1 = "http://127.0.0.1:0/ejbca/publicweb/cmp/cmp"; - String invalidURL2 = "http://127.0.0.1:65536/ejbca/publicweb/cmp/cmp"; + String invalidUrl1 = "http://127.0.0.1:0/ejbca/publicweb/cmp/cmp"; + String invalidUrl2 = "http://127.0.0.1:65536/ejbca/publicweb/cmp/cmp"; //when - boolean result1 = violation.validate(invalidURL1); - boolean result2 = violation.validate(invalidURL2); + boolean result1 = violation.validate(invalidUrl1); + boolean result2 = violation.validate(invalidUrl2); //then assertFalse(result1); assertFalse(result2); } -}
\ No newline at end of file +} diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/RequestTypeViolationTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/RequestTypeViolationTest.java index cba2f340..dce66d52 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/RequestTypeViolationTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/configuration/validation/constraints/violations/RequestTypeViolationTest.java @@ -22,33 +22,35 @@ package org.onap.aaf.certservice.certification.configuration.validation.constrai import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + class RequestTypeViolationTest { private final RequestTypeViolation violation = new RequestTypeViolation(); @Test - public void givenValidRequestTypeShouldReturnTrue() { + void givenValidRequestTypeShouldReturnTrue() { //given - String validURL = "http://127.0.0.1/ejbca/publicweb/cmp/cmp"; + String validUrl = "http://127.0.0.1/ejbca/publicweb/cmp/cmp"; //when - boolean result = violation.validate(validURL); + boolean result = violation.validate(validUrl); //then assertTrue(result); } @Test - public void givenInvalidRequestTypeShouldReturnFalse() { + void givenInvalidRequestTypeShouldReturnFalse() { //given - String invalidURL = "htestps://127.0.0.1/ejbca/publicweb/cmp/cmp"; + String invalidUrl = "htestps://127.0.0.1/ejbca/publicweb/cmp/cmp"; //when - boolean result = violation.validate(invalidURL); + boolean result = violation.validate(invalidUrl); //then assertFalse(result); } -}
\ No newline at end of file +} diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/model/CsrModelTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/model/CsrModelTest.java index 45bd9664..08bc3368 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/model/CsrModelTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/model/CsrModelTest.java @@ -24,7 +24,7 @@ import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.util.io.pem.PemObject; import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.certification.PKCS10CertificationRequestFactory; +import org.onap.aaf.certservice.certification.Pkcs10CertificationRequestFactory; import org.onap.aaf.certservice.certification.PemObjectFactory; import org.onap.aaf.certservice.certification.exception.CsrDecryptionException; import org.onap.aaf.certservice.certification.exception.DecryptionException; @@ -44,10 +44,11 @@ import static org.onap.aaf.certservice.certification.TestData.TEST_PK; class CsrModelTest { - private final PKCS10CertificationRequestFactory certificationRequestFactory - = new PKCS10CertificationRequestFactory(); + private final Pkcs10CertificationRequestFactory certificationRequestFactory + = new Pkcs10CertificationRequestFactory(); private final PemObjectFactory pemObjectFactory = new PemObjectFactory(); + @Test void shouldByConstructedAndReturnProperFields() throws DecryptionException, IOException { // Given @@ -175,7 +176,7 @@ class CsrModelTest { private PKCS10CertificationRequest generateTestCertificationRequest() throws DecryptionException { return pemObjectFactory.createPemObject(TEST_CSR) .flatMap( - certificationRequestFactory::createKCS10CertificationRequest + certificationRequestFactory::createPkcs10CertificationRequest ).orElseThrow( () -> new DecryptionException("Incorrect CSR, decryption failed") ); diff --git a/certService/src/test/java/org/onap/aaf/certservice/cmpv2Client/Cmpv2ClientTest.java b/certService/src/test/java/org/onap/aaf/certservice/cmpv2Client/Cmpv2ClientTest.java deleted file mode 100644 index a2f3050f..00000000 --- a/certService/src/test/java/org/onap/aaf/certservice/cmpv2Client/Cmpv2ClientTest.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Copyright (C) 2019 Ericsson Software Technology AB. 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 - */ -package org.onap.aaf.certservice.cmpv2Client; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Security; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.impl.client.CloseableHttpClient; -import org.bouncycastle.cert.CertException; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException; -import org.onap.aaf.certservice.cmpv2client.external.CSRMeta; -import org.onap.aaf.certservice.cmpv2client.external.RDN; -import org.onap.aaf.certservice.cmpv2client.impl.CmpClientImpl; - -class Cmpv2ClientTest { - - static { - Security.addProvider(new BouncyCastleProvider()); - } - - private CSRMeta csrMeta; - private Date notBefore; - private Date notAfter; - - @Mock KeyPairGenerator kpg; - - @Mock X509Certificate cert; - - @Mock CloseableHttpClient httpClient; - - @Mock CloseableHttpResponse httpResponse; - - @Mock HttpEntity httpEntity; - - private static KeyPair keyPair; - private static ArrayList<RDN> rdns; - - @BeforeEach - void setUp() - throws NoSuchProviderException, NoSuchAlgorithmException, IOException, - InvalidKeySpecException { - KeyPairGenerator keyGenerator; - keyGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); - keyGenerator.initialize(2048); - keyPair = loadKeyPair(); - rdns = new ArrayList<>(); - try { - rdns.add(new RDN("O=CommonCompany")); - } catch (CertException e) { - e.printStackTrace(); - } - initMocks(this); - } - - public KeyPair loadKeyPair() - throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, - NoSuchProviderException { - - final InputStream privateInputStream = this.getClass().getResourceAsStream("/privateKey"); - final InputStream publicInputStream = this.getClass().getResourceAsStream("/publicKey"); - BufferedInputStream bis = new BufferedInputStream(privateInputStream); - byte[] privateBytes = IOUtils.toByteArray(bis); - bis = new BufferedInputStream(publicInputStream); - byte[] publicBytes = IOUtils.toByteArray(bis); - - KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); - X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicBytes); - PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); - - PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateBytes); - PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); - - return new KeyPair(publicKey, privateKey); - } - - @Test - void shouldReturnValidPkiMessageWhenCreateCertificateRequestMessageMethodCalledWithValidCsr() - throws Exception { - // given - Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); - Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=CommonName", - "CN=ManagementCA", - "CommonName.com", - "CommonName@cn.com", - "mypassword", - "http://127.0.0.1/ejbca/publicweb/cmp/cmp", - "senderKID", - beforeDate, - afterDate); - when(httpClient.execute(any())).thenReturn(httpResponse); - when(httpResponse.getEntity()).thenReturn(httpEntity); - - try (final InputStream is = - this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile"); - BufferedInputStream bis = new BufferedInputStream(is)) { - - byte[] ba = IOUtils.toByteArray(bis); - doAnswer( - invocation -> { - OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0]; - os.write(ba); - return null; - }) - .when(httpEntity) - .writeTo(any(OutputStream.class)); - } - CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); - // when - List<List<X509Certificate>> cmpClientResult = - cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter); - // then - assertNotNull(cmpClientResult); - } - - @Test - void - shouldThrowCmpClientExceptionWhenCreateCertificateRequestMessageMethodCalledWithWrongProtectedBytesInResponse() - throws Exception { - // given - Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); - Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=CommonName", - "CN=ManagementCA", - "CommonName.com", - "CommonName@cn.com", - "password", - "http://127.0.0.1/ejbca/publicweb/cmp/cmp", - "senderKID", - beforeDate, - afterDate); - when(httpClient.execute(any())).thenReturn(httpResponse); - when(httpResponse.getEntity()).thenReturn(httpEntity); - - try (final InputStream is = - this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile"); - BufferedInputStream bis = new BufferedInputStream(is)) { - - byte[] ba = IOUtils.toByteArray(bis); - doAnswer( - invocation -> { - OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0]; - os.write(ba); - return null; - }) - .when(httpEntity) - .writeTo(any(OutputStream.class)); - } - CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); - // then - Assertions.assertThrows( - CmpClientException.class, - () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); - } - - @Test - void shouldThrowCmpClientExceptionWithPkiErrorExceptionWhenCmpClientCalledWithBadPassword() - throws Exception { - // given - Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); - Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=CommonName", - "CN=ManagementCA", - "CommonName.com", - "CommonName@cn.com", - "password", - "http://127.0.0.1/ejbca/publicweb/cmp/cmp", - "senderKID", - beforeDate, - afterDate); - when(httpClient.execute(any())).thenReturn(httpResponse); - when(httpResponse.getEntity()).thenReturn(httpEntity); - - try (final InputStream is = - this.getClass().getResourceAsStream("/ReturnedFailurePKIMessageBadPassword"); - BufferedInputStream bis = new BufferedInputStream(is)) { - - byte[] ba = IOUtils.toByteArray(bis); - doAnswer( - invocation -> { - OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0]; - os.write(ba); - return null; - }) - .when(httpEntity) - .writeTo(any(OutputStream.class)); - } - CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); - - // then - Assertions.assertThrows( - CmpClientException.class, - () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); - } - - @Test - void shouldThrowIllegalArgumentExceptionWhencreateCertificateCalledWithInvalidCsr() - throws ParseException { - // given - Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); - Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=CommonName", - "CN=ManagementCA", - "CommonName.com", - "CommonName@cn.com", - "password", - "http://127.0.0.1/ejbca/publicweb/cmp/cmp", - "senderKID", - beforeDate, - afterDate); - CmpClientImpl cmpClient = new CmpClientImpl(httpClient); - // then - Assertions.assertThrows( - IllegalArgumentException.class, - () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); - } - - @Test - void shouldThrowIOExceptionWhenCreateCertificateCalledWithNoServerAvailable() - throws IOException, ParseException { - // given - Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); - Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=Common", - "CN=CommonCA", - "Common.com", - "Common@cn.com", - "myPassword", - "http://127.0.0.1/ejbca/publicweb/cmp/cmpTest", - "sender", - beforeDate, - afterDate); - when(httpClient.execute(any())).thenThrow(IOException.class); - CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); - // then - Assertions.assertThrows( - CmpClientException.class, - () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); - } - - private void setCsrMetaValuesAndDateValues( - List<RDN> rdns, - String cn, - String issuerCn, - String san, - String email, - String password, - String externalCaUrl, - String senderKid, - Date notBefore, - Date notAfter) { - csrMeta = new CSRMeta(rdns); - csrMeta.setCn(cn); - csrMeta.addSan(san); - csrMeta.setPassword(password); - csrMeta.setEmail(email); - csrMeta.setIssuerCn(issuerCn); - when(kpg.generateKeyPair()).thenReturn(keyPair); - csrMeta.getKeyPairOrGenerateIfNull(); - csrMeta.setCaUrl(externalCaUrl); - csrMeta.setSenderKid(senderKid); - this.notBefore = notBefore; - this.notAfter = notAfter; - } -} diff --git a/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java b/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java new file mode 100644 index 00000000..3f5a2540 --- /dev/null +++ b/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java @@ -0,0 +1,329 @@ +/* + * Copyright (C) 2019 Ericsson Software Technology AB. 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 + */ + +package org.onap.aaf.certservice.cmpv2client; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.impl.client.CloseableHttpClient; +import org.bouncycastle.cert.CertException; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException; +import org.onap.aaf.certservice.cmpv2client.external.CsrMeta; +import org.onap.aaf.certservice.cmpv2client.external.Rdn; +import org.onap.aaf.certservice.cmpv2client.impl.CmpClientImpl; + +class Cmpv2ClientTest { + + static { + Security.addProvider(new BouncyCastleProvider()); + } + + private CsrMeta csrMeta; + private Date notBefore; + private Date notAfter; + + @Mock + KeyPairGenerator kpg; + + @Mock + X509Certificate cert; + + @Mock + CloseableHttpClient httpClient; + + @Mock + CloseableHttpResponse httpResponse; + + @Mock + HttpEntity httpEntity; + + private static KeyPair keyPair; + private static ArrayList<Rdn> rdns; + + @BeforeEach + void setUp() + throws NoSuchProviderException, NoSuchAlgorithmException, IOException, + InvalidKeySpecException { + KeyPairGenerator keyGenerator; + keyGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); + keyGenerator.initialize(2048); + keyPair = loadKeyPair(); + rdns = new ArrayList<>(); + try { + rdns.add(new Rdn("O=CommonCompany")); + } catch (CertException e) { + e.printStackTrace(); + } + initMocks(this); + } + + public KeyPair loadKeyPair() + throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, + NoSuchProviderException { + + final InputStream privateInputStream = this.getClass().getResourceAsStream("/privateKey"); + final InputStream publicInputStream = this.getClass().getResourceAsStream("/publicKey"); + BufferedInputStream bis = new BufferedInputStream(privateInputStream); + byte[] privateBytes = IOUtils.toByteArray(bis); + bis = new BufferedInputStream(publicInputStream); + byte[] publicBytes = IOUtils.toByteArray(bis); + + KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); + X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicBytes); + PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); + + PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateBytes); + PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); + + return new KeyPair(publicKey, privateKey); + } + + @Test + void shouldReturnValidPkiMessageWhenCreateCertificateRequestMessageMethodCalledWithValidCsr() + throws Exception { + // given + Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); + Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); + setCsrMetaValuesAndDateValues( + rdns, + "CN=CommonName", + "CN=ManagementCA", + "CommonName.com", + "CommonName@cn.com", + "mypassword", + "http://127.0.0.1/ejbca/publicweb/cmp/cmp", + "senderKID", + beforeDate, + afterDate); + when(httpClient.execute(any())).thenReturn(httpResponse); + when(httpResponse.getEntity()).thenReturn(httpEntity); + + try (final InputStream is = + this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile"); + BufferedInputStream bis = new BufferedInputStream(is)) { + + byte[] ba = IOUtils.toByteArray(bis); + doAnswer( + invocation -> { + OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0]; + os.write(ba); + return null; + }) + .when(httpEntity) + .writeTo(any(OutputStream.class)); + } + CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); + // when + List<List<X509Certificate>> cmpClientResult = + cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter); + // then + assertNotNull(cmpClientResult); + } + + @Test + void + shouldThrowCmpClientExceptionWhenCreateCertificateRequestMessageMethodCalledWithWrongProtectedBytesInResponse() + throws Exception { + // given + Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); + Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); + setCsrMetaValuesAndDateValues( + rdns, + "CN=CommonName", + "CN=ManagementCA", + "CommonName.com", + "CommonName@cn.com", + "password", + "http://127.0.0.1/ejbca/publicweb/cmp/cmp", + "senderKID", + beforeDate, + afterDate); + when(httpClient.execute(any())).thenReturn(httpResponse); + when(httpResponse.getEntity()).thenReturn(httpEntity); + + try (final InputStream is = + this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile"); + BufferedInputStream bis = new BufferedInputStream(is)) { + + byte[] ba = IOUtils.toByteArray(bis); + doAnswer( + invocation -> { + OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0]; + os.write(ba); + return null; + }) + .when(httpEntity) + .writeTo(any(OutputStream.class)); + } + CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); + // then + Assertions.assertThrows( + CmpClientException.class, + () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); + } + + @Test + void shouldThrowCmpClientExceptionWithPkiErrorExceptionWhenCmpClientCalledWithBadPassword() + throws Exception { + // given + Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); + Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); + setCsrMetaValuesAndDateValues( + rdns, + "CN=CommonName", + "CN=ManagementCA", + "CommonName.com", + "CommonName@cn.com", + "password", + "http://127.0.0.1/ejbca/publicweb/cmp/cmp", + "senderKID", + beforeDate, + afterDate); + when(httpClient.execute(any())).thenReturn(httpResponse); + when(httpResponse.getEntity()).thenReturn(httpEntity); + + try (final InputStream is = + this.getClass().getResourceAsStream("/ReturnedFailurePKIMessageBadPassword"); + BufferedInputStream bis = new BufferedInputStream(is)) { + + byte[] ba = IOUtils.toByteArray(bis); + doAnswer( + invocation -> { + OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0]; + os.write(ba); + return null; + }) + .when(httpEntity) + .writeTo(any(OutputStream.class)); + } + CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); + + // then + Assertions.assertThrows( + CmpClientException.class, + () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); + } + + @Test + void shouldThrowIllegalArgumentExceptionWhencreateCertificateCalledWithInvalidCsr() + throws ParseException { + // given + Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); + Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); + setCsrMetaValuesAndDateValues( + rdns, + "CN=CommonName", + "CN=ManagementCA", + "CommonName.com", + "CommonName@cn.com", + "password", + "http://127.0.0.1/ejbca/publicweb/cmp/cmp", + "senderKID", + beforeDate, + afterDate); + CmpClientImpl cmpClient = new CmpClientImpl(httpClient); + // then + Assertions.assertThrows( + IllegalArgumentException.class, + () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); + } + + @Test + void shouldThrowIoExceptionWhenCreateCertificateCalledWithNoServerAvailable() + throws IOException, ParseException { + // given + Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); + Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); + setCsrMetaValuesAndDateValues( + rdns, + "CN=Common", + "CN=CommonCA", + "Common.com", + "Common@cn.com", + "myPassword", + "http://127.0.0.1/ejbca/publicweb/cmp/cmpTest", + "sender", + beforeDate, + afterDate); + when(httpClient.execute(any())).thenThrow(IOException.class); + CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); + // then + Assertions.assertThrows( + CmpClientException.class, + () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); + } + + private void setCsrMetaValuesAndDateValues( + List<Rdn> rdns, + String cn, + String issuerCn, + String san, + String email, + String password, + String externalCaUrl, + String senderKid, + Date notBefore, + Date notAfter) { + csrMeta = new CsrMeta(rdns); + csrMeta.setCn(cn); + csrMeta.addSan(san); + csrMeta.setPassword(password); + csrMeta.setEmail(email); + csrMeta.setIssuerCn(issuerCn); + when(kpg.generateKeyPair()).thenReturn(keyPair); + csrMeta.getKeyPairOrGenerateIfNull(); + csrMeta.setCaUrl(externalCaUrl); + csrMeta.setSenderKid(senderKid); + this.notBefore = notBefore; + this.notAfter = notAfter; + } +} diff --git a/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/external/RDNTest.java b/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/external/RdnTest.java index 7a1f8be4..6e42afe8 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/external/RDNTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/external/RdnTest.java @@ -31,19 +31,20 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -class RDNTest { +class RdnTest { @Test - public void shouldCreateCorrectRDN() throws CertException { + void shouldCreateCorrectRdn() throws CertException { + // given + final String expectedValue = "ManagmentCA"; + final ASN1ObjectIdentifier expectedAoi = BCStyle.CN; + //when - RDN rdn1 = new RDN("CN=ManagmentCA"); - RDN rdn2 = new RDN("CN = ManagmentCA "); - RDN rdn3 = new RDN("CN", "ManagmentCA"); + Rdn rdn1 = new Rdn("CN=ManagmentCA"); + Rdn rdn2 = new Rdn("CN = ManagmentCA "); + Rdn rdn3 = new Rdn("CN", "ManagmentCA"); //then - String expectedValue = "ManagmentCA"; - ASN1ObjectIdentifier expectedAoi = BCStyle.CN; - assertEquals(expectedValue, rdn1.getValue()); assertEquals(expectedValue, rdn2.getValue()); assertEquals(expectedValue, rdn3.getValue()); @@ -53,7 +54,7 @@ class RDNTest { } @Test - public void shouldCorrectlySplitAndTrimString() { + void shouldCorrectlySplitAndTrimString() { //given String value1 = " T = Test"; List<String> expected1 = Arrays.asList("T", "Test"); @@ -62,8 +63,8 @@ class RDNTest { List<String> expected2 = Arrays.asList("This", "is 99 tested", "string"); //when - List<String> actual1 = RDN.parseRDN("=", value1); - List<String> actual2 = RDN.parseRDN("[0-9]{3,}", value2); + List<String> actual1 = Rdn.parseRdn("=", value1); + List<String> actual2 = Rdn.parseRdn("[0-9]{3,}", value2); //then assertEquals(expected1, actual1); @@ -71,8 +72,8 @@ class RDNTest { } @Test - public void shouldConvertAoiStringToEnum() throws CertException { - RDN rdn = new RDN("CN", "ManagmentCA"); + void shouldConvertAoiStringToEnum() throws CertException { + Rdn rdn = new Rdn("CN", "ManagmentCA"); assertEquals(BCStyle.CN, rdn.getAoi("CN")); assertEquals(BCStyle.C, rdn.getAoi("C")); @@ -92,4 +93,4 @@ class RDNTest { assertEquals(BCStyle.SERIALNUMBER, rdn.getAoi("SERIALNUMBER")); assertThrows(CertException.class, () -> rdn.getAoi("INVALIDTAG")); } -}
\ No newline at end of file +} |