From b8c4e6867d6b26652f4382e93665c220769cdc9f Mon Sep 17 00:00:00 2001 From: baniewsk Date: Wed, 29 Jul 2020 16:01:27 +0200 Subject: Removing AAF references from Cert-Service in OOM repo. Certificates regenerated External files (from legacy AAF) removed Still left: * Sonar link, * Link to documentation, * Names of K8s resources in RTD documentation, * Link to CSITs Issue-ID: OOM-2526 Signed-off-by: Pawel Baniewski Change-Id: I675f7485160b9b8e46e9ea573550e62ed28ca607 --- .../client/CerServiceRequestTestData.java | 89 --------- .../certservice/client/CertServiceClientTest.java | 49 ----- .../ArtifactsCreatorProviderTest.java | 73 -------- .../client/certification/CsrFactoryTest.java | 56 ------ .../client/certification/KeyPairFactoryTest.java | 53 ------ .../certification/PrivateKeyToPemEncoderTest.java | 66 ------- .../conversion/ConvertedArtifactsCreatorTest.java | 125 ------------- .../conversion/PemArtifactsCreatorTest.java | 58 ------ .../certification/conversion/PemConverterTest.java | 206 --------------------- .../conversion/RandomPasswordGeneratorTest.java | 33 ---- .../certification/writer/CertFileWriterTest.java | 76 -------- .../client/configuration/EnvProviderTest.java | 65 ------- .../client/configuration/EnvsForCsrTest.java | 201 -------------------- .../client/configuration/EnvsForTlsTest.java | 133 ------------- .../exception/TlsConfigurationExceptionTest.java | 48 ----- .../factory/AbstractConfigurationFactoryTest.java | 93 ---------- .../factory/ClientConfigurationFactoryTest.java | 155 ---------------- .../factory/CsrConfigurationFactoryTest.java | 186 ------------------- .../factory/SslContextFactoryTest.java | 197 -------------------- .../client/httpclient/HttpClientTest.java | 144 -------------- .../client/CerServiceRequestTestData.java | 89 +++++++++ .../certservice/client/CertServiceClientTest.java | 49 +++++ .../ArtifactsCreatorProviderTest.java | 73 ++++++++ .../client/certification/CsrFactoryTest.java | 56 ++++++ .../client/certification/KeyPairFactoryTest.java | 53 ++++++ .../certification/PrivateKeyToPemEncoderTest.java | 66 +++++++ .../conversion/ConvertedArtifactsCreatorTest.java | 125 +++++++++++++ .../conversion/PemArtifactsCreatorTest.java | 58 ++++++ .../certification/conversion/PemConverterTest.java | 206 +++++++++++++++++++++ .../conversion/RandomPasswordGeneratorTest.java | 33 ++++ .../certification/writer/CertFileWriterTest.java | 76 ++++++++ .../client/configuration/EnvProviderTest.java | 65 +++++++ .../client/configuration/EnvsForCsrTest.java | 201 ++++++++++++++++++++ .../client/configuration/EnvsForTlsTest.java | 133 +++++++++++++ .../exception/TlsConfigurationExceptionTest.java | 48 +++++ .../factory/AbstractConfigurationFactoryTest.java | 93 ++++++++++ .../factory/ClientConfigurationFactoryTest.java | 155 ++++++++++++++++ .../factory/CsrConfigurationFactoryTest.java | 186 +++++++++++++++++++ .../factory/SslContextFactoryTest.java | 197 ++++++++++++++++++++ .../client/httpclient/HttpClientTest.java | 144 ++++++++++++++ 40 files changed, 2106 insertions(+), 2106 deletions(-) delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/CerServiceRequestTestData.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProviderTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/CsrFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/KeyPairFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoderTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreatorTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemConverterTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriterTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvProviderTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForCsrTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForTlsTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/CerServiceRequestTestData.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/CertServiceClientTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProviderTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/CsrFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/KeyPairFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoderTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreatorTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemConverterTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/writer/CertFileWriterTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvProviderTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForCsrTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForTlsTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/httpclient/HttpClientTest.java (limited to 'certServiceClient/src/test/java/org/onap') diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CerServiceRequestTestData.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CerServiceRequestTestData.java deleted file mode 100644 index 8f252c31..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CerServiceRequestTestData.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; - -public final class CerServiceRequestTestData { - - private static final String RESOURCE_PATH = "src/test/resources/"; - - // Request parameters - public static final String CA_NAME = "TestCA"; - public static final String CSR = getCsrValue(); - public static final String PK = getPkValue(); - - // Correct response data - public static final String CORRECT_RESPONSE = getCorrectResponse(); - public static final String EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN = - getExpectedFirstElementOfCertificateChain(); - public static final String EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES = - getExpectedFirstElementOfTrustedCertificates(); - - // Error response data - public static final String MISSING_PK_RESPONSE = getMissingPkResponse(); - - private CerServiceRequestTestData() { - } - - private static String getMissingPkResponse() { - String fileName = "missingPkResponse"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getExpectedFirstElementOfTrustedCertificates() { - - String fileName = "expectedFirstElementOfTrustedCertificates"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getExpectedFirstElementOfCertificateChain() { - String fileName = "expectedFirstElementOfCertificateChain"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getCorrectResponse() { - String fileName = "correctResponse"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getPkValue() { - String fileName = "testPk"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getCsrValue() { - String fileName = "testCsr"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String readFromFile(String path) { - try { - return Files.readString(Paths.get(path), StandardCharsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - return "File not found"; - } - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java deleted file mode 100644 index 9e256f98..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Spy; -import org.mockito.junit.jupiter.MockitoExtension; - -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.verify; -import static org.onap.aaf.certservice.client.api.ExitStatus.CLIENT_CONFIGURATION_EXCEPTION; -import static org.onap.aaf.certservice.client.api.ExitStatus.SUCCESS; - -@ExtendWith(MockitoExtension.class) -class CertServiceClientTest { - @Spy - AppExitHandler appExitHandler = new AppExitHandler(); - - @Test - void shouldExitWithDefinedExitCode_onRunCallWhenNoEnvsPresent() { - // given - doNothing().when(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); - doNothing().when(appExitHandler).exit(SUCCESS); - CertServiceClient certServiceClient = new CertServiceClient(appExitHandler); - // when - certServiceClient.run(); - // then - verify(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); - verify(appExitHandler).exit(SUCCESS); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProviderTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProviderTest.java deleted file mode 100644 index 46bacef8..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProviderTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.certification; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.ValueSource; -import org.onap.aaf.certservice.client.certification.conversion.ArtifactsCreator; -import org.onap.aaf.certservice.client.certification.conversion.ConvertedArtifactsCreator; -import org.onap.aaf.certservice.client.certification.conversion.PemArtifactsCreator; - -import static org.assertj.core.api.Assertions.assertThat; - - -class ArtifactsCreatorProviderTest { - - private static final String P12 = "P12"; - private static final String JKS = "JKS"; - private static final String PEM = "PEM"; - private static final String TEST_PATH = "testPath"; - - @ParameterizedTest - @ValueSource(strings = {JKS, P12}) - void artifactsProviderShouldReturnConvertedCreator(String outputType) { - - // when - ArtifactsCreator artifactsCreator = - ArtifactsCreatorProvider.get(outputType, TEST_PATH); - // then - assertThat(artifactsCreator).isInstanceOf(ConvertedArtifactsCreator.class); - } - - @Test - void artifactsProviderShouldReturnPemCreator() { - - // when - ArtifactsCreator artifactsCreator = - ArtifactsCreatorProvider.get(PEM, TEST_PATH); - // then - assertThat(artifactsCreator).isInstanceOf(PemArtifactsCreator.class); - } - - @ParameterizedTest - @CsvSource({ - "JKS, jks", - "P12, p12"}) - void getExtensionShouldProvideExtensionBasedOnArtifactType(String artifactType, String expectedExtension) { - - //when - String actualExtension = ArtifactsCreatorProvider.valueOf(artifactType).getExtension(); - //then - assertThat(actualExtension).isEqualTo(expectedExtension); - } - -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/CsrFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/CsrFactoryTest.java deleted file mode 100644 index ae18e6fb..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/CsrFactoryTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.certification; - - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.certification.exception.CsrGenerationException; -import org.onap.aaf.certservice.client.certification.exception.KeyPairGenerationException; -import org.onap.aaf.certservice.client.configuration.model.CsrConfiguration; - -import java.security.KeyPair; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class CsrFactoryTest { - - CsrConfiguration config = mock(CsrConfiguration.class); - - - @Test - void createEncodedCsr_shouldSucceedWhenAllFieldsAreSetCorrectly() throws KeyPairGenerationException, CsrGenerationException { - - KeyPair keyPair = - new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, EncryptionAlgorithmConstants.KEY_SIZE).create(); - - when(config.getCommonName()).thenReturn("onap.org"); - when(config.getSans()).thenReturn("onapexample.com:onapexample.com.pl:onapexample.pl"); - when(config.getCountry()).thenReturn("US"); - when(config.getLocation()).thenReturn("San-Francisco"); - when(config.getOrganization()).thenReturn("Linux-Foundation"); - when(config.getOrganizationUnit()).thenReturn("ONAP"); - when(config.getState()).thenReturn("California"); - - assertThat(new CsrFactory(config).createCsrInPem(keyPair)).isNotEmpty(); - } -} - diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/KeyPairFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/KeyPairFactoryTest.java deleted file mode 100644 index 3d3d3c17..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/KeyPairFactoryTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.certification; - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.certification.exception.KeyPairGenerationException; - -import java.security.KeyPair; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -class KeyPairFactoryTest { - private static final String NOT_EXISTING_ENCRYPTION_ALGORITHM = "FAKE_ALGORITHM"; - - @Test - public void shouldProvideKeyPair_whenCreateKeyPairCalledWithCorrectArguments() throws KeyPairGenerationException { - // given - KeyPairFactory keyPairFactory = new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, - EncryptionAlgorithmConstants.KEY_SIZE); - // when - KeyPair keyPair = keyPairFactory.create(); - // then - assertThat(keyPair).isInstanceOf(KeyPair.class); - } - - @Test - public void shouldThrowKeyPairGenerationException_whenCreateTryCalledOnNotExistingAlgorithm() { - // given - KeyPairFactory keyPairFactory = new KeyPairFactory(NOT_EXISTING_ENCRYPTION_ALGORITHM, - EncryptionAlgorithmConstants.KEY_SIZE); - // when, then - assertThatThrownBy(keyPairFactory::create).isInstanceOf(KeyPairGenerationException.class); - } - -} \ No newline at end of file diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoderTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoderTest.java deleted file mode 100644 index 41f15bb7..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoderTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.certification; - - -import org.bouncycastle.util.io.pem.PemObject; -import org.bouncycastle.util.io.pem.PemReader; -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.certification.exception.PkEncodingException; - -import java.io.IOException; -import java.io.StringReader; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; - -import static org.assertj.core.api.Assertions.assertThat; - -class PrivateKeyToPemEncoderTest { - - private static final String ENCRYPTION_ALGORITHM = "RSA"; - private static final String RESOURCES_DIR = "src/test/resources/"; - private static final String PRIVATE_KEY_PEM_PATH = RESOURCES_DIR + "rsaPrivateKeyPem"; - - @Test - void shouldReturnProperlyEncodedPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException, PkEncodingException, IOException { - //given - String expectedPem = Files.readString(Paths.get(PRIVATE_KEY_PEM_PATH)); - PrivateKeyToPemEncoder testedPkEncoder = new PrivateKeyToPemEncoder(); - //when - PrivateKey privateKey = extractPrivateKeyFromPem(expectedPem); - String resultPkInPem = testedPkEncoder.encodePrivateKeyToPem(privateKey); - //then - assertThat(resultPkInPem).isEqualTo(expectedPem); - } - - private PrivateKey extractPrivateKeyFromPem(String pem) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { - PemReader pemReader = new PemReader(new StringReader(pem)); - PemObject pemObject = pemReader.readPemObject(); - pemReader.close(); - PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pemObject.getContent()); - KeyFactory kf = KeyFactory.getInstance(ENCRYPTION_ALGORITHM); - return kf.generatePrivate(spec); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java deleted file mode 100644 index e13f8be8..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.certification.conversion; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.certification.exception.CertFileWriterException; -import org.onap.aaf.certservice.client.certification.exception.PemConversionException; -import org.onap.aaf.certservice.client.certification.writer.CertFileWriter; - -import java.security.PrivateKey; -import java.util.List; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -class ConvertedArtifactsCreatorTest { - - private static final int PASSWORD_LENGTH = 24; - private static final String CERTIFICATE_ALIAS = "certificate"; - private static final String TRUSTED_CERTIFICATE_ALIAS = "trusted-certificate-"; - - private static final Password SAMPLE_PASSWORD = new Password("d9D_u8LooYaXH4G48DtN#vw0"); - private static final List SAMPLE_KEYSTORE_CERTIFICATE_CHAIN = List.of("a", "b"); - private static final List SAMPLE_TRUSTED_CERTIFICATE_CHAIN = List.of("c", "d"); - private static final byte[] SAMPLE_KEYSTORE_BYTES = "this is a keystore test".getBytes(); - private static final byte[] SAMPLE_TRUSTSTORE_BYTES = "this is a truststore test".getBytes(); - private static final String P12_EXTENSION = "p12"; - - private CertFileWriter certFileWriter; - private RandomPasswordGenerator passwordGenerator; - private PemConverter converter; - private PrivateKey privateKey; - private ConvertedArtifactsCreator artifactsCreator; - - - @BeforeEach - void setUp() { - certFileWriter = mock(CertFileWriter.class); - passwordGenerator = mock(RandomPasswordGenerator.class); - converter = mock(PemConverter.class); - privateKey = mock(PrivateKey.class); - artifactsCreator = new ConvertedArtifactsCreator(certFileWriter, passwordGenerator, converter, P12_EXTENSION); - } - - @Test - void convertedArtifactCreatorShouldTryCreateFileWithGivenExtension() - throws CertFileWriterException, PemConversionException { - //given - mockPasswordGeneratorAndPemConverter(); - final String keystore = "keystore"; - final String testExtension = "testExt"; - final String keystoreFileName = String.format("%s.%s", keystore, testExtension); - artifactsCreator = new ConvertedArtifactsCreator(certFileWriter, passwordGenerator, converter, testExtension); - - //when - artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); - - //then - verify(certFileWriter, times(1)) - .saveData(SAMPLE_KEYSTORE_BYTES, keystoreFileName); - } - - @Test - void convertedArtifactsCreatorShouldCallConverterAndFilesCreatorMethods() - throws PemConversionException, CertFileWriterException { - // given - mockPasswordGeneratorAndPemConverter(); - final String keystoreP12 = "keystore.p12"; - final String keystorePass = "keystore.pass"; - - //when - artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); - - // then - verify(converter, times(1)) - .convertKeystore(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, CERTIFICATE_ALIAS, privateKey); - verify(certFileWriter, times(1)) - .saveData(SAMPLE_KEYSTORE_BYTES, keystoreP12); - verify(certFileWriter, times(1)) - .saveData(SAMPLE_PASSWORD.getCurrentPassword().getBytes(), keystorePass); - verify(converter, times(1)) - .convertTruststore(SAMPLE_TRUSTED_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, TRUSTED_CERTIFICATE_ALIAS); - } - - @Test - void convertedArtifactsCreatorShouldCallPasswordGeneratorTwice() - throws PemConversionException, CertFileWriterException { - // given - mockPasswordGeneratorAndPemConverter(); - - //when - artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); - - // then - verify(passwordGenerator, times(2)).generate(PASSWORD_LENGTH); - } - - private void mockPasswordGeneratorAndPemConverter() throws PemConversionException { - when(passwordGenerator.generate(PASSWORD_LENGTH)).thenReturn(SAMPLE_PASSWORD); - when(converter.convertKeystore(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, CERTIFICATE_ALIAS, privateKey)) - .thenReturn(SAMPLE_KEYSTORE_BYTES); - when(converter.convertTruststore(SAMPLE_TRUSTED_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, TRUSTED_CERTIFICATE_ALIAS)) - .thenReturn(SAMPLE_TRUSTSTORE_BYTES); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreatorTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreatorTest.java deleted file mode 100644 index 5e79b96f..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreatorTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.certification.conversion; - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.api.ExitableException; -import org.onap.aaf.certservice.client.certification.PrivateKeyToPemEncoder; -import org.onap.aaf.certservice.client.certification.writer.CertFileWriter; - -import java.security.PrivateKey; -import java.util.List; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -class PemArtifactsCreatorTest { - private static final String KEYSTORE_PEM = "keystore.pem"; - private static final String TRUSTSTORE_PEM = "truststore.pem"; - private static final String KEY_PEM = "key.pem"; - private static final String KEY = "my private key"; - private CertFileWriter certFileWriter = mock(CertFileWriter.class); - private PrivateKey privateKey = mock(PrivateKey.class); - private PrivateKeyToPemEncoder pkEncoder = mock(PrivateKeyToPemEncoder.class); - - @Test - void pemArtifactsCreatorShouldCallRequiredMethods() throws ExitableException { - // given - final PemArtifactsCreator creator = new PemArtifactsCreator(certFileWriter, pkEncoder); - - // when - when(pkEncoder.encodePrivateKeyToPem(privateKey)).thenReturn(KEY); - creator.create(List.of("one", "two"), List.of("three", "four"), privateKey); - - // then - verify(certFileWriter, times(1)).saveData("one\ntwo".getBytes(), KEYSTORE_PEM); - verify(certFileWriter, times(1)).saveData("three\nfour".getBytes(), TRUSTSTORE_PEM); - verify(certFileWriter, times(1)).saveData(KEY.getBytes(), KEY_PEM); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemConverterTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemConverterTest.java deleted file mode 100644 index e3a58c3f..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemConverterTest.java +++ /dev/null @@ -1,206 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.certification.conversion; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants; -import org.onap.aaf.certservice.client.certification.exception.PemConversionException; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -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; - -class PemConverterTest { - - private static final String RESOURCES_PATH = "src/test/resources"; - private static final String CERT1_PATH = RESOURCES_PATH + "/cert1.pem"; - private static final String CERT2_PATH = RESOURCES_PATH + "/cert2.pem"; - private static final String KEY_PATH = RESOURCES_PATH + "/privateKey"; - private static final String EXPECTED_KEYSTORE_PATH = RESOURCES_PATH + "/expectedKeystore.jks"; - private static final String EXPECTED_TRUSTSTORE_PATH = RESOURCES_PATH + "/expectedTruststore.jks"; - private static final String PKCS12 = "PKCS12"; - private static final String PKCS8 = "PKCS#8"; - private static final String JKS = "JKS"; - private static final String KEY_ERROR_MSG = "java.security.KeyStoreException: Key protection algorithm not found: java.lang.NullPointerException"; - private static final String CERTIFICATES_ERROR_MSG = "The certificate couldn't be parsed correctly. certificate1"; - private static final String PASSWORD_ERROR_MSG = "Password should be min. 16 chars long and should contain only alphanumeric characters and special characters like Underscore (_), Dollar ($) and Pound (#)"; - private static byte[] key; - private PrivateKey privateKey = mock(PrivateKey.class); - - @BeforeAll - static void setUpForAll() throws IOException { - key = Files.readAllBytes(Path.of(KEY_PATH)); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertKeystoreShouldReturnKeystoreWithGivenPrivateKeyAndCertificateChain(String conversionTarget) - throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, PemConversionException { - // given - final String alias = "keystore-entry"; - final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); - final List certificateChain = getCertificates(); - final PemConverter converter = new PemConverter(conversionTarget); - final KeyStore expectedKeyStore = KeyStore.getInstance(conversionTarget); - expectedKeyStore.load(new ByteArrayInputStream(Files.readAllBytes(Path.of(EXPECTED_KEYSTORE_PATH))), - password.toCharArray()); - final Certificate[] expectedChain = expectedKeyStore.getCertificateChain(alias); - privateKeyMockSetup(); - - // when - final byte[] result = converter.convertKeystore(certificateChain, password, alias, privateKey); - - // then - final KeyStore actualKeyStore = KeyStore.getInstance(conversionTarget); - actualKeyStore.load(new ByteArrayInputStream(result), password.toCharArray()); - final Certificate[] actualChain = actualKeyStore.getCertificateChain(alias); - - assertArrayEquals(key, actualKeyStore.getKey(alias, password.toCharArray()).getEncoded()); - assertEquals(2, expectedChain.length); - assertArrayEquals(expectedChain, actualChain); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongPassword(String conversionTarget) throws IOException { - // given - final String alias = "keystore-entry"; - final Password password = new Password("apple"); - final List certificateChain = getCertificates(); - final PemConverter converter = new PemConverter(conversionTarget); - privateKeyMockSetup(); - - // when - Exception exception = assertThrows(PemConversionException.class, () -> - converter.convertKeystore(certificateChain, password, alias, privateKey) - ); - - // then - assertEquals(PASSWORD_ERROR_MSG, exception.getMessage()); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertTruststoreShouldReturnTruststoreWithGivenCertificatesArray(String conversionTarget) - throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, PemConversionException { - - // given - final PemConverter converter = new PemConverter(conversionTarget); - final String alias = "trusted-certificate-"; - final String alias1 = alias + 1; - final String alias2 = alias + 2; - final Password password = new Password("9z6oFx1epRSCuBWU4Er8i_0y"); - final List trustedCertificates = getCertificates(); - final KeyStore expectedTrustStore = KeyStore.getInstance(conversionTarget); - expectedTrustStore.load(new ByteArrayInputStream(Files.readAllBytes(Path.of(EXPECTED_TRUSTSTORE_PATH))), - password.toCharArray()); - - // when - final byte[] result = converter.convertTruststore(trustedCertificates, password, alias); - - // then - final KeyStore actualKeyStore = KeyStore.getInstance(conversionTarget); - actualKeyStore.load(new ByteArrayInputStream(result), password.toCharArray()); - - assertTrue(actualKeyStore.containsAlias(alias1)); - assertTrue(actualKeyStore.containsAlias(alias2)); - assertEquals(expectedTrustStore.getCertificate(alias1), actualKeyStore.getCertificate(alias1)); - assertEquals(expectedTrustStore.getCertificate(alias2), actualKeyStore.getCertificate(alias2)); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertTruststoreShouldThrowPemConverterExceptionBecauseOfWrongPassword(String conversionTarget) throws IOException { - // given - final String alias = "trusted-certificate-"; - final Password password = new Password("nokia"); - final List trustedCertificates = getCertificates(); - final PemConverter converter = new PemConverter(conversionTarget); - - // when then - assertThatThrownBy(() -> - converter.convertTruststore(trustedCertificates, password, alias)) - .isInstanceOf(PemConversionException.class).hasMessage(PASSWORD_ERROR_MSG); - } - - @Test - void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongPrivateKey() throws IOException { - // given - final String alias = "keystore-entry"; - final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); - final List certificateChain = getCertificates(); - final PemConverter converter = new PemConverter(PKCS12); - - // when then - assertThatThrownBy(() -> converter.convertKeystore(certificateChain, password, alias, privateKey)) - .isInstanceOf(PemConversionException.class).hasMessage(KEY_ERROR_MSG); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongCertificates(String conversionTarget) { - // given - final String alias = "keystore-entry"; - final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); - final List certificateChain = List.of("certificate1", "certificate2"); - final PemConverter converter = new PemConverter(conversionTarget); - privateKeyMockSetup(); - - // when then - assertThatThrownBy(() -> converter.convertKeystore(certificateChain, password, alias, privateKey)) - .isInstanceOf(PemConversionException.class).hasMessage(CERTIFICATES_ERROR_MSG); - } - - private void privateKeyMockSetup() { - when(privateKey.getEncoded()).thenReturn(key); - when(privateKey.getAlgorithm()).thenReturn(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM); - when(privateKey.getFormat()).thenReturn(PKCS8); - } - - private List getCertificates() throws IOException { - return List.of( - Files.readString( - Path.of(CERT1_PATH), StandardCharsets.UTF_8), - Files.readString( - Path.of(CERT2_PATH), StandardCharsets.UTF_8) - ); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java deleted file mode 100644 index 483e35e0..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.certification.conversion; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -class RandomPasswordGeneratorTest { - - @Test - void shouldGenerateRandomPasswordOfGivenLengthMatchingThePattern() { - Password password = new RandomPasswordGenerator().generate(24); - assertTrue(password.isCorrectPasswordPattern()); - } -} \ No newline at end of file diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriterTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriterTest.java deleted file mode 100644 index c45876ec..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriterTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.certification.writer; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.onap.aaf.certservice.client.certification.exception.CertFileWriterException; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -class CertFileWriterTest { - - private static final String RESOURCES_PATH = "src/test/resources/"; - private static final String OUTPUT_PATH = RESOURCES_PATH + "generatedFiles/"; - private static final String NOT_EXISTING_OUTPUT_PATH = OUTPUT_PATH + "directoryDoesNotExist/"; - private static final String TRUSTSTORE_P12 = "truststore.p12"; - private File outputDirectory = new File(OUTPUT_PATH); - - @AfterEach - void cleanUpFiles() { - deleteDirectoryRecursive(outputDirectory); - } - - @ParameterizedTest - @ValueSource(strings = {OUTPUT_PATH, NOT_EXISTING_OUTPUT_PATH}) - void certFileWriterShouldCreateFilesWithDataInGivenLocation(String outputPath) - throws IOException, CertFileWriterException { - // given - File truststore = new File(outputPath + TRUSTSTORE_P12); - CertFileWriter certFileWriter = CertFileWriter.createWithDir(outputPath); - final byte[] data = new byte[]{-128, 1, 2, 3, 127}; - - // when - certFileWriter.saveData(data, TRUSTSTORE_P12); - - // then - assertThat(truststore.exists()).isTrue(); - assertThat(Files.readAllBytes(Path.of(outputPath + TRUSTSTORE_P12))).isEqualTo(data); - } - - private void deleteDirectoryRecursive(File dirForDeletion) { - List.of(dirForDeletion.listFiles()).forEach(file -> { - if (file.isDirectory()) { - deleteDirectoryRecursive(file); - } - file.delete(); - }); - dirForDeletion.delete(); - } - -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvProviderTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvProviderTest.java deleted file mode 100644 index 74c8c2a1..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvProviderTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.configuration; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -class EnvProviderTest { - private static final String TEST_ENV = "testEnv"; - private static final String TEST_ENV_VALUE = "prod"; - - private EnvProvider envProvider; - - @BeforeEach - void setUp() { - envProvider = Mockito.spy(EnvProvider.class); - } - - @Test - void shouldReturnSystemEnvVariableWhenItWasDefined() { - // given - when(envProvider.getSystemEnv(TEST_ENV)).thenReturn(TEST_ENV_VALUE); - - // when - final Optional testEnv = envProvider.readEnvVariable(TEST_ENV); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV_VALUE); - } - - @Test - void shouldReportThatSystemEnvVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envProvider.readEnvVariable(TEST_ENV); - - // then - assertThat(testEnv).isNotPresent(); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForCsrTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForCsrTest.java deleted file mode 100644 index d6af20c6..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForCsrTest.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.configuration; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -class EnvsForCsrTest { - private static final String TEST_ENV = "testEnv"; - private EnvsForCsr envsForCsr; - - @BeforeEach - public void setUp() { - envsForCsr = Mockito.spy(EnvsForCsr.class); - } - - @Test - void shouldReturnSystemEnvCommonNameVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.COMMON_NAME)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getCommonName(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvCommonNameVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getCommonName(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvOrganizationVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.ORGANIZATION)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getOrganization(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvOrganizationVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getOrganization(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvOuVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.ORGANIZATION_UNIT)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getOrganizationUnit(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - public void shouldReportThatSystemEnvOuVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getOrganizationUnit(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvLocationVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.LOCATION)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getLocation(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvLocationVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getLocation(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvStateVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.STATE)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getState(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvStateVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getState(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvCountryVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.COUNTRY)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getCountry(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvCountryVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getCountry(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvSansVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.SANS)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getSubjectAlternativesName(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - public void shouldReportThatSystemEnvSansVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getSubjectAlternativesName(); - - // then - assertThat(testEnv).isNotPresent(); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForTlsTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForTlsTest.java deleted file mode 100644 index 7f599aa5..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForTlsTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.configuration; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -class EnvsForTlsTest { - - private static final String TEST_ENV = "testEnv"; - private EnvsForTls envsForTls; - - @BeforeEach - public void setUp() { - envsForTls = Mockito.spy(EnvsForTls.class); - } - - @Test - void shouldReturnSystemEnvKeyStorePathVariableWhenItWasDefined() { - // given - when(envsForTls.readEnv(TlsConfigurationEnvs.KEYSTORE_PATH)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForTls.getKeystorePath(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvKeyStorePathVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForTls.getKeystorePath(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvKeyStorePasswordVariableWhenItWasDefined() { - // given - when(envsForTls.readEnv(TlsConfigurationEnvs.KEYSTORE_PASSWORD)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForTls.getKeystorePassword(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvKeyStorePasswordVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForTls.getKeystorePassword(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvTrustStorePathVariableWhenItWasDefined() { - // given - when(envsForTls.readEnv(TlsConfigurationEnvs.TRUSTSTORE_PATH)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForTls.getTruststorePath(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvTrustStorePathVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForTls.getTruststorePath(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvTrustStorePasswordVariableWhenItWasDefined() { - // given - when(envsForTls.readEnv(TlsConfigurationEnvs.TRUSTSTORE_PASSWORD)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForTls.getTruststorePassword(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvTrustStorePasswordVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForTls.getTruststorePassword(); - - // then - assertThat(testEnv).isNotPresent(); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java deleted file mode 100644 index e9e5c3bf..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.configuration.exception; - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.api.ExitStatus; - -import static org.assertj.core.api.Assertions.assertThat; - - -class TlsConfigurationExceptionTest { - - @Test - void containsProperExitStatus() { - // Given - ExitStatus exitStatus = null; - - // When - try { - throw new TlsConfigurationException("Test message"); - } catch (TlsConfigurationException e) { - exitStatus = e.applicationExitStatus(); - } - - // Then - assertThat(exitStatus) - .isNotNull() - .isEqualTo(ExitStatus.TLS_CONFIGURATION_EXCEPTION); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java deleted file mode 100644 index e4d71b31..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.configuration.factory; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.mockito.Mockito; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -class AbstractConfigurationFactoryTest { - - private final AbstractConfigurationFactory cut = mock(AbstractConfigurationFactory.class, Mockito.CALLS_REAL_METHODS); - - @ParameterizedTest - @ValueSource(strings = {"/var/log", "/", "/var/log/", "/second_var", "/second-var"}) - void shouldAcceptValidPath(String path) { - assertThat(cut.isPathValid(path)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"/var/log?", "", "var_", "var", "//", "/var//log"}) - void shouldRejectInvalidPath(String path) { - assertThat(cut.isPathValid(path)).isFalse(); - } - - @ParameterizedTest - @ValueSource(strings = {"PL", "DE", "PN", "US", "IO", "CA", "KH", "CO", "DK", "EC", "CZ", "CN", "BR", "BD", "BE"}) - void shouldAcceptValidCountryCode(String countryCode) { - assertThat(cut.isCountryValid(countryCode)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"", "QQ", "AFG", "D", "&*", "!", "ONAP", "p", "pl", "us", "afg"}) - void shouldRejectInvalidCountryCode(String countryCode) { - assertThat(cut.isCountryValid(countryCode)).isFalse(); - } - - @ParameterizedTest - @ValueSource(strings = {"caname", "caname1", "123caName", "ca1name"}) - void shouldAcceptValidAlphanumeric(String caName) { - assertThat(cut.isAlphaNumeric(caName)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"44caname$", "#caname1", "1c_aname", "ca1-name"}) - void shouldRejectInvalidAlphanumeric(String caName) { - assertThat(cut.isAlphaNumeric(caName)).isFalse(); - } - - @ParameterizedTest - @ValueSource(strings = {"example.com", "www.example.com"}) - void shouldAcceptValidCommonName(String commonName) { - assertThat(cut.isCommonNameValid(commonName)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"https://example.com", "http://example.com", "example.com:8080", "0.0.0.0", "@#$%.com"}) - void shouldRejectInvalidCommonName(String commonName) { - assertThat(cut.isCommonNameValid(commonName)).isFalse(); - } - - @ParameterizedTest - @ValueSource(strings = {"JKS", "P12", "PEM"}) - void shouldAcceptValidOutputType(String outputType) { - assertThat(cut.isOutputTypeValid(outputType)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"jks", "p12", "pem", "", "pass", "!@$#pp"}) - void shouldRejectInvalidOutputType(String outputType) { - assertThat(cut.isOutputTypeValid(outputType)).isFalse(); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java deleted file mode 100644 index 20a6c7ef..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.configuration.factory; - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.configuration.ClientConfigurationEnvs; -import org.onap.aaf.certservice.client.configuration.EnvsForClient; -import org.onap.aaf.certservice.client.configuration.exception.ClientConfigurationException; -import org.onap.aaf.certservice.client.configuration.model.ClientConfiguration; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class ClientConfigurationFactoryTest { - - private static final String CA_NAME_VALID = "caaaftest2"; - private static final String TIME_OUT_VALID = "30000"; - private static final String OUTPUT_PATH_VALID = "/opt/app/osaaf"; - private static final String URL_TO_CERT_SERVICE_VALID = "https://cert-service:8443/v1/certificate/"; - private static final String URL_TO_CERT_SERVICE_DEFAULT = "https://aaf-cert-service:8443/v1/certificate/"; - private static final String CA_NAME_INVALID = "caaaftest2#$"; - private static final String OUTPUT_PATH_INVALID = "/opt//app/osaaf"; - private static final String OUTPUT_TYPE_VALID = "JKS"; - private static final String OUTPUT_TYPE_INVALID = "JKSS"; - private static final String OUTPUT_TYPE_DEFAULT = "P12"; - - private EnvsForClient envsForClient = mock(EnvsForClient.class); - - - @Test - void create_shouldReturnSuccessWhenAllVariablesAreSetAndValid() throws ClientConfigurationException { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); - when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); - when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_VALID)); - - // when - ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); - System.out.println(configuration.toString()); - - // then - assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); - assertThat(configuration.getRequestTimeout()).isEqualTo(Integer.valueOf(TIME_OUT_VALID)); - assertThat(configuration.getCertsOutputPath()).isEqualTo(OUTPUT_PATH_VALID); - assertThat(configuration.getUrlToCertService()).isEqualTo(URL_TO_CERT_SERVICE_VALID); - assertThat(configuration.getOutputType()).isEqualTo(OUTPUT_TYPE_VALID); - } - - @Test - void create_shouldReturnSuccessWhenDefaultVariablesAreNotSet() throws ClientConfigurationException { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - - // when - ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); - - // then - assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); - assertThat(configuration.getRequestTimeout()).isEqualTo(Integer.valueOf(TIME_OUT_VALID)); - assertThat(configuration.getCertsOutputPath()).isEqualTo(OUTPUT_PATH_VALID); - assertThat(configuration.getUrlToCertService()).isEqualTo(URL_TO_CERT_SERVICE_DEFAULT); - assertThat(configuration.getOutputType()).isEqualTo(OUTPUT_TYPE_DEFAULT); - } - - @Test - void create_shouldReturnClientExceptionWhenRequiredVariableIsNotSet() { - // given - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - - // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); - - // then - assertThatExceptionOfType(ClientConfigurationException.class) - .isThrownBy(configurationFactory::create) - .withMessageContaining(ClientConfigurationEnvs.CA_NAME + " is invalid."); - } - - @Test - void create_shouldReturnClientExceptionWhenCaNameContainsSpecialCharacters() { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_INVALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); - when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); - - // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); - - // when/then - assertThatExceptionOfType(ClientConfigurationException.class) - .isThrownBy(configurationFactory::create) - .withMessageContaining(ClientConfigurationEnvs.CA_NAME + " is invalid."); - } - - @Test - void create_shouldReturnClientExceptionWhenOutputPathContainsSpecialCharacters() { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_INVALID)); - when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); - when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); - - // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); - - //then - assertThatExceptionOfType(ClientConfigurationException.class) - .isThrownBy(configurationFactory::create) - .withMessageContaining(ClientConfigurationEnvs.OUTPUT_PATH + " is invalid."); - } - - @Test - void create_shouldReturnClientExceptionWhenOutputTypeIsInvalid() { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); - when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); - when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_INVALID)); - - // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); - - //then - assertThatExceptionOfType(ClientConfigurationException.class) - .isThrownBy(configurationFactory::create) - .withMessageContaining(ClientConfigurationEnvs.OUTPUT_TYPE + " is invalid."); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java deleted file mode 100644 index b9b9b078..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.configuration.factory; - -import org.assertj.core.api.Condition; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.configuration.CsrConfigurationEnvs; -import org.onap.aaf.certservice.client.configuration.EnvsForCsr; -import org.onap.aaf.certservice.client.configuration.exception.CsrConfigurationException; -import org.onap.aaf.certservice.client.configuration.model.CsrConfiguration; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.onap.aaf.certservice.client.api.ExitStatus.CSR_CONFIGURATION_EXCEPTION; - -public class CsrConfigurationFactoryTest { - - private static final String COMMON_NAME_VALID = "onap.org"; - private static final String SANS_VALID = "test-name"; - private static final String COUNTRY_VALID = "US"; - private static final String LOCATION_VALID = "San-Francisco"; - private static final String ORGANIZATION_VALID = "Linux-Foundation"; - private static final String ORGANIZATION_UNIT_VALID = "ONAP"; - private static final String STATE_VALID = "California"; - private static final String COMMON_NAME_INVALID = "onap.org*&"; - private static final String COUNTRY_INVALID = "PLA"; - private static final String ORGANIZATION_INVALID = "Linux?Foundation"; - - private EnvsForCsr envsForCsr = mock(EnvsForCsr.class); - private CsrConfigurationFactory testedFactory; - private Condition expectedExitCodeCondition = new Condition<>("Correct exit code") { - @Override - public boolean matches(CsrConfigurationException exception) { - return exception.applicationExitStatus() == CSR_CONFIGURATION_EXCEPTION; - } - }; - - @BeforeEach - void setUp() { - testedFactory = new CsrConfigurationFactory(envsForCsr); - } - - @Test - void shouldReturnCorrectConfiguration_WhenAllVariablesAreSetAndValid() throws CsrConfigurationException { - // given - mockEnvsWithAllValidParameters(); - - // when - CsrConfiguration configuration = testedFactory.create(); - - // then - assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); - assertThat(configuration.getSans()).isEqualTo(SANS_VALID); - assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); - assertThat(configuration.getLocation()).isEqualTo(LOCATION_VALID); - assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); - assertThat(configuration.getOrganizationUnit()).isEqualTo(ORGANIZATION_UNIT_VALID); - assertThat(configuration.getState()).isEqualTo(STATE_VALID); - } - - @Test - void shouldReturnCorrectConfiguration_WhenNotRequiredVariablesAreNotSet() throws CsrConfigurationException { - // given - mockEnvsWithValidRequiredParameters(); - - // when - CsrConfiguration configuration = testedFactory.create(); - - // then - assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); - assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); - assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); - assertThat(configuration.getState()).isEqualTo(STATE_VALID); - } - - - @Test - void shouldThrowCsrConfigurationException_WhenCommonNameInvalid() { - // given - mockEnvsWithInvalidCommonName(); - - // when/then - assertThatExceptionOfType(CsrConfigurationException.class) - .isThrownBy(testedFactory::create) - .withMessageContaining(CsrConfigurationEnvs.COMMON_NAME + " is invalid.") - .has(expectedExitCodeCondition); - } - - @Test - void shouldThrowCsrConfigurationException_WhenOrganizationInvalid() { - // given - mockEnvsWithInvalidOrganization(); - - // when/then - assertThatExceptionOfType(CsrConfigurationException.class) - .isThrownBy(testedFactory::create) - .withMessageContaining(CsrConfigurationEnvs.ORGANIZATION + " is invalid.") - .has(expectedExitCodeCondition); - - } - - @Test - void shouldThrowCsrConfigurationException_WhenCountryInvalid() { - // given - mockEnvsWithInvalidCountry(); - - // when/then - assertThatExceptionOfType(CsrConfigurationException.class) - .isThrownBy(testedFactory::create) - .withMessageContaining(CsrConfigurationEnvs.COUNTRY + " is invalid.") - .has(expectedExitCodeCondition); - - } - - @Test - void shouldThrowCsrConfigurationExceptionWhenStateInvalid() { - // given - mockEnvsWithInvalidState(); - // when/then - assertThatExceptionOfType(CsrConfigurationException.class) - .isThrownBy(testedFactory::create) - .withMessageContaining(CsrConfigurationEnvs.STATE + " is invalid.") - .has(expectedExitCodeCondition); - } - - private void mockEnvsWithAllValidParameters() { - mockEnvsWithValidRequiredParameters(); - mockEnvsWithValidOptionalParameters(); - } - - private void mockEnvsWithValidOptionalParameters() { - when(envsForCsr.getOrganizationUnit()).thenReturn(Optional.of(ORGANIZATION_UNIT_VALID)); - when(envsForCsr.getLocation()).thenReturn(Optional.of(LOCATION_VALID)); - when(envsForCsr.getSubjectAlternativesName()).thenReturn(Optional.of(SANS_VALID)); - } - - private void mockEnvsWithValidRequiredParameters() { - when(envsForCsr.getCommonName()).thenReturn(Optional.of(COMMON_NAME_VALID)); - when(envsForCsr.getCountry()).thenReturn(Optional.of(COUNTRY_VALID)); - when(envsForCsr.getOrganization()).thenReturn(Optional.of(ORGANIZATION_VALID)); - when(envsForCsr.getState()).thenReturn(Optional.of(STATE_VALID)); - } - - private void mockEnvsWithInvalidCommonName() { - mockEnvsWithAllValidParameters(); - when(envsForCsr.getCommonName()).thenReturn(Optional.of(COMMON_NAME_INVALID)); - } - - private void mockEnvsWithInvalidCountry() { - mockEnvsWithAllValidParameters(); - when(envsForCsr.getCountry()).thenReturn(Optional.of(COUNTRY_INVALID)); - } - - private void mockEnvsWithInvalidOrganization() { - mockEnvsWithAllValidParameters(); - when(envsForCsr.getOrganization()).thenReturn(Optional.of(ORGANIZATION_INVALID)); - } - - private void mockEnvsWithInvalidState() { - mockEnvsWithAllValidParameters(); - when(envsForCsr.getState()).thenReturn(Optional.empty()); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactoryTest.java deleted file mode 100644 index 8e6e8369..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactoryTest.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.configuration.factory; - -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.client.configuration.EnvsForTls; -import org.onap.aaf.certservice.client.configuration.exception.TlsConfigurationException; - -import javax.net.ssl.SSLContext; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.when; - - -@ExtendWith(MockitoExtension.class) -public class SslContextFactoryTest { - - public static final String INVALID_KEYSTORE_PATH = "nonexistent/keystore"; - public static final String VALID_KEYSTORE_NAME = "keystore.jks"; - public static final String VALID_KEYSTORE_PASSWORD = "secret"; - public static final String INVALID_KEYSTORE_PASSWORD = "wrong_secret"; - public static final String INVALID_TRUSTSTORE_PATH = "nonexistent/truststore"; - public static final String VALID_TRUSTSTORE_PASSWORD = "secret"; - public static final String INVALID_TRUSTSTORE_PASSWORD = "wrong_secret"; - public static final String VALID_TRUSTSTORE_NAME = "truststore.jks"; - @Mock - private EnvsForTls envsForTls; - - @Test - public void shouldThrowExceptionWhenKeystorePathEnvIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.empty()); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - Exception exception = assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - assertThat(exception.getMessage()).contains("KEYSTORE_PATH"); - } - - @Test - public void shouldThrowExceptionWhenKeystorePasswordEnvIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.empty()); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - Exception exception = assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - assertThat(exception.getMessage()).contains("KEYSTORE_PASSWORD"); - } - - @Test - public void shouldThrowExceptionWhenTruststorePathEnvIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); - when(envsForTls.getTruststorePath()).thenReturn(Optional.empty()); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - Exception exception = assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - assertThat(exception.getMessage()).contains("TRUSTSTORE_PATH"); - } - - @Test - public void shouldThrowExceptionWhenTruststorePasswordEnvIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore")); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.empty()); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - Exception exception = assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - assertThat(exception.getMessage()).contains("TRUSTSTORE_PASSWORD"); - } - - @Test - public void shouldThrowExceptionWhenKeystoreIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(INVALID_KEYSTORE_PATH)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("secret")); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore.jks")); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of("secret")); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - } - - @Test - public void shouldThrowExceptionWhenKeystorePasswordIsWrong() { - // Given - String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(INVALID_KEYSTORE_PASSWORD)); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of(VALID_TRUSTSTORE_NAME)); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - } - - @Test - public void shouldThrowExceptionWhenTruststoreIsMissing() { - // Given - String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PATH)); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - } - - @Test - public void shouldThrowExceptionWhenTruststorePasswordIsWrong() { - // Given - String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); - String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PASSWORD)); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - } - - @Test - public void shouldReturnSslContext() throws TlsConfigurationException { - // Given - String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); - String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When - SSLContext sslContext = sslContextFactory.create(); - - // Then - assertNotNull(sslContext); - } - - private String getResourcePath(String resource) { - return getClass().getClassLoader().getResource(resource).getFile(); - } -} - diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java deleted file mode 100644 index a109749b..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * 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.client.httpclient; - -import org.apache.http.HttpEntity; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.httpclient.exception.CertServiceApiResponseException; -import org.onap.aaf.certservice.client.httpclient.exception.HttpClientException; -import org.onap.aaf.certservice.client.httpclient.model.CertServiceResponse; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.List; - -import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; -import static java.net.HttpURLConnection.HTTP_OK; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.CA_NAME; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.CORRECT_RESPONSE; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.CSR; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.MISSING_PK_RESPONSE; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.PK; - -class HttpClientTest { - - private HttpClient httpClient; - private CloseableHttpClient closeableHttpClient; - private HttpEntity httpEntity; - private StatusLine statusLine; - private CloseableHttpResponse httpResponse; - - @BeforeEach - void setUp() { - - closeableHttpClient = mock(CloseableHttpClient.class); - httpEntity = mock(HttpEntity.class); - statusLine = mock(StatusLine.class); - httpResponse = mock(CloseableHttpResponse.class); - - CloseableHttpsClientProvider httpClientProvider = mock(CloseableHttpsClientProvider.class); - - when(httpClientProvider.getClient()).thenReturn(closeableHttpClient); - String testCertServiceAddress = ""; - httpClient = new HttpClient(httpClientProvider, testCertServiceAddress); - } - - @Test - void shouldReturnCorrectListsOfCertificatedChainsAndTrustedCertificates_WhenRequestDataIsCorrect() - throws Exception { - - // given - mockServerResponse(HTTP_OK, CORRECT_RESPONSE); - - // when - CertServiceResponse certServiceResponse = - httpClient.retrieveCertServiceData(CA_NAME, CSR, PK); - List certificateChain = certServiceResponse.getCertificateChain(); - List trustedCertificate = certServiceResponse.getTrustedCertificates(); - - // then - assertThat(certServiceResponse).isNotNull(); - - final int expectedTwoElements = 2; - - assertThat(certificateChain).hasSize(expectedTwoElements); - assertThat(trustedCertificate).hasSize(expectedTwoElements); - - assertThat(certificateChain.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN); - assertThat(trustedCertificate.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES); - } - - @Test - void shouldThrowCertServiceApiResponseException_WhenPkHeaderIsMissing() throws Exception { - - //given - mockServerResponse(HTTP_BAD_REQUEST, MISSING_PK_RESPONSE); - - //when //then - assertThatExceptionOfType(CertServiceApiResponseException.class) - .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); - } - - @Test - void shouldThrowHttpClientException_WhenCannotExecuteRequestToApi() throws Exception { - - //given - when(closeableHttpClient.execute(any(HttpGet.class))).thenThrow(IOException.class); - - //when //then - assertThatExceptionOfType(HttpClientException.class) - .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); - } - - @Test - void shouldThrowHttpClientException_WhenCannotParseResponseToString() throws Exception { - - //given - mockServerResponse(HTTP_OK, CORRECT_RESPONSE); - when(httpEntity.getContent()).thenThrow(IOException.class); - - //when //then - assertThatExceptionOfType(HttpClientException.class) - .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); - } - - private void mockServerResponse(int serverCodeResponse, String stringResponse) - throws IOException { - when(statusLine.getStatusCode()).thenReturn(serverCodeResponse); - when(httpResponse.getStatusLine()).thenReturn(statusLine); - when(httpResponse.getEntity()).thenReturn(httpEntity); - when(closeableHttpClient.execute(any(HttpGet.class))).thenReturn(httpResponse); - - when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream(stringResponse.getBytes())); - } -} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/CerServiceRequestTestData.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/CerServiceRequestTestData.java new file mode 100644 index 00000000..0e5ec191 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/CerServiceRequestTestData.java @@ -0,0 +1,89 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; + +public final class CerServiceRequestTestData { + + private static final String RESOURCE_PATH = "src/test/resources/"; + + // Request parameters + public static final String CA_NAME = "TestCA"; + public static final String CSR = getCsrValue(); + public static final String PK = getPkValue(); + + // Correct response data + public static final String CORRECT_RESPONSE = getCorrectResponse(); + public static final String EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN = + getExpectedFirstElementOfCertificateChain(); + public static final String EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES = + getExpectedFirstElementOfTrustedCertificates(); + + // Error response data + public static final String MISSING_PK_RESPONSE = getMissingPkResponse(); + + private CerServiceRequestTestData() { + } + + private static String getMissingPkResponse() { + String fileName = "missingPkResponse"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getExpectedFirstElementOfTrustedCertificates() { + + String fileName = "expectedFirstElementOfTrustedCertificates"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getExpectedFirstElementOfCertificateChain() { + String fileName = "expectedFirstElementOfCertificateChain"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getCorrectResponse() { + String fileName = "correctResponse"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getPkValue() { + String fileName = "testPk"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getCsrValue() { + String fileName = "testCsr"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String readFromFile(String path) { + try { + return Files.readString(Paths.get(path), StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + return "File not found"; + } + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/CertServiceClientTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/CertServiceClientTest.java new file mode 100644 index 00000000..0a5806fd --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/CertServiceClientTest.java @@ -0,0 +1,49 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.verify; +import static org.onap.oom.certservice.client.api.ExitStatus.CLIENT_CONFIGURATION_EXCEPTION; +import static org.onap.oom.certservice.client.api.ExitStatus.SUCCESS; + +@ExtendWith(MockitoExtension.class) +class CertServiceClientTest { + @Spy + AppExitHandler appExitHandler = new AppExitHandler(); + + @Test + void shouldExitWithDefinedExitCode_onRunCallWhenNoEnvsPresent() { + // given + doNothing().when(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); + doNothing().when(appExitHandler).exit(SUCCESS); + CertServiceClient certServiceClient = new CertServiceClient(appExitHandler); + // when + certServiceClient.run(); + // then + verify(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); + verify(appExitHandler).exit(SUCCESS); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProviderTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProviderTest.java new file mode 100644 index 00000000..503ed70f --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProviderTest.java @@ -0,0 +1,73 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.certification; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.onap.oom.certservice.client.certification.conversion.ArtifactsCreator; +import org.onap.oom.certservice.client.certification.conversion.ConvertedArtifactsCreator; +import org.onap.oom.certservice.client.certification.conversion.PemArtifactsCreator; + +import static org.assertj.core.api.Assertions.assertThat; + + +class ArtifactsCreatorProviderTest { + + private static final String P12 = "P12"; + private static final String JKS = "JKS"; + private static final String PEM = "PEM"; + private static final String TEST_PATH = "testPath"; + + @ParameterizedTest + @ValueSource(strings = {JKS, P12}) + void artifactsProviderShouldReturnConvertedCreator(String outputType) { + + // when + ArtifactsCreator artifactsCreator = + ArtifactsCreatorProvider.get(outputType, TEST_PATH); + // then + assertThat(artifactsCreator).isInstanceOf(ConvertedArtifactsCreator.class); + } + + @Test + void artifactsProviderShouldReturnPemCreator() { + + // when + ArtifactsCreator artifactsCreator = + ArtifactsCreatorProvider.get(PEM, TEST_PATH); + // then + assertThat(artifactsCreator).isInstanceOf(PemArtifactsCreator.class); + } + + @ParameterizedTest + @CsvSource({ + "JKS, jks", + "P12, p12"}) + void getExtensionShouldProvideExtensionBasedOnArtifactType(String artifactType, String expectedExtension) { + + //when + String actualExtension = ArtifactsCreatorProvider.valueOf(artifactType).getExtension(); + //then + assertThat(actualExtension).isEqualTo(expectedExtension); + } + +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/CsrFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/CsrFactoryTest.java new file mode 100644 index 00000000..e2bfa976 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/CsrFactoryTest.java @@ -0,0 +1,56 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.certification; + + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.certification.exception.CsrGenerationException; +import org.onap.oom.certservice.client.certification.exception.KeyPairGenerationException; +import org.onap.oom.certservice.client.configuration.model.CsrConfiguration; + +import java.security.KeyPair; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class CsrFactoryTest { + + CsrConfiguration config = mock(CsrConfiguration.class); + + + @Test + void createEncodedCsr_shouldSucceedWhenAllFieldsAreSetCorrectly() throws KeyPairGenerationException, CsrGenerationException { + + KeyPair keyPair = + new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, EncryptionAlgorithmConstants.KEY_SIZE).create(); + + when(config.getCommonName()).thenReturn("onap.org"); + when(config.getSans()).thenReturn("onapexample.com:onapexample.com.pl:onapexample.pl"); + when(config.getCountry()).thenReturn("US"); + when(config.getLocation()).thenReturn("San-Francisco"); + when(config.getOrganization()).thenReturn("Linux-Foundation"); + when(config.getOrganizationUnit()).thenReturn("ONAP"); + when(config.getState()).thenReturn("California"); + + assertThat(new CsrFactory(config).createCsrInPem(keyPair)).isNotEmpty(); + } +} + diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/KeyPairFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/KeyPairFactoryTest.java new file mode 100644 index 00000000..765a58ca --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/KeyPairFactoryTest.java @@ -0,0 +1,53 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.certification; + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.certification.exception.KeyPairGenerationException; + +import java.security.KeyPair; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class KeyPairFactoryTest { + private static final String NOT_EXISTING_ENCRYPTION_ALGORITHM = "FAKE_ALGORITHM"; + + @Test + public void shouldProvideKeyPair_whenCreateKeyPairCalledWithCorrectArguments() throws KeyPairGenerationException { + // given + KeyPairFactory keyPairFactory = new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, + EncryptionAlgorithmConstants.KEY_SIZE); + // when + KeyPair keyPair = keyPairFactory.create(); + // then + assertThat(keyPair).isInstanceOf(KeyPair.class); + } + + @Test + public void shouldThrowKeyPairGenerationException_whenCreateTryCalledOnNotExistingAlgorithm() { + // given + KeyPairFactory keyPairFactory = new KeyPairFactory(NOT_EXISTING_ENCRYPTION_ALGORITHM, + EncryptionAlgorithmConstants.KEY_SIZE); + // when, then + assertThatThrownBy(keyPairFactory::create).isInstanceOf(KeyPairGenerationException.class); + } + +} \ No newline at end of file diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoderTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoderTest.java new file mode 100644 index 00000000..6424611e --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoderTest.java @@ -0,0 +1,66 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.certification; + + +import org.bouncycastle.util.io.pem.PemObject; +import org.bouncycastle.util.io.pem.PemReader; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.certification.exception.PkEncodingException; + +import java.io.IOException; +import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; + +import static org.assertj.core.api.Assertions.assertThat; + +class PrivateKeyToPemEncoderTest { + + private static final String ENCRYPTION_ALGORITHM = "RSA"; + private static final String RESOURCES_DIR = "src/test/resources/"; + private static final String PRIVATE_KEY_PEM_PATH = RESOURCES_DIR + "rsaPrivateKeyPem"; + + @Test + void shouldReturnProperlyEncodedPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException, PkEncodingException, IOException { + //given + String expectedPem = Files.readString(Paths.get(PRIVATE_KEY_PEM_PATH)); + PrivateKeyToPemEncoder testedPkEncoder = new PrivateKeyToPemEncoder(); + //when + PrivateKey privateKey = extractPrivateKeyFromPem(expectedPem); + String resultPkInPem = testedPkEncoder.encodePrivateKeyToPem(privateKey); + //then + assertThat(resultPkInPem).isEqualTo(expectedPem); + } + + private PrivateKey extractPrivateKeyFromPem(String pem) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { + PemReader pemReader = new PemReader(new StringReader(pem)); + PemObject pemObject = pemReader.readPemObject(); + pemReader.close(); + PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pemObject.getContent()); + KeyFactory kf = KeyFactory.getInstance(ENCRYPTION_ALGORITHM); + return kf.generatePrivate(spec); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java new file mode 100644 index 00000000..3a4d3419 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java @@ -0,0 +1,125 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.certification.conversion; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.certification.exception.CertFileWriterException; +import org.onap.oom.certservice.client.certification.exception.PemConversionException; +import org.onap.oom.certservice.client.certification.writer.CertFileWriter; + +import java.security.PrivateKey; +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ConvertedArtifactsCreatorTest { + + private static final int PASSWORD_LENGTH = 24; + private static final String CERTIFICATE_ALIAS = "certificate"; + private static final String TRUSTED_CERTIFICATE_ALIAS = "trusted-certificate-"; + + private static final Password SAMPLE_PASSWORD = new Password("d9D_u8LooYaXH4G48DtN#vw0"); + private static final List SAMPLE_KEYSTORE_CERTIFICATE_CHAIN = List.of("a", "b"); + private static final List SAMPLE_TRUSTED_CERTIFICATE_CHAIN = List.of("c", "d"); + private static final byte[] SAMPLE_KEYSTORE_BYTES = "this is a keystore test".getBytes(); + private static final byte[] SAMPLE_TRUSTSTORE_BYTES = "this is a truststore test".getBytes(); + private static final String P12_EXTENSION = "p12"; + + private CertFileWriter certFileWriter; + private RandomPasswordGenerator passwordGenerator; + private PemConverter converter; + private PrivateKey privateKey; + private ConvertedArtifactsCreator artifactsCreator; + + + @BeforeEach + void setUp() { + certFileWriter = mock(CertFileWriter.class); + passwordGenerator = mock(RandomPasswordGenerator.class); + converter = mock(PemConverter.class); + privateKey = mock(PrivateKey.class); + artifactsCreator = new ConvertedArtifactsCreator(certFileWriter, passwordGenerator, converter, P12_EXTENSION); + } + + @Test + void convertedArtifactCreatorShouldTryCreateFileWithGivenExtension() + throws CertFileWriterException, PemConversionException { + //given + mockPasswordGeneratorAndPemConverter(); + final String keystore = "keystore"; + final String testExtension = "testExt"; + final String keystoreFileName = String.format("%s.%s", keystore, testExtension); + artifactsCreator = new ConvertedArtifactsCreator(certFileWriter, passwordGenerator, converter, testExtension); + + //when + artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); + + //then + verify(certFileWriter, times(1)) + .saveData(SAMPLE_KEYSTORE_BYTES, keystoreFileName); + } + + @Test + void convertedArtifactsCreatorShouldCallConverterAndFilesCreatorMethods() + throws PemConversionException, CertFileWriterException { + // given + mockPasswordGeneratorAndPemConverter(); + final String keystoreP12 = "keystore.p12"; + final String keystorePass = "keystore.pass"; + + //when + artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); + + // then + verify(converter, times(1)) + .convertKeystore(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, CERTIFICATE_ALIAS, privateKey); + verify(certFileWriter, times(1)) + .saveData(SAMPLE_KEYSTORE_BYTES, keystoreP12); + verify(certFileWriter, times(1)) + .saveData(SAMPLE_PASSWORD.getCurrentPassword().getBytes(), keystorePass); + verify(converter, times(1)) + .convertTruststore(SAMPLE_TRUSTED_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, TRUSTED_CERTIFICATE_ALIAS); + } + + @Test + void convertedArtifactsCreatorShouldCallPasswordGeneratorTwice() + throws PemConversionException, CertFileWriterException { + // given + mockPasswordGeneratorAndPemConverter(); + + //when + artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); + + // then + verify(passwordGenerator, times(2)).generate(PASSWORD_LENGTH); + } + + private void mockPasswordGeneratorAndPemConverter() throws PemConversionException { + when(passwordGenerator.generate(PASSWORD_LENGTH)).thenReturn(SAMPLE_PASSWORD); + when(converter.convertKeystore(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, CERTIFICATE_ALIAS, privateKey)) + .thenReturn(SAMPLE_KEYSTORE_BYTES); + when(converter.convertTruststore(SAMPLE_TRUSTED_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, TRUSTED_CERTIFICATE_ALIAS)) + .thenReturn(SAMPLE_TRUSTSTORE_BYTES); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreatorTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreatorTest.java new file mode 100644 index 00000000..fd6d95c5 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreatorTest.java @@ -0,0 +1,58 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.certification.conversion; + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.api.ExitableException; +import org.onap.oom.certservice.client.certification.PrivateKeyToPemEncoder; +import org.onap.oom.certservice.client.certification.writer.CertFileWriter; + +import java.security.PrivateKey; +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class PemArtifactsCreatorTest { + private static final String KEYSTORE_PEM = "keystore.pem"; + private static final String TRUSTSTORE_PEM = "truststore.pem"; + private static final String KEY_PEM = "key.pem"; + private static final String KEY = "my private key"; + private CertFileWriter certFileWriter = mock(CertFileWriter.class); + private PrivateKey privateKey = mock(PrivateKey.class); + private PrivateKeyToPemEncoder pkEncoder = mock(PrivateKeyToPemEncoder.class); + + @Test + void pemArtifactsCreatorShouldCallRequiredMethods() throws ExitableException { + // given + final PemArtifactsCreator creator = new PemArtifactsCreator(certFileWriter, pkEncoder); + + // when + when(pkEncoder.encodePrivateKeyToPem(privateKey)).thenReturn(KEY); + creator.create(List.of("one", "two"), List.of("three", "four"), privateKey); + + // then + verify(certFileWriter, times(1)).saveData("one\ntwo".getBytes(), KEYSTORE_PEM); + verify(certFileWriter, times(1)).saveData("three\nfour".getBytes(), TRUSTSTORE_PEM); + verify(certFileWriter, times(1)).saveData(KEY.getBytes(), KEY_PEM); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemConverterTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemConverterTest.java new file mode 100644 index 00000000..c5adec08 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemConverterTest.java @@ -0,0 +1,206 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.certification.conversion; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants; +import org.onap.oom.certservice.client.certification.exception.PemConversionException; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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; + +class PemConverterTest { + + private static final String RESOURCES_PATH = "src/test/resources"; + private static final String CERT1_PATH = RESOURCES_PATH + "/cert1.pem"; + private static final String CERT2_PATH = RESOURCES_PATH + "/cert2.pem"; + private static final String KEY_PATH = RESOURCES_PATH + "/privateKey"; + private static final String EXPECTED_KEYSTORE_PATH = RESOURCES_PATH + "/expectedKeystore.jks"; + private static final String EXPECTED_TRUSTSTORE_PATH = RESOURCES_PATH + "/expectedTruststore.jks"; + private static final String PKCS12 = "PKCS12"; + private static final String PKCS8 = "PKCS#8"; + private static final String JKS = "JKS"; + private static final String KEY_ERROR_MSG = "java.security.KeyStoreException: Key protection algorithm not found: java.lang.NullPointerException"; + private static final String CERTIFICATES_ERROR_MSG = "The certificate couldn't be parsed correctly. certificate1"; + private static final String PASSWORD_ERROR_MSG = "Password should be min. 16 chars long and should contain only alphanumeric characters and special characters like Underscore (_), Dollar ($) and Pound (#)"; + private static byte[] key; + private PrivateKey privateKey = mock(PrivateKey.class); + + @BeforeAll + static void setUpForAll() throws IOException { + key = Files.readAllBytes(Path.of(KEY_PATH)); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertKeystoreShouldReturnKeystoreWithGivenPrivateKeyAndCertificateChain(String conversionTarget) + throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, PemConversionException { + // given + final String alias = "keystore-entry"; + final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); + final List certificateChain = getCertificates(); + final PemConverter converter = new PemConverter(conversionTarget); + final KeyStore expectedKeyStore = KeyStore.getInstance(conversionTarget); + expectedKeyStore.load(new ByteArrayInputStream(Files.readAllBytes(Path.of(EXPECTED_KEYSTORE_PATH))), + password.toCharArray()); + final Certificate[] expectedChain = expectedKeyStore.getCertificateChain(alias); + privateKeyMockSetup(); + + // when + final byte[] result = converter.convertKeystore(certificateChain, password, alias, privateKey); + + // then + final KeyStore actualKeyStore = KeyStore.getInstance(conversionTarget); + actualKeyStore.load(new ByteArrayInputStream(result), password.toCharArray()); + final Certificate[] actualChain = actualKeyStore.getCertificateChain(alias); + + assertArrayEquals(key, actualKeyStore.getKey(alias, password.toCharArray()).getEncoded()); + assertEquals(2, expectedChain.length); + assertArrayEquals(expectedChain, actualChain); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongPassword(String conversionTarget) throws IOException { + // given + final String alias = "keystore-entry"; + final Password password = new Password("apple"); + final List certificateChain = getCertificates(); + final PemConverter converter = new PemConverter(conversionTarget); + privateKeyMockSetup(); + + // when + Exception exception = assertThrows(PemConversionException.class, () -> + converter.convertKeystore(certificateChain, password, alias, privateKey) + ); + + // then + assertEquals(PASSWORD_ERROR_MSG, exception.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertTruststoreShouldReturnTruststoreWithGivenCertificatesArray(String conversionTarget) + throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, PemConversionException { + + // given + final PemConverter converter = new PemConverter(conversionTarget); + final String alias = "trusted-certificate-"; + final String alias1 = alias + 1; + final String alias2 = alias + 2; + final Password password = new Password("9z6oFx1epRSCuBWU4Er8i_0y"); + final List trustedCertificates = getCertificates(); + final KeyStore expectedTrustStore = KeyStore.getInstance(conversionTarget); + expectedTrustStore.load(new ByteArrayInputStream(Files.readAllBytes(Path.of(EXPECTED_TRUSTSTORE_PATH))), + password.toCharArray()); + + // when + final byte[] result = converter.convertTruststore(trustedCertificates, password, alias); + + // then + final KeyStore actualKeyStore = KeyStore.getInstance(conversionTarget); + actualKeyStore.load(new ByteArrayInputStream(result), password.toCharArray()); + + assertTrue(actualKeyStore.containsAlias(alias1)); + assertTrue(actualKeyStore.containsAlias(alias2)); + assertEquals(expectedTrustStore.getCertificate(alias1), actualKeyStore.getCertificate(alias1)); + assertEquals(expectedTrustStore.getCertificate(alias2), actualKeyStore.getCertificate(alias2)); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertTruststoreShouldThrowPemConverterExceptionBecauseOfWrongPassword(String conversionTarget) throws IOException { + // given + final String alias = "trusted-certificate-"; + final Password password = new Password("nokia"); + final List trustedCertificates = getCertificates(); + final PemConverter converter = new PemConverter(conversionTarget); + + // when then + assertThatThrownBy(() -> + converter.convertTruststore(trustedCertificates, password, alias)) + .isInstanceOf(PemConversionException.class).hasMessage(PASSWORD_ERROR_MSG); + } + + @Test + void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongPrivateKey() throws IOException { + // given + final String alias = "keystore-entry"; + final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); + final List certificateChain = getCertificates(); + final PemConverter converter = new PemConverter(PKCS12); + + // when then + assertThatThrownBy(() -> converter.convertKeystore(certificateChain, password, alias, privateKey)) + .isInstanceOf(PemConversionException.class).hasMessage(KEY_ERROR_MSG); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongCertificates(String conversionTarget) { + // given + final String alias = "keystore-entry"; + final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); + final List certificateChain = List.of("certificate1", "certificate2"); + final PemConverter converter = new PemConverter(conversionTarget); + privateKeyMockSetup(); + + // when then + assertThatThrownBy(() -> converter.convertKeystore(certificateChain, password, alias, privateKey)) + .isInstanceOf(PemConversionException.class).hasMessage(CERTIFICATES_ERROR_MSG); + } + + private void privateKeyMockSetup() { + when(privateKey.getEncoded()).thenReturn(key); + when(privateKey.getAlgorithm()).thenReturn(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM); + when(privateKey.getFormat()).thenReturn(PKCS8); + } + + private List getCertificates() throws IOException { + return List.of( + Files.readString( + Path.of(CERT1_PATH), StandardCharsets.UTF_8), + Files.readString( + Path.of(CERT2_PATH), StandardCharsets.UTF_8) + ); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java new file mode 100644 index 00000000..3457f32a --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java @@ -0,0 +1,33 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.certification.conversion; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RandomPasswordGeneratorTest { + + @Test + void shouldGenerateRandomPasswordOfGivenLengthMatchingThePattern() { + Password password = new RandomPasswordGenerator().generate(24); + assertTrue(password.isCorrectPasswordPattern()); + } +} \ No newline at end of file diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/writer/CertFileWriterTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/writer/CertFileWriterTest.java new file mode 100644 index 00000000..11259368 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/writer/CertFileWriterTest.java @@ -0,0 +1,76 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.certification.writer; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.onap.oom.certservice.client.certification.exception.CertFileWriterException; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CertFileWriterTest { + + private static final String RESOURCES_PATH = "src/test/resources/"; + private static final String OUTPUT_PATH = RESOURCES_PATH + "generatedFiles/"; + private static final String NOT_EXISTING_OUTPUT_PATH = OUTPUT_PATH + "directoryDoesNotExist/"; + private static final String TRUSTSTORE_P12 = "truststore.p12"; + private File outputDirectory = new File(OUTPUT_PATH); + + @AfterEach + void cleanUpFiles() { + deleteDirectoryRecursive(outputDirectory); + } + + @ParameterizedTest + @ValueSource(strings = {OUTPUT_PATH, NOT_EXISTING_OUTPUT_PATH}) + void certFileWriterShouldCreateFilesWithDataInGivenLocation(String outputPath) + throws IOException, CertFileWriterException { + // given + File truststore = new File(outputPath + TRUSTSTORE_P12); + CertFileWriter certFileWriter = CertFileWriter.createWithDir(outputPath); + final byte[] data = new byte[]{-128, 1, 2, 3, 127}; + + // when + certFileWriter.saveData(data, TRUSTSTORE_P12); + + // then + assertThat(truststore.exists()).isTrue(); + assertThat(Files.readAllBytes(Path.of(outputPath + TRUSTSTORE_P12))).isEqualTo(data); + } + + private void deleteDirectoryRecursive(File dirForDeletion) { + List.of(dirForDeletion.listFiles()).forEach(file -> { + if (file.isDirectory()) { + deleteDirectoryRecursive(file); + } + file.delete(); + }); + dirForDeletion.delete(); + } + +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvProviderTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvProviderTest.java new file mode 100644 index 00000000..3181ec9f --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvProviderTest.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.configuration; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +class EnvProviderTest { + private static final String TEST_ENV = "testEnv"; + private static final String TEST_ENV_VALUE = "prod"; + + private EnvProvider envProvider; + + @BeforeEach + void setUp() { + envProvider = Mockito.spy(EnvProvider.class); + } + + @Test + void shouldReturnSystemEnvVariableWhenItWasDefined() { + // given + when(envProvider.getSystemEnv(TEST_ENV)).thenReturn(TEST_ENV_VALUE); + + // when + final Optional testEnv = envProvider.readEnvVariable(TEST_ENV); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV_VALUE); + } + + @Test + void shouldReportThatSystemEnvVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envProvider.readEnvVariable(TEST_ENV); + + // then + assertThat(testEnv).isNotPresent(); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForCsrTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForCsrTest.java new file mode 100644 index 00000000..ade13f75 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForCsrTest.java @@ -0,0 +1,201 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.configuration; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +class EnvsForCsrTest { + private static final String TEST_ENV = "testEnv"; + private EnvsForCsr envsForCsr; + + @BeforeEach + public void setUp() { + envsForCsr = Mockito.spy(EnvsForCsr.class); + } + + @Test + void shouldReturnSystemEnvCommonNameVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.COMMON_NAME)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getCommonName(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvCommonNameVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getCommonName(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvOrganizationVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.ORGANIZATION)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getOrganization(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvOrganizationVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getOrganization(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvOuVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.ORGANIZATION_UNIT)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getOrganizationUnit(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + public void shouldReportThatSystemEnvOuVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getOrganizationUnit(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvLocationVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.LOCATION)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getLocation(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvLocationVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getLocation(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvStateVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.STATE)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getState(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvStateVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getState(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvCountryVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.COUNTRY)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getCountry(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvCountryVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getCountry(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvSansVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.SANS)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getSubjectAlternativesName(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + public void shouldReportThatSystemEnvSansVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getSubjectAlternativesName(); + + // then + assertThat(testEnv).isNotPresent(); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForTlsTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForTlsTest.java new file mode 100644 index 00000000..54ed56b7 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForTlsTest.java @@ -0,0 +1,133 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.configuration; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +class EnvsForTlsTest { + + private static final String TEST_ENV = "testEnv"; + private EnvsForTls envsForTls; + + @BeforeEach + public void setUp() { + envsForTls = Mockito.spy(EnvsForTls.class); + } + + @Test + void shouldReturnSystemEnvKeyStorePathVariableWhenItWasDefined() { + // given + when(envsForTls.readEnv(TlsConfigurationEnvs.KEYSTORE_PATH)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForTls.getKeystorePath(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvKeyStorePathVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForTls.getKeystorePath(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvKeyStorePasswordVariableWhenItWasDefined() { + // given + when(envsForTls.readEnv(TlsConfigurationEnvs.KEYSTORE_PASSWORD)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForTls.getKeystorePassword(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvKeyStorePasswordVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForTls.getKeystorePassword(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvTrustStorePathVariableWhenItWasDefined() { + // given + when(envsForTls.readEnv(TlsConfigurationEnvs.TRUSTSTORE_PATH)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForTls.getTruststorePath(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvTrustStorePathVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForTls.getTruststorePath(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvTrustStorePasswordVariableWhenItWasDefined() { + // given + when(envsForTls.readEnv(TlsConfigurationEnvs.TRUSTSTORE_PASSWORD)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForTls.getTruststorePassword(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvTrustStorePasswordVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForTls.getTruststorePassword(); + + // then + assertThat(testEnv).isNotPresent(); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java new file mode 100644 index 00000000..6ebc3f2a --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.configuration.exception; + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.api.ExitStatus; + +import static org.assertj.core.api.Assertions.assertThat; + + +class TlsConfigurationExceptionTest { + + @Test + void containsProperExitStatus() { + // Given + ExitStatus exitStatus = null; + + // When + try { + throw new TlsConfigurationException("Test message"); + } catch (TlsConfigurationException e) { + exitStatus = e.applicationExitStatus(); + } + + // Then + assertThat(exitStatus) + .isNotNull() + .isEqualTo(ExitStatus.TLS_CONFIGURATION_EXCEPTION); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java new file mode 100644 index 00000000..e55e55b6 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java @@ -0,0 +1,93 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.configuration.factory; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +class AbstractConfigurationFactoryTest { + + private final AbstractConfigurationFactory cut = mock(AbstractConfigurationFactory.class, Mockito.CALLS_REAL_METHODS); + + @ParameterizedTest + @ValueSource(strings = {"/var/log", "/", "/var/log/", "/second_var", "/second-var"}) + void shouldAcceptValidPath(String path) { + assertThat(cut.isPathValid(path)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"/var/log?", "", "var_", "var", "//", "/var//log"}) + void shouldRejectInvalidPath(String path) { + assertThat(cut.isPathValid(path)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"PL", "DE", "PN", "US", "IO", "CA", "KH", "CO", "DK", "EC", "CZ", "CN", "BR", "BD", "BE"}) + void shouldAcceptValidCountryCode(String countryCode) { + assertThat(cut.isCountryValid(countryCode)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"", "QQ", "AFG", "D", "&*", "!", "ONAP", "p", "pl", "us", "afg"}) + void shouldRejectInvalidCountryCode(String countryCode) { + assertThat(cut.isCountryValid(countryCode)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"caname", "caname1", "123caName", "ca1name"}) + void shouldAcceptValidAlphanumeric(String caName) { + assertThat(cut.isAlphaNumeric(caName)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"44caname$", "#caname1", "1c_aname", "ca1-name"}) + void shouldRejectInvalidAlphanumeric(String caName) { + assertThat(cut.isAlphaNumeric(caName)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"example.com", "www.example.com"}) + void shouldAcceptValidCommonName(String commonName) { + assertThat(cut.isCommonNameValid(commonName)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"https://example.com", "http://example.com", "example.com:8080", "0.0.0.0", "@#$%.com"}) + void shouldRejectInvalidCommonName(String commonName) { + assertThat(cut.isCommonNameValid(commonName)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"JKS", "P12", "PEM"}) + void shouldAcceptValidOutputType(String outputType) { + assertThat(cut.isOutputTypeValid(outputType)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"jks", "p12", "pem", "", "pass", "!@$#pp"}) + void shouldRejectInvalidOutputType(String outputType) { + assertThat(cut.isOutputTypeValid(outputType)).isFalse(); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java new file mode 100644 index 00000000..44827494 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java @@ -0,0 +1,155 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.configuration.factory; + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.configuration.ClientConfigurationEnvs; +import org.onap.oom.certservice.client.configuration.EnvsForClient; +import org.onap.oom.certservice.client.configuration.exception.ClientConfigurationException; +import org.onap.oom.certservice.client.configuration.model.ClientConfiguration; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ClientConfigurationFactoryTest { + + private static final String CA_NAME_VALID = "catest2"; + private static final String TIME_OUT_VALID = "30000"; + private static final String OUTPUT_PATH_VALID = "/opt/app/oom"; + private static final String URL_TO_CERT_SERVICE_VALID = "https://cert-service:8443/v1/certificate/"; + private static final String URL_TO_CERT_SERVICE_DEFAULT = "https://oom-cert-service:8443/v1/certificate/"; + private static final String CA_NAME_INVALID = "catest2#$"; + private static final String OUTPUT_PATH_INVALID = "/opt//app/oom"; + private static final String OUTPUT_TYPE_VALID = "JKS"; + private static final String OUTPUT_TYPE_INVALID = "JKSS"; + private static final String OUTPUT_TYPE_DEFAULT = "P12"; + + private EnvsForClient envsForClient = mock(EnvsForClient.class); + + + @Test + void create_shouldReturnSuccessWhenAllVariablesAreSetAndValid() throws ClientConfigurationException { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); + when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); + when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_VALID)); + + // when + ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); + System.out.println(configuration.toString()); + + // then + assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); + assertThat(configuration.getRequestTimeout()).isEqualTo(Integer.valueOf(TIME_OUT_VALID)); + assertThat(configuration.getCertsOutputPath()).isEqualTo(OUTPUT_PATH_VALID); + assertThat(configuration.getUrlToCertService()).isEqualTo(URL_TO_CERT_SERVICE_VALID); + assertThat(configuration.getOutputType()).isEqualTo(OUTPUT_TYPE_VALID); + } + + @Test + void create_shouldReturnSuccessWhenDefaultVariablesAreNotSet() throws ClientConfigurationException { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + + // when + ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); + + // then + assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); + assertThat(configuration.getRequestTimeout()).isEqualTo(Integer.valueOf(TIME_OUT_VALID)); + assertThat(configuration.getCertsOutputPath()).isEqualTo(OUTPUT_PATH_VALID); + assertThat(configuration.getUrlToCertService()).isEqualTo(URL_TO_CERT_SERVICE_DEFAULT); + assertThat(configuration.getOutputType()).isEqualTo(OUTPUT_TYPE_DEFAULT); + } + + @Test + void create_shouldReturnClientExceptionWhenRequiredVariableIsNotSet() { + // given + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + + // when + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + + // then + assertThatExceptionOfType(ClientConfigurationException.class) + .isThrownBy(configurationFactory::create) + .withMessageContaining(ClientConfigurationEnvs.CA_NAME + " is invalid."); + } + + @Test + void create_shouldReturnClientExceptionWhenCaNameContainsSpecialCharacters() { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_INVALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); + when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); + + // when + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + + // when/then + assertThatExceptionOfType(ClientConfigurationException.class) + .isThrownBy(configurationFactory::create) + .withMessageContaining(ClientConfigurationEnvs.CA_NAME + " is invalid."); + } + + @Test + void create_shouldReturnClientExceptionWhenOutputPathContainsSpecialCharacters() { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_INVALID)); + when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); + when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); + + // when + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + + //then + assertThatExceptionOfType(ClientConfigurationException.class) + .isThrownBy(configurationFactory::create) + .withMessageContaining(ClientConfigurationEnvs.OUTPUT_PATH + " is invalid."); + } + + @Test + void create_shouldReturnClientExceptionWhenOutputTypeIsInvalid() { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); + when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); + when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_INVALID)); + + // when + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + + //then + assertThatExceptionOfType(ClientConfigurationException.class) + .isThrownBy(configurationFactory::create) + .withMessageContaining(ClientConfigurationEnvs.OUTPUT_TYPE + " is invalid."); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java new file mode 100644 index 00000000..e27cb57a --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java @@ -0,0 +1,186 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.configuration.factory; + +import org.assertj.core.api.Condition; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.configuration.CsrConfigurationEnvs; +import org.onap.oom.certservice.client.configuration.EnvsForCsr; +import org.onap.oom.certservice.client.configuration.exception.CsrConfigurationException; +import org.onap.oom.certservice.client.configuration.model.CsrConfiguration; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.oom.certservice.client.api.ExitStatus.CSR_CONFIGURATION_EXCEPTION; + +public class CsrConfigurationFactoryTest { + + private static final String COMMON_NAME_VALID = "onap.org"; + private static final String SANS_VALID = "test-name"; + private static final String COUNTRY_VALID = "US"; + private static final String LOCATION_VALID = "San-Francisco"; + private static final String ORGANIZATION_VALID = "Linux-Foundation"; + private static final String ORGANIZATION_UNIT_VALID = "ONAP"; + private static final String STATE_VALID = "California"; + private static final String COMMON_NAME_INVALID = "onap.org*&"; + private static final String COUNTRY_INVALID = "PLA"; + private static final String ORGANIZATION_INVALID = "Linux?Foundation"; + + private EnvsForCsr envsForCsr = mock(EnvsForCsr.class); + private CsrConfigurationFactory testedFactory; + private Condition expectedExitCodeCondition = new Condition<>("Correct exit code") { + @Override + public boolean matches(CsrConfigurationException exception) { + return exception.applicationExitStatus() == CSR_CONFIGURATION_EXCEPTION; + } + }; + + @BeforeEach + void setUp() { + testedFactory = new CsrConfigurationFactory(envsForCsr); + } + + @Test + void shouldReturnCorrectConfiguration_WhenAllVariablesAreSetAndValid() throws CsrConfigurationException { + // given + mockEnvsWithAllValidParameters(); + + // when + CsrConfiguration configuration = testedFactory.create(); + + // then + assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); + assertThat(configuration.getSans()).isEqualTo(SANS_VALID); + assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); + assertThat(configuration.getLocation()).isEqualTo(LOCATION_VALID); + assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); + assertThat(configuration.getOrganizationUnit()).isEqualTo(ORGANIZATION_UNIT_VALID); + assertThat(configuration.getState()).isEqualTo(STATE_VALID); + } + + @Test + void shouldReturnCorrectConfiguration_WhenNotRequiredVariablesAreNotSet() throws CsrConfigurationException { + // given + mockEnvsWithValidRequiredParameters(); + + // when + CsrConfiguration configuration = testedFactory.create(); + + // then + assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); + assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); + assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); + assertThat(configuration.getState()).isEqualTo(STATE_VALID); + } + + + @Test + void shouldThrowCsrConfigurationException_WhenCommonNameInvalid() { + // given + mockEnvsWithInvalidCommonName(); + + // when/then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(testedFactory::create) + .withMessageContaining(CsrConfigurationEnvs.COMMON_NAME + " is invalid.") + .has(expectedExitCodeCondition); + } + + @Test + void shouldThrowCsrConfigurationException_WhenOrganizationInvalid() { + // given + mockEnvsWithInvalidOrganization(); + + // when/then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(testedFactory::create) + .withMessageContaining(CsrConfigurationEnvs.ORGANIZATION + " is invalid.") + .has(expectedExitCodeCondition); + + } + + @Test + void shouldThrowCsrConfigurationException_WhenCountryInvalid() { + // given + mockEnvsWithInvalidCountry(); + + // when/then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(testedFactory::create) + .withMessageContaining(CsrConfigurationEnvs.COUNTRY + " is invalid.") + .has(expectedExitCodeCondition); + + } + + @Test + void shouldThrowCsrConfigurationExceptionWhenStateInvalid() { + // given + mockEnvsWithInvalidState(); + // when/then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(testedFactory::create) + .withMessageContaining(CsrConfigurationEnvs.STATE + " is invalid.") + .has(expectedExitCodeCondition); + } + + private void mockEnvsWithAllValidParameters() { + mockEnvsWithValidRequiredParameters(); + mockEnvsWithValidOptionalParameters(); + } + + private void mockEnvsWithValidOptionalParameters() { + when(envsForCsr.getOrganizationUnit()).thenReturn(Optional.of(ORGANIZATION_UNIT_VALID)); + when(envsForCsr.getLocation()).thenReturn(Optional.of(LOCATION_VALID)); + when(envsForCsr.getSubjectAlternativesName()).thenReturn(Optional.of(SANS_VALID)); + } + + private void mockEnvsWithValidRequiredParameters() { + when(envsForCsr.getCommonName()).thenReturn(Optional.of(COMMON_NAME_VALID)); + when(envsForCsr.getCountry()).thenReturn(Optional.of(COUNTRY_VALID)); + when(envsForCsr.getOrganization()).thenReturn(Optional.of(ORGANIZATION_VALID)); + when(envsForCsr.getState()).thenReturn(Optional.of(STATE_VALID)); + } + + private void mockEnvsWithInvalidCommonName() { + mockEnvsWithAllValidParameters(); + when(envsForCsr.getCommonName()).thenReturn(Optional.of(COMMON_NAME_INVALID)); + } + + private void mockEnvsWithInvalidCountry() { + mockEnvsWithAllValidParameters(); + when(envsForCsr.getCountry()).thenReturn(Optional.of(COUNTRY_INVALID)); + } + + private void mockEnvsWithInvalidOrganization() { + mockEnvsWithAllValidParameters(); + when(envsForCsr.getOrganization()).thenReturn(Optional.of(ORGANIZATION_INVALID)); + } + + private void mockEnvsWithInvalidState() { + mockEnvsWithAllValidParameters(); + when(envsForCsr.getState()).thenReturn(Optional.empty()); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java new file mode 100644 index 00000000..923bc18d --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java @@ -0,0 +1,197 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.configuration.factory; + +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.oom.certservice.client.configuration.EnvsForTls; +import org.onap.oom.certservice.client.configuration.exception.TlsConfigurationException; + +import javax.net.ssl.SSLContext; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + + +@ExtendWith(MockitoExtension.class) +public class SslContextFactoryTest { + + public static final String INVALID_KEYSTORE_PATH = "nonexistent/keystore"; + public static final String VALID_KEYSTORE_NAME = "keystore.jks"; + public static final String VALID_KEYSTORE_PASSWORD = "secret"; + public static final String INVALID_KEYSTORE_PASSWORD = "wrong_secret"; + public static final String INVALID_TRUSTSTORE_PATH = "nonexistent/truststore"; + public static final String VALID_TRUSTSTORE_PASSWORD = "secret"; + public static final String INVALID_TRUSTSTORE_PASSWORD = "wrong_secret"; + public static final String VALID_TRUSTSTORE_NAME = "truststore.jks"; + @Mock + private EnvsForTls envsForTls; + + @Test + public void shouldThrowExceptionWhenKeystorePathEnvIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.empty()); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + Exception exception = assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + assertThat(exception.getMessage()).contains("KEYSTORE_PATH"); + } + + @Test + public void shouldThrowExceptionWhenKeystorePasswordEnvIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.empty()); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + Exception exception = assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + assertThat(exception.getMessage()).contains("KEYSTORE_PASSWORD"); + } + + @Test + public void shouldThrowExceptionWhenTruststorePathEnvIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); + when(envsForTls.getTruststorePath()).thenReturn(Optional.empty()); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + Exception exception = assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + assertThat(exception.getMessage()).contains("TRUSTSTORE_PATH"); + } + + @Test + public void shouldThrowExceptionWhenTruststorePasswordEnvIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore")); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.empty()); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + Exception exception = assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + assertThat(exception.getMessage()).contains("TRUSTSTORE_PASSWORD"); + } + + @Test + public void shouldThrowExceptionWhenKeystoreIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(INVALID_KEYSTORE_PATH)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("secret")); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore.jks")); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of("secret")); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + } + + @Test + public void shouldThrowExceptionWhenKeystorePasswordIsWrong() { + // Given + String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(INVALID_KEYSTORE_PASSWORD)); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of(VALID_TRUSTSTORE_NAME)); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + } + + @Test + public void shouldThrowExceptionWhenTruststoreIsMissing() { + // Given + String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PATH)); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + } + + @Test + public void shouldThrowExceptionWhenTruststorePasswordIsWrong() { + // Given + String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); + String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PASSWORD)); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + } + + @Test + public void shouldReturnSslContext() throws TlsConfigurationException { + // Given + String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); + String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When + SSLContext sslContext = sslContextFactory.create(); + + // Then + assertNotNull(sslContext); + } + + private String getResourcePath(String resource) { + return getClass().getClassLoader().getResource(resource).getFile(); + } +} + diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/httpclient/HttpClientTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/httpclient/HttpClientTest.java new file mode 100644 index 00000000..553de25c --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/httpclient/HttpClientTest.java @@ -0,0 +1,144 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * 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.oom.certservice.client.httpclient; + +import org.apache.http.HttpEntity; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.httpclient.exception.CertServiceApiResponseException; +import org.onap.oom.certservice.client.httpclient.exception.HttpClientException; +import org.onap.oom.certservice.client.httpclient.model.CertServiceResponse; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.List; + +import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; +import static java.net.HttpURLConnection.HTTP_OK; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.CA_NAME; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.CORRECT_RESPONSE; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.CSR; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.MISSING_PK_RESPONSE; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.PK; + +class HttpClientTest { + + private HttpClient httpClient; + private CloseableHttpClient closeableHttpClient; + private HttpEntity httpEntity; + private StatusLine statusLine; + private CloseableHttpResponse httpResponse; + + @BeforeEach + void setUp() { + + closeableHttpClient = mock(CloseableHttpClient.class); + httpEntity = mock(HttpEntity.class); + statusLine = mock(StatusLine.class); + httpResponse = mock(CloseableHttpResponse.class); + + CloseableHttpsClientProvider httpClientProvider = mock(CloseableHttpsClientProvider.class); + + when(httpClientProvider.getClient()).thenReturn(closeableHttpClient); + String testCertServiceAddress = ""; + httpClient = new HttpClient(httpClientProvider, testCertServiceAddress); + } + + @Test + void shouldReturnCorrectListsOfCertificatedChainsAndTrustedCertificates_WhenRequestDataIsCorrect() + throws Exception { + + // given + mockServerResponse(HTTP_OK, CORRECT_RESPONSE); + + // when + CertServiceResponse certServiceResponse = + httpClient.retrieveCertServiceData(CA_NAME, CSR, PK); + List certificateChain = certServiceResponse.getCertificateChain(); + List trustedCertificate = certServiceResponse.getTrustedCertificates(); + + // then + assertThat(certServiceResponse).isNotNull(); + + final int expectedTwoElements = 2; + + assertThat(certificateChain).hasSize(expectedTwoElements); + assertThat(trustedCertificate).hasSize(expectedTwoElements); + + assertThat(certificateChain.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN); + assertThat(trustedCertificate.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES); + } + + @Test + void shouldThrowCertServiceApiResponseException_WhenPkHeaderIsMissing() throws Exception { + + //given + mockServerResponse(HTTP_BAD_REQUEST, MISSING_PK_RESPONSE); + + //when //then + assertThatExceptionOfType(CertServiceApiResponseException.class) + .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); + } + + @Test + void shouldThrowHttpClientException_WhenCannotExecuteRequestToApi() throws Exception { + + //given + when(closeableHttpClient.execute(any(HttpGet.class))).thenThrow(IOException.class); + + //when //then + assertThatExceptionOfType(HttpClientException.class) + .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); + } + + @Test + void shouldThrowHttpClientException_WhenCannotParseResponseToString() throws Exception { + + //given + mockServerResponse(HTTP_OK, CORRECT_RESPONSE); + when(httpEntity.getContent()).thenThrow(IOException.class); + + //when //then + assertThatExceptionOfType(HttpClientException.class) + .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); + } + + private void mockServerResponse(int serverCodeResponse, String stringResponse) + throws IOException { + when(statusLine.getStatusCode()).thenReturn(serverCodeResponse); + when(httpResponse.getStatusLine()).thenReturn(statusLine); + when(httpResponse.getEntity()).thenReturn(httpEntity); + when(closeableHttpClient.execute(any(HttpGet.class))).thenReturn(httpResponse); + + when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream(stringResponse.getBytes())); + } +} -- cgit 1.2.3-korg