diff options
83 files changed, 2223 insertions, 1683 deletions
diff --git a/certService/pom.xml b/certService/pom.xml index 4d75fe90..8c8a487a 100644 --- a/certService/pom.xml +++ b/certService/pom.xml @@ -18,10 +18,10 @@ <parent> <groupId>org.onap.oom.platform.cert-service</groupId> <artifactId>oom-certservice</artifactId> - <version>1.2.0-SNAPSHOT</version> + <version>2.0.0-SNAPSHOT</version> </parent> <artifactId>oom-certservice-api</artifactId> - <version>1.2.0-SNAPSHOT</version> + <version>2.0.0-SNAPSHOT</version> <name>oom-certservice-api</name> <description>OOM Certification Service Api</description> <packaging>jar</packaging> diff --git a/certServiceClient/pom.xml b/certServiceClient/pom.xml index 8c156413..0a1bd29e 100644 --- a/certServiceClient/pom.xml +++ b/certServiceClient/pom.xml @@ -18,12 +18,12 @@ <parent> <artifactId>oom-certservice</artifactId> <groupId>org.onap.oom.platform.cert-service</groupId> - <version>1.2.0-SNAPSHOT</version> + <version>2.0.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>oom-certservice-client</artifactId> - <version>1.2.0-SNAPSHOT</version> + <version>2.0.0-SNAPSHOT</version> <name>oom-certservice-client</name> <description>OOM Certification Service Api Client</description> <packaging>jar</packaging> diff --git a/docs/sections/release-notes.rst b/docs/sections/release-notes.rst index daeab0f2..b3eb3981 100644 --- a/docs/sections/release-notes.rst +++ b/docs/sections/release-notes.rst @@ -6,6 +6,47 @@ Release Notes ============== +Version: 2.0.0 +-------------- + +:Release Date: + +**New Features** + + - The same functionality as in aaf-certservice 1.2.0 + +**Bug Fixes** + + N/A + +**Known Issues** + + N/A + +**Security Notes** + + N/A + +*Fixed Security Issues* + + N/A + +*Known Security Issues* + + N/A + +*Known Vulnerabilities in Used Modules* + + N/A + +**Upgrade Notes** + +**Deprecation Notes** + +**Other** + +=========== + Version: 1.2.0 -------------- @@ -23,7 +23,7 @@ </parent> <groupId>org.onap.oom.platform.cert-service</groupId> <artifactId>oom-certservice</artifactId> - <version>1.2.0-SNAPSHOT</version> + <version>2.0.0-SNAPSHOT</version> <name>oom-certservice</name> <description>OOM Certification Service</description> <packaging>pom</packaging> diff --git a/releases/2.0.0-container.yaml b/releases/2.0.0-container.yaml new file mode 100644 index 00000000..ce7c1e1c --- /dev/null +++ b/releases/2.0.0-container.yaml @@ -0,0 +1,12 @@ +distribution_type: 'container' +container_release_tag: '2.0.0' +container_pull_registry: nexus3.onap.org:10003 +container_push_registry: nexus3.onap.org:10002 +project: 'oom-platform-cert-service' +log_dir: 'oom-platform-cert-service-maven-docker-stage-master/40' +ref: fedbe9461dbc5667f35651e6211f025989578e50 +containers: + - name: 'org.onap.oom.platform.cert-service.oom-certservice-api' + version: '2.0.0-20200903T201647Z' + - name: 'org.onap.oom.platform.cert-service.oom-certservice-client' + version: '2.0.0-20200903T201647Z'
\ No newline at end of file diff --git a/trustStoreMerger/README.md b/trustStoreMerger/README.md index dff8a145..5a2c2b47 100644 --- a/trustStoreMerger/README.md +++ b/trustStoreMerger/README.md @@ -26,12 +26,18 @@ Exemplary config.env file with necessary envs ``` TRUSTSTORES_PATHS=/var/certs/truststore.jks:/var/certs/truststore.pem TRUSTSTORES_PASSWORDS_PATHS=/var/certs/truststoreJks.pass: +KEYSTORE_SOURCE_PATHS=/var/certs/external/keystore.jks:/var/certs/external/keystore.pass +KEYSTORE_DESTINATION_PATHS=/var/certs/cert.jks:/var/certs/jks.pass ``` TRUSTSTORES_PATHS env indicates paths (separated by ":") where truststores files are located. TRUSTSTORES_PASSWORDS_PATHS env indicates paths (separated by ":") where files with passwords to truststores are located. PEM is not protected by password so its value should be empty +KEYSTORE_SOURCE_PATHS env (optional) indicates paths (separated by ":") where files to copy are located. + +KEYSTORE_DESTINATION_PATHS env (optional) indicates paths (separated by ":") to files which should be replaced. Before keystore files override, destination files will be copied with addition of .bak extension. + Execute below command in order to run app as docker container ``` docker run \ @@ -42,9 +48,10 @@ onap/org.onap.oom.platform.cert-service.oom-truststore-merger:latest ``` Before run replace <src_path> with absolute path where you located truststores to merge (eg. /certs/resources/) -Output from merger (when pointed more than one truststore to merge in TRUSTSTORES_PATHS env) success execution should be: +Output from merger (when pointed more than one truststore to merge in TRUSTSTORES_PATHS env and provided optional envs) success execution should be: 1. Created backup file (with .bak ext) of first truststore pointed in TRUSTSTORES_PATHS env -2. First truststore pointed in TRUSTSTORES_PATHS env contains merged certificates from all truststores mentioned in TRUSTSTORES_PATHS env +2. Keystores files listed in KEYSTORE_SOURCE_PATHS env overrides corresponding to them files defined in KEYSTORE_DESTINATION_PATHS env. +3. Keystores listed in KEYSTORE_SOURCE_PATHS env are in locations taken from KEYSTORE_DESTINATION_PATHS env. Files listed in KEYSTORE_DESTINATION_PATHS env before application run, still exist with appended .bak extension. Remove docker container: ``` @@ -75,3 +82,6 @@ docker logs oom-merger 9 Missing truststore certificates in provided file 10 Alias conflict detected 11 Cannot save truststore file +12 Cannot copy keystore file +13 Keystore file does not exist +99 Application exited abnormally diff --git a/trustStoreMerger/pom.xml b/trustStoreMerger/pom.xml index fd2aff05..d150a9b3 100644 --- a/trustStoreMerger/pom.xml +++ b/trustStoreMerger/pom.xml @@ -5,12 +5,12 @@ <parent> <artifactId>oom-certservice</artifactId> <groupId>org.onap.oom.platform.cert-service</groupId> - <version>1.2.0-SNAPSHOT</version> + <version>2.0.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>oom-truststore-merger</artifactId> - <version>1.2.0-SNAPSHOT</version> + <version>2.0.0-SNAPSHOT</version> <name>oom-truststore-merger</name> <description>Truststore merging application</description> <packaging>jar</packaging> @@ -70,7 +70,7 @@ <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> - <mainClass>org.onap.oom.truststoremerger.MainApp</mainClass> + <mainClass>org.onap.oom.certservice.postprocessor.MainApp</mainClass> </transformer> </transformers> </configuration> @@ -142,6 +142,10 @@ <dependencies> <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + </dependency> + <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> </dependency> diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/AppExecutor.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/AppExecutor.java new file mode 100644 index 00000000..2ef30b68 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/AppExecutor.java @@ -0,0 +1,54 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor; + +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AppExecutor { + + private static final Logger LOGGER = LoggerFactory.getLogger(AppExecutor.class); + + private AppExitHandler exitHandler; + + AppExecutor() { + this(new AppExitHandler()); + } + + AppExecutor(AppExitHandler exitHandler) { + this.exitHandler = exitHandler; + } + + + public void execute(Runnable logic) { + try { + logic.run(); + exitHandler.exit(ExitStatus.SUCCESS); + } catch (ExitableException e) { + LOGGER.error("Application failed: ", e); + exitHandler.exit(e.applicationExitStatus()); + } catch (Exception e) { + LOGGER.error("Application failed (unexpected error): ", e); + exitHandler.exit(ExitStatus.UNEXPECTED_EXCEPTION); + } + } +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/AppExitHandler.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/AppExitHandler.java index c257756a..15677dc4 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/AppExitHandler.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/AppExitHandler.java @@ -17,9 +17,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger; +package org.onap.oom.certservice.postprocessor; -import org.onap.oom.truststoremerger.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,7 +27,7 @@ public class AppExitHandler { private static final Logger LOGGER = LoggerFactory.getLogger(AppExitHandler.class); public void exit(ExitStatus exitStatus) { - LOGGER.info("Application exits with following exit code: {} and message: {}", + LOGGER.info("Application exits with code [{}] and message: {}", exitStatus.getExitCodeValue(), exitStatus.getMessage()); System.exit(exitStatus.getExitCodeValue()); } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/CertificatePostProcessor.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/CertificatePostProcessor.java new file mode 100644 index 00000000..b9038227 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/CertificatePostProcessor.java @@ -0,0 +1,47 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor; + +import org.onap.oom.certservice.postprocessor.common.FileTools; +import org.onap.oom.certservice.postprocessor.configuration.AppConfigurationLoader; +import org.onap.oom.certservice.postprocessor.configuration.model.AppConfiguration; +import org.onap.oom.certservice.postprocessor.copier.KeystoreCopier; +import org.onap.oom.certservice.postprocessor.merger.TruststoreMerger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class CertificatePostProcessor implements Runnable { + + private static final Logger LOGGER = LoggerFactory.getLogger(CertificatePostProcessor.class); + + private AppConfigurationLoader config = new AppConfigurationLoader(); + private TruststoreMerger merger = new TruststoreMerger(); + private KeystoreCopier copier = new KeystoreCopier(new FileTools()); + + public void run() { + LOGGER.debug("Loading configuration..."); + AppConfiguration configuration = config.loadConfiguration(); + LOGGER.debug("Starting TruststoreMerger..."); + merger.mergeTruststores(configuration); + LOGGER.debug("Starting KeystoreCopier..."); + copier.copyKeystores(configuration); + LOGGER.debug("Certificate post processing finished successfully."); + } +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/MainApp.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/MainApp.java index a26b9def..f815f489 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/MainApp.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/MainApp.java @@ -17,12 +17,11 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger; +package org.onap.oom.certservice.postprocessor; public class MainApp { public static void main(String[] args) { - TrustStoreMerger trustStoreMerger = new TrustStoreMerger(new AppExitHandler()); - trustStoreMerger.run(); + new AppExecutor().execute(new CertificatePostProcessor()); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/api/CertificateConstants.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/api/CertificateConstants.java index 68c5d13c..629397e4 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/api/CertificateConstants.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/api/CertificateConstants.java @@ -17,12 +17,12 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.api; +package org.onap.oom.certservice.postprocessor.api; public class CertificateConstants { - public static final String JKS_INSTANCE = "JKS"; - public static final String PKCS12_INSTANCE = "PKCS12"; + public static final String JKS_TYPE = "JKS"; + public static final String PKCS12_TYPE = "PKCS12"; public static final String X_509_CERTIFICATE = "X.509"; public static final String BOUNCY_CASTLE_PROVIDER = "BC"; diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/api/ExitStatus.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/api/ExitStatus.java index b9111bf9..b6cebeb1 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/api/ExitStatus.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/api/ExitStatus.java @@ -17,13 +17,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.api; +package org.onap.oom.certservice.postprocessor.api; public enum ExitStatus { SUCCESS(0, "Success"), - TRUSTSTORES_PATHS_PROVIDER_EXCEPTION(1, "Invalid paths in environment variables"), - MERGER_CONFIGURATION_EXCEPTION(2, "Invalid merger configuration"), + CERTIFICATES_PATHS_VALIDATION_EXCEPTION(1, "Invalid paths in environment variables"), + CONFIGURATION_EXCEPTION(2, "Invalid merger configuration"), TRUSTSTORE_FILE_FACTORY_EXCEPTION(3, "Invalid truststore file-password pair"), PASSWORD_READER_EXCEPTION(4, "Cannot read password from file"), CREATE_BACKUP_EXCEPTION(5, "Cannot create backup file"), @@ -32,7 +32,10 @@ public enum ExitStatus { TRUSTSTORE_DATA_OPERATION_EXCEPTION(8, "Cannot operate on truststore data"), MISSING_TRUSTSTORE_EXCEPTION(9, "Missing truststore certificates in provided file"), ALIAS_CONFLICT_EXCEPTION(10, "Alias conflict detected"), - WRITE_TRUSTSTORE_FILE_EXCEPTION(11, "Cannot save truststore file"); + WRITE_TRUSTSTORE_FILE_EXCEPTION(11, "Cannot save truststore file"), + KEYSTORE_FILE_COPY_EXCEPTION(12, "Cannot copy keystore file"), + KEYSTORE_NOT_EXIST_EXCEPTION(13, "Keystore file does not exist"), + UNEXPECTED_EXCEPTION(99, "Application exited abnormally"); private final int value; diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/api/ExitableException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/api/ExitableException.java index ec28d466..54a7c6a1 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/api/ExitableException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/api/ExitableException.java @@ -17,9 +17,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.api; +package org.onap.oom.certservice.postprocessor.api; -public class ExitableException extends Exception { +public class ExitableException extends RuntimeException { private final ExitStatus exitStatus; diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/FileManager.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/common/ExtensionResolver.java index 12029ade..7a785ae1 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/FileManager.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/common/ExtensionResolver.java @@ -17,15 +17,17 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider; +package org.onap.oom.certservice.postprocessor.common; import java.io.File; -public class FileManager { +public final class ExtensionResolver { private static final int INDEX_NOT_FOUND = -1; - public String getExtension(File file) { + private ExtensionResolver() {} + + public static String get(File file) { int extStartIndex = file.getName().lastIndexOf("."); if (extStartIndex == INDEX_NOT_FOUND) { return ""; @@ -33,7 +35,7 @@ public class FileManager { return file.getName().substring(extStartIndex).toLowerCase(); } - public boolean checkIfFileExists(File file) { + public static boolean checkIfFileExists(File file) { return file.exists(); } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/common/FileTools.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/common/FileTools.java new file mode 100644 index 00000000..620d8088 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/common/FileTools.java @@ -0,0 +1,52 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.common; + +import java.io.File; +import java.io.IOException; +import org.apache.commons.io.FileUtils; +import org.onap.oom.certservice.postprocessor.merger.exception.CreateBackupException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public final class FileTools { + + private static final Logger LOGGER = LoggerFactory.getLogger(FileTools.class); + private static final String BACKUP_EXTENSION = ".bak"; + + public void createBackup(File file) throws CreateBackupException { + LOGGER.debug("Try to create a backup of the file: {}", file.getPath()); + File backupFile = new File(file.getAbsolutePath() + BACKUP_EXTENSION); + try { + copy(file, backupFile); + } catch (IOException e) { + LOGGER.error("Could not create backup of the file: '{}'", file.getPath()); + throw new CreateBackupException(e); + } + LOGGER.debug("Backup file created: '{}'", backupFile.getAbsolutePath()); + } + + public void copy(File source, File destination) throws IOException { + LOGGER.debug("Try to copy from '{}' to '{}'.", source.getAbsolutePath(), destination.getAbsolutePath()); + FileUtils.copyFile(source, destination); + LOGGER.debug("File copied from '{}' to '{}'.", source.getAbsolutePath(), + destination.getAbsolutePath()); + } +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/PasswordReader.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/common/PasswordReader.java index d7da53b0..6e4a5f3a 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/PasswordReader.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/common/PasswordReader.java @@ -17,17 +17,21 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider; +package org.onap.oom.certservice.postprocessor.common; import java.io.File; import java.io.IOException; import java.nio.file.Files; -import org.onap.oom.truststoremerger.certification.file.exception.PasswordReaderException; +import org.onap.oom.certservice.postprocessor.merger.exception.PasswordReaderException; + +public final class PasswordReader { -public class PasswordReader { private static final String COULD_NOT_READ_PASSWORD_FROM_FILE_MSG_TEMPLATE = "Could not read password from file: %s"; - public String readPassword(File file) throws PasswordReaderException { + private PasswordReader() { + } + + public static String readPassword(File file) { try { return Files.readString(file.toPath()); } catch (IOException e) { diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/path/PathValidator.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/AppConfigurationLoader.java index 256da490..a0a00a6d 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/path/PathValidator.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/AppConfigurationLoader.java @@ -17,22 +17,18 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.path; +package org.onap.oom.certservice.postprocessor.configuration; -public class PathValidator { +import org.onap.oom.certservice.postprocessor.api.ExitableException; +import org.onap.oom.certservice.postprocessor.configuration.model.AppConfiguration; +import org.onap.oom.certservice.postprocessor.configuration.path.DelimitedPathsSplitter; +import org.onap.oom.certservice.postprocessor.configuration.path.env.EnvReader; - private static final String TRUSTSTORE_PATH_REGEX = "^(/[a-zA-Z0-9_-]+)+\\.(pem|jks|p12)"; - private static final String TRUSTSTORE_PASSWORD_PATH_REGEX = "^(/[a-zA-Z0-9_-]+)+\\.pass"; +public class AppConfigurationLoader { - public boolean isTruststorePathValid(String truststorePath) { - return isPathValid(truststorePath, TRUSTSTORE_PATH_REGEX); - } - - public boolean isTruststorePasswordPathValid(String truststorePasswordPath) { - return truststorePasswordPath.isEmpty() || isPathValid(truststorePasswordPath, TRUSTSTORE_PASSWORD_PATH_REGEX); - } - - private boolean isPathValid(String path, String regex) { - return path.matches(regex); + public AppConfiguration loadConfiguration() throws ExitableException { + DelimitedPathsSplitter pathsSplitter = new DelimitedPathsSplitter(); + AppConfigurationProvider factory = new AppConfigurationProvider(pathsSplitter, new EnvReader()); + return factory.createConfiguration(); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/AppConfigurationProvider.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/AppConfigurationProvider.java new file mode 100644 index 00000000..79e223c5 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/AppConfigurationProvider.java @@ -0,0 +1,85 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.configuration; + + +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.KEYSTORE_DESTINATION_PATHS; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.KEYSTORE_SOURCE_PATHS; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.TRUSTSTORES_PASSWORDS_PATHS; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.TRUSTSTORES_PATHS; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import org.onap.oom.certservice.postprocessor.configuration.path.env.EnvReader; +import org.onap.oom.certservice.postprocessor.configuration.exception.CertificatesPathsValidationException; +import org.onap.oom.certservice.postprocessor.configuration.exception.ConfigurationException; +import org.onap.oom.certservice.postprocessor.configuration.model.AppConfiguration; +import org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable; +import org.onap.oom.certservice.postprocessor.configuration.path.DelimitedPathsSplitter; + +public class AppConfigurationProvider { + + private final EnvReader envReader; + private final DelimitedPathsSplitter pathsSplitter; + + public AppConfigurationProvider(DelimitedPathsSplitter pathsSplitter, EnvReader envReader) { + this.envReader = envReader; + this.pathsSplitter = pathsSplitter; + } + + public AppConfiguration createConfiguration() + throws ConfigurationException, CertificatesPathsValidationException { + + List<String> truststoresPaths = getPaths(TRUSTSTORES_PATHS); + List<String> truststoresPasswordsPaths = getPaths(TRUSTSTORES_PASSWORDS_PATHS); + List<String> sourceKeystorePaths = getPaths(KEYSTORE_SOURCE_PATHS); + List<String> destinationKeystorePaths = getPaths(KEYSTORE_DESTINATION_PATHS); + + ensureSameSize(truststoresPaths, truststoresPasswordsPaths, TRUSTSTORES_PATHS.name(), + TRUSTSTORES_PASSWORDS_PATHS.name()); + ensureSameSize(sourceKeystorePaths, destinationKeystorePaths, KEYSTORE_SOURCE_PATHS.name(), + KEYSTORE_DESTINATION_PATHS.name()); + + return new AppConfiguration(truststoresPaths, truststoresPasswordsPaths, sourceKeystorePaths, + destinationKeystorePaths); + } + + private List<String> getPaths(EnvVariable envVariable) throws ConfigurationException { + Optional<String> envValue = envReader.getEnv(envVariable.name()); + isMandatoryEnvPresent(envVariable, envValue); + return envValue.isPresent() ? pathsSplitter.getValidatedPaths(envVariable, envValue) : Collections.emptyList(); + } + + private void isMandatoryEnvPresent(EnvVariable envVariable, Optional<String> envValue) { + if (envVariable.isMandatory() && envValue.isEmpty()) { + throw new ConfigurationException(envVariable + " mandatory environment variable is not defined"); + } + } + + private void ensureSameSize(List<String> firstList, List<String> secondList, String firstListEnvName, + String secondListEnvName) throws ConfigurationException { + if (firstList.size() != secondList.size()) { + throw new ConfigurationException( + "Size of " + firstListEnvName + + " does not match size of " + secondListEnvName + " environment variables"); + } + } +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/exception/CertificatesPathsValidationException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/exception/CertificatesPathsValidationException.java new file mode 100644 index 00000000..fb621017 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/exception/CertificatesPathsValidationException.java @@ -0,0 +1,30 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.configuration.exception; + +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; + +public class CertificatesPathsValidationException extends ExitableException { + + public CertificatesPathsValidationException(String errorMessage) { + super(errorMessage, ExitStatus.CERTIFICATES_PATHS_VALIDATION_EXCEPTION); + } +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/api/ConfigurationEnvs.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/exception/ConfigurationException.java index f6f8bbba..c9f9a416 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/api/ConfigurationEnvs.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/exception/ConfigurationException.java @@ -17,10 +17,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.api; +package org.onap.oom.certservice.postprocessor.configuration.exception; -public class ConfigurationEnvs { +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; - public static final String TRUSTSTORES_PATHS_ENV = "TRUSTSTORES_PATHS"; - public static final String TRUSTSTORES_PASSWORDS_PATHS_ENV = "TRUSTSTORES_PASSWORDS_PATHS"; +public class ConfigurationException extends ExitableException { + + public ConfigurationException(String errorMessage) { + super(errorMessage, ExitStatus.CONFIGURATION_EXCEPTION); + } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/MergerConfiguration.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/model/AppConfiguration.java index f3b7d935..d28dcac5 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/MergerConfiguration.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/model/AppConfiguration.java @@ -17,28 +17,40 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.configuration; +package org.onap.oom.certservice.postprocessor.configuration.model; import java.util.Collections; import java.util.List; -public class MergerConfiguration { +public final class AppConfiguration { private final List<String> truststoreFilePaths; private final List<String> truststoreFilePasswordPaths; + private final List<String> sourceKeystorePaths; + private final List<String> destinationKeystorePaths; - public MergerConfiguration(List<String> truststoreFilePaths, - List<String> truststoreFilePasswordPaths) { + public AppConfiguration(List<String> truststoreFilePaths, + List<String> truststoreFilePasswordPaths, List<String> sourceKeystorePaths, + List<String> destinationKeystorePaths) { this.truststoreFilePaths = List.copyOf(truststoreFilePaths); this.truststoreFilePasswordPaths = List.copyOf(truststoreFilePasswordPaths); + this.sourceKeystorePaths = List.copyOf(sourceKeystorePaths); + this.destinationKeystorePaths = List.copyOf(destinationKeystorePaths); } public List<String> getTruststoreFilePaths() { return Collections.unmodifiableList(truststoreFilePaths); } - public List<String> getTruststoreFilePasswordPaths() { return Collections.unmodifiableList(truststoreFilePasswordPaths); } + + public List<String> getDestinationKeystorePaths() { + return Collections.unmodifiableList(destinationKeystorePaths); + } + + public List<String> getSourceKeystorePaths() { + return Collections.unmodifiableList(sourceKeystorePaths); + } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/model/EnvVariable.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/model/EnvVariable.java new file mode 100644 index 00000000..42028521 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/model/EnvVariable.java @@ -0,0 +1,52 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.configuration.model; + +import static org.onap.oom.certservice.postprocessor.configuration.path.validation.ValidationFunctions.doesItContainValidCertificatesPaths; +import static org.onap.oom.certservice.postprocessor.configuration.path.validation.ValidationFunctions.doesItContainValidPasswordPaths; +import static org.onap.oom.certservice.postprocessor.configuration.path.validation.ValidationFunctions.doesItContainValidPathsToCopy; + +import java.util.List; +import java.util.function.Predicate; +import org.onap.oom.certservice.postprocessor.configuration.path.validation.ValidationFunctions; + +public enum EnvVariable { + TRUSTSTORES_PATHS(true, doesItContainValidCertificatesPaths()), + TRUSTSTORES_PASSWORDS_PATHS(true, doesItContainValidPasswordPaths()), + KEYSTORE_SOURCE_PATHS(false, doesItContainValidPathsToCopy()), + KEYSTORE_DESTINATION_PATHS(false, doesItContainValidPathsToCopy()); + + boolean isMandatory; + + Predicate<List<String>> validationFunction; + + EnvVariable(boolean isMandatory, Predicate<List<String>> validationFunction) { + this.isMandatory = isMandatory; + this.validationFunction = validationFunction; + } + + public boolean isMandatory() { + return isMandatory; + } + + public Predicate<List<String>> getValidationFunction() { + return validationFunction; + } +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/path/DelimitedPathsSplitter.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/path/DelimitedPathsSplitter.java new file mode 100644 index 00000000..b2e71cb3 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/path/DelimitedPathsSplitter.java @@ -0,0 +1,49 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.configuration.path; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import org.onap.oom.certservice.postprocessor.configuration.exception.CertificatesPathsValidationException; +import org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable; + +public class DelimitedPathsSplitter { + + private static final String DELIMITER = ":"; + private static final int NEGATIVE_SPLIT_LIMIT = -1; + + public List<String> getValidatedPaths(EnvVariable envVariable, Optional<String> envValue) + throws CertificatesPathsValidationException { + return envValue.filter(this::hasValue) + .map(this::splitToList) + .filter(envVariable.getValidationFunction()) + .orElseThrow(() -> new CertificatesPathsValidationException( + envVariable + " environment variable does not contain valid paths")); + } + + private boolean hasValue(String envValue) { + return !envValue.isEmpty(); + } + + private List<String> splitToList(String stringToSplit) { + return Arrays.asList(stringToSplit.split(DELIMITER, NEGATIVE_SPLIT_LIMIT)); + } +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/path/EnvProvider.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/path/env/EnvReader.java index a1998b86..f30e43be 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/path/EnvProvider.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/path/env/EnvReader.java @@ -17,20 +17,23 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.path; +package org.onap.oom.certservice.postprocessor.configuration.path.env; import java.util.Optional; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class EnvProvider { +public class EnvReader { + + private static final Logger LOGGER = LoggerFactory.getLogger(EnvReader.class); - private static final Logger LOGGER = LoggerFactory.getLogger(EnvProvider.class); + public Optional<String> getEnv(String name) { + return getSystemEnv(name); + } - Optional<String> getEnv(String name) { + Optional<String> getSystemEnv(String name) { String value = System.getenv(name); LOGGER.info("Read variable: {} , value: {}", name, value); - return Optional.ofNullable(System.getenv(name)); + return Optional.ofNullable(value); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/path/validation/ValidationFunctions.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/path/validation/ValidationFunctions.java new file mode 100644 index 00000000..f65a21a0 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/configuration/path/validation/ValidationFunctions.java @@ -0,0 +1,57 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.configuration.path.validation; + +import java.util.List; +import java.util.function.Predicate; + +public final class ValidationFunctions { + + private static final String CERTIFICATE_PATH_REGEX = "^(/[a-zA-Z0-9_-]+)+\\.(pem|jks|p12)"; + private static final String CERTIFICATE_PASSWORD_PATH_REGEX = "^(/[a-zA-Z0-9_-]+)+\\.pass"; + + private ValidationFunctions() { + } + + public static Predicate<List<String>> doesItContainValidPasswordPaths() { + return paths -> paths.stream().allMatch(ValidationFunctions::isCertificatePasswordPathValid); + } + + public static Predicate<List<String>> doesItContainValidCertificatesPaths() { + return paths -> paths.stream().allMatch(ValidationFunctions::isCertificatePathValid); + } + + public static Predicate<List<String>> doesItContainValidPathsToCopy() { + return paths -> paths.stream().allMatch(path -> + doesMatch(path, CERTIFICATE_PASSWORD_PATH_REGEX) || isCertificatePathValid(path)); + } + + private static boolean isCertificatePathValid(String path) { + return doesMatch(path, CERTIFICATE_PATH_REGEX); + } + + private static boolean isCertificatePasswordPathValid(String path) { + return path.isEmpty() || doesMatch(path, CERTIFICATE_PASSWORD_PATH_REGEX); + } + + private static boolean doesMatch(String path, String regex) { + return path.matches(regex); + } +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/copier/KeystoreCopier.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/copier/KeystoreCopier.java new file mode 100644 index 00000000..eba59fd6 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/copier/KeystoreCopier.java @@ -0,0 +1,74 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.copier; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import org.onap.oom.certservice.postprocessor.common.FileTools; +import org.onap.oom.certservice.postprocessor.configuration.model.AppConfiguration; +import org.onap.oom.certservice.postprocessor.copier.exception.KeystoreFileCopyException; +import org.onap.oom.certservice.postprocessor.copier.exception.KeystoreNotExistException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class KeystoreCopier { + + private static final Logger LOGGER = LoggerFactory.getLogger(KeystoreCopier.class); + private final FileTools fileTools; + + public KeystoreCopier(FileTools fileTools) { + this.fileTools = fileTools; + } + + public void copyKeystores(AppConfiguration configuration) { + final List<String> sources = configuration.getSourceKeystorePaths(); + final List<String> destinations = configuration.getDestinationKeystorePaths(); + containsPaths(sources); + try { + for (int i = 0; i < sources.size(); i++) { + copy(sources.get(i), destinations.get(i)); + } + } catch (IOException e) { + throw new KeystoreFileCopyException(e); + } + } + + private void containsPaths(List<String> sources) { + if (sources.size() == 0) { + LOGGER.info("No Keystore files to copy"); + } + } + + private void copy(String sourcePath, String destinationPath) throws IOException { + final File source = new File(sourcePath); + final File destination = new File(destinationPath); + + if (!source.exists()) { + throw new KeystoreNotExistException("Keystore file does not exist '" + source.getAbsolutePath() + "'!"); + } + + if (destination.exists()) { + fileTools.createBackup(destination); + } + fileTools.copy(source, destination); + } + +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/path/TruststoresPathsProviderException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/copier/exception/KeystoreFileCopyException.java index 1f69fe20..66190965 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/path/TruststoresPathsProviderException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/copier/exception/KeystoreFileCopyException.java @@ -17,14 +17,15 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.path; +package org.onap.oom.certservice.postprocessor.copier.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; -public class TruststoresPathsProviderException extends ExitableException { +public class KeystoreFileCopyException extends ExitableException { - TruststoresPathsProviderException(String message) { - super(message, ExitStatus.TRUSTSTORES_PATHS_PROVIDER_EXCEPTION); + public KeystoreFileCopyException(Exception e) { + super(e, ExitStatus.KEYSTORE_FILE_COPY_EXCEPTION); } + } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/copier/exception/KeystoreNotExistException.java index 54982f5f..37f2f537 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/copier/exception/KeystoreNotExistException.java @@ -17,14 +17,15 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.configuration; +package org.onap.oom.certservice.postprocessor.copier.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; -public class MergerConfigurationException extends ExitableException { +public class KeystoreNotExistException extends ExitableException { - MergerConfigurationException(String message) { - super(message, ExitStatus.MERGER_CONFIGURATION_EXCEPTION); + public KeystoreNotExistException(String message) { + super(message, ExitStatus.KEYSTORE_NOT_EXIST_EXCEPTION); } + } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/TruststoreFilesListProvider.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/TruststoreFilesProvider.java index 92e3c2a8..59800b13 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/TruststoreFilesListProvider.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/TruststoreFilesProvider.java @@ -17,37 +17,35 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file; - -import org.onap.oom.truststoremerger.certification.file.model.Truststore; +package org.onap.oom.certservice.postprocessor.merger; import java.util.ArrayList; import java.util.List; -import org.onap.oom.truststoremerger.certification.file.exception.KeystoreInstanceException; -import org.onap.oom.truststoremerger.certification.file.exception.LoadTruststoreException; -import org.onap.oom.truststoremerger.certification.file.exception.PasswordReaderException; -import org.onap.oom.truststoremerger.certification.file.exception.TruststoreFileFactoryException; +import org.onap.oom.certservice.postprocessor.merger.exception.KeystoreInstanceException; +import org.onap.oom.certservice.postprocessor.merger.exception.LoadTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.PasswordReaderException; +import org.onap.oom.certservice.postprocessor.merger.exception.TruststoreFileFactoryException; +import org.onap.oom.certservice.postprocessor.merger.model.Truststore; +import org.onap.oom.certservice.postprocessor.merger.model.TruststoreFactory; -public class TruststoreFilesListProvider { +public class TruststoreFilesProvider { - private final TruststoreFileFactory truststoreFileFactory; - public TruststoreFilesListProvider(TruststoreFileFactory truststoreFileFactory) { - this.truststoreFileFactory = truststoreFileFactory; + private TruststoreFilesProvider() { } - public List<Truststore> getTruststoreFilesList(List<String> truststoreFilePaths, + public static List<Truststore> getTruststoreFiles(List<String> truststoreFilePaths, List<String> truststoreFilePasswordPaths) throws LoadTruststoreException, PasswordReaderException, TruststoreFileFactoryException, KeystoreInstanceException { - List<Truststore> truststoreFilesList = new ArrayList<>(); + List<Truststore> truststoreFiles = new ArrayList<>(); for (int i = 0; i < truststoreFilePaths.size(); i++) { String truststorePath = truststoreFilePaths.get(i); String passwordPath = truststoreFilePasswordPaths.get(i); - Truststore truststore = truststoreFileFactory.create(truststorePath, passwordPath); - truststoreFilesList.add(truststore); + Truststore truststore = TruststoreFactory.create(truststorePath, passwordPath); + truststoreFiles.add(truststore); } - return truststoreFilesList; + return truststoreFiles; } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/TruststoreMerger.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/TruststoreMerger.java new file mode 100644 index 00000000..9bc3dd82 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/TruststoreMerger.java @@ -0,0 +1,55 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.merger; + +import java.util.List; +import org.onap.oom.certservice.postprocessor.api.ExitableException; +import org.onap.oom.certservice.postprocessor.configuration.model.AppConfiguration; +import org.onap.oom.certservice.postprocessor.merger.model.Truststore; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAlias; + +public class TruststoreMerger { + + private static final int FIRST_TRUSTSTORE_INDEX = 0; + private static final int SECOND_TRUSTSTORE_INDEX = 1; + + public void mergeTruststores(AppConfiguration configuration) throws ExitableException { + List<Truststore> truststoreFilesList = getTruststoreFiles(configuration); + + Truststore baseFile = truststoreFilesList.get(FIRST_TRUSTSTORE_INDEX); + baseFile.createBackup(); + + for (int i = SECOND_TRUSTSTORE_INDEX; i < truststoreFilesList.size(); i++) { + Truststore truststore = truststoreFilesList.get(i); + List<CertificateWithAlias> certificateWrappers = truststore.getCertificates(); + baseFile.addCertificates(certificateWrappers); + } + + baseFile.saveFile(); + } + + private List<Truststore> getTruststoreFiles(AppConfiguration configuration) throws ExitableException { + return TruststoreFilesProvider + .getTruststoreFiles( + configuration.getTruststoreFilePaths(), + configuration.getTruststoreFilePasswordPaths() + ); + } +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/AliasConflictException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/AliasConflictException.java index a4102d9f..2e7939b7 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/AliasConflictException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/AliasConflictException.java @@ -17,15 +17,15 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.exception; +package org.onap.oom.certservice.postprocessor.merger.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; public class AliasConflictException extends ExitableException { - public AliasConflictException(String message) { - super(message, ExitStatus.ALIAS_CONFLICT_EXCEPTION); + public AliasConflictException(String errorMessage) { + super(errorMessage, ExitStatus.ALIAS_CONFLICT_EXCEPTION); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/CreateBackupException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/CreateBackupException.java index a21f7013..8e99f993 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/CreateBackupException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/CreateBackupException.java @@ -17,14 +17,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.exception; +package org.onap.oom.certservice.postprocessor.merger.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; public class CreateBackupException extends ExitableException { - public CreateBackupException(Exception e) { - super(e, ExitStatus.CREATE_BACKUP_EXCEPTION); + public CreateBackupException(Exception cause) { + super(cause, ExitStatus.CREATE_BACKUP_EXCEPTION); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/KeystoreInstanceException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/KeystoreInstanceException.java index c5bcc3ca..1279dff7 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/KeystoreInstanceException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/KeystoreInstanceException.java @@ -17,14 +17,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.exception; +package org.onap.oom.certservice.postprocessor.merger.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; public class KeystoreInstanceException extends ExitableException { - public KeystoreInstanceException(Throwable e) { - super(e, ExitStatus.KEYSTORE_INSTANCE_EXCEPTION); + public KeystoreInstanceException(Exception cause) { + super(cause, ExitStatus.KEYSTORE_INSTANCE_EXCEPTION); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/LoadTruststoreException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/LoadTruststoreException.java index b8bb53fa..b3493fd6 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/LoadTruststoreException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/LoadTruststoreException.java @@ -17,14 +17,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.exception; +package org.onap.oom.certservice.postprocessor.merger.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; public class LoadTruststoreException extends ExitableException { - public LoadTruststoreException(Throwable e) { - super(e, ExitStatus.TRUSTSTORE_LOAD_FILE_EXCEPTION); + public LoadTruststoreException(Exception cause) { + super(cause, ExitStatus.TRUSTSTORE_LOAD_FILE_EXCEPTION); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/MissingTruststoreException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/MissingTruststoreException.java index c502d6b6..51660f60 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/MissingTruststoreException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/MissingTruststoreException.java @@ -17,14 +17,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.exception; +package org.onap.oom.certservice.postprocessor.merger.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; public class MissingTruststoreException extends ExitableException { - public MissingTruststoreException(String message) { - super(message, ExitStatus.MISSING_TRUSTSTORE_EXCEPTION); + public MissingTruststoreException(String errorMessage) { + super(errorMessage, ExitStatus.MISSING_TRUSTSTORE_EXCEPTION); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/PasswordReaderException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/PasswordReaderException.java index d601d229..b1bdf1ea 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/PasswordReaderException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/PasswordReaderException.java @@ -17,13 +17,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.exception; +package org.onap.oom.certservice.postprocessor.merger.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; public class PasswordReaderException extends ExitableException { - public PasswordReaderException(String message) { - super(message, ExitStatus.PASSWORD_READER_EXCEPTION); + public PasswordReaderException(String errorMessage) { + super(errorMessage, ExitStatus.PASSWORD_READER_EXCEPTION); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/TruststoreDataOperationException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/TruststoreDataOperationException.java index cf848f79..77ae366e 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/TruststoreDataOperationException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/TruststoreDataOperationException.java @@ -17,14 +17,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.exception; +package org.onap.oom.certservice.postprocessor.merger.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; public class TruststoreDataOperationException extends ExitableException { - public TruststoreDataOperationException(Exception e) { - super(e, ExitStatus.TRUSTSTORE_DATA_OPERATION_EXCEPTION); + public TruststoreDataOperationException(Exception cause) { + super(cause, ExitStatus.TRUSTSTORE_DATA_OPERATION_EXCEPTION); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/TruststoreFileFactoryException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/TruststoreFileFactoryException.java index 18349fd4..a87a62a3 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/TruststoreFileFactoryException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/TruststoreFileFactoryException.java @@ -17,14 +17,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.exception; +package org.onap.oom.certservice.postprocessor.merger.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; public class TruststoreFileFactoryException extends ExitableException { - public TruststoreFileFactoryException(String message) { - super(message, ExitStatus.TRUSTSTORE_FILE_FACTORY_EXCEPTION); + public TruststoreFileFactoryException(String errorMessage) { + super(errorMessage, ExitStatus.TRUSTSTORE_FILE_FACTORY_EXCEPTION); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/WriteTruststoreFileException.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/WriteTruststoreFileException.java index a5e02b3c..f9b772ca 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/exception/WriteTruststoreFileException.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/exception/WriteTruststoreFileException.java @@ -18,14 +18,14 @@ */ -package org.onap.oom.truststoremerger.certification.file.exception; +package org.onap.oom.certservice.postprocessor.merger.exception; -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; +import org.onap.oom.certservice.postprocessor.api.ExitStatus; +import org.onap.oom.certservice.postprocessor.api.ExitableException; public class WriteTruststoreFileException extends ExitableException { - public WriteTruststoreFileException(Exception e) { - super(e, ExitStatus.WRITE_TRUSTSTORE_FILE_EXCEPTION); + public WriteTruststoreFileException(Exception cause) { + super(cause, ExitStatus.WRITE_TRUSTSTORE_FILE_EXCEPTION); } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/JavaCertificateStoreController.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/JavaTruststore.java index 1c20fd38..d264d2f4 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/JavaCertificateStoreController.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/JavaTruststore.java @@ -17,7 +17,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider; +package org.onap.oom.certservice.postprocessor.merger.model; import java.io.File; import java.io.FileInputStream; @@ -27,35 +27,43 @@ import java.security.KeyStoreException; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAliasFactory; -import org.onap.oom.truststoremerger.certification.file.exception.AliasConflictException; -import org.onap.oom.truststoremerger.certification.file.exception.TruststoreDataOperationException; -import org.onap.oom.truststoremerger.certification.file.exception.LoadTruststoreException; -import org.onap.oom.truststoremerger.certification.file.exception.MissingTruststoreException; -import org.onap.oom.truststoremerger.certification.file.exception.WriteTruststoreFileException; +import org.onap.oom.certservice.postprocessor.merger.exception.AliasConflictException; +import org.onap.oom.certservice.postprocessor.merger.exception.LoadTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.MissingTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.TruststoreDataOperationException; +import org.onap.oom.certservice.postprocessor.merger.exception.WriteTruststoreFileException; +import org.onap.oom.certservice.postprocessor.api.ExitableException; +import org.onap.oom.certservice.postprocessor.common.FileTools; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAlias; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAliasFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class JavaCertificateStoreController implements CertificateController { +public final class JavaTruststore extends Truststore { - private static final Logger LOGGER = LoggerFactory.getLogger(JavaCertificateStoreController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(JavaTruststore.class); private final CertificateWithAliasFactory factory = new CertificateWithAliasFactory(); private final KeyStore keyStore; - private final File storeFile; private final String password; - public JavaCertificateStoreController(KeyStore keyStore, File storeFile, String password) { + private JavaTruststore(KeyStore keyStore, File storeFile, String password) { + super(storeFile, new FileTools()); this.keyStore = keyStore; - this.storeFile = storeFile; this.password = password; } - public List<CertificateWithAlias> getNotEmptyCertificateList() throws ExitableException { - List<String> aliases = getTruststoreAliasesList(); + public static JavaTruststore createWithLoadingFile(KeyStore keyStore, File storeFile, String password) + throws LoadTruststoreException { + JavaTruststore javaTruststore = new JavaTruststore(keyStore, storeFile, password); + javaTruststore.loadFile(); + return javaTruststore; + } + + public List<CertificateWithAlias> getCertificates() throws ExitableException { + LOGGER.debug("Attempt to read certificates from file: {}", storeFile.getPath()); + List<String> aliases = getTruststoreAliases(); if (aliases.isEmpty()) { throw new MissingTruststoreException("Missing certificate aliases in file: " + storeFile.getPath()); } @@ -64,7 +72,8 @@ public class JavaCertificateStoreController implements CertificateController { public void addCertificates(List<CertificateWithAlias> certificatesWithAliases) throws ExitableException { - if (getTruststoreAliasesList().isEmpty()){ + LOGGER.debug("Attempt to add certificates for saving to file"); + if (getTruststoreAliases().isEmpty()) { throw new MissingTruststoreException("Missing certificate aliases in file: " + storeFile.getPath()); } for (CertificateWithAlias certificate : certificatesWithAliases) { @@ -73,7 +82,8 @@ public class JavaCertificateStoreController implements CertificateController { } public void saveFile() throws WriteTruststoreFileException { - try (FileOutputStream outputStream = new FileOutputStream(this.storeFile)) { + LOGGER.debug("Attempt to save file: {}", storeFile.getPath()); + try (FileOutputStream outputStream = new FileOutputStream(storeFile)) { keyStore.store(outputStream, this.password.toCharArray()); } catch (Exception e) { LOGGER.error("Cannot write truststore file"); @@ -81,11 +91,11 @@ public class JavaCertificateStoreController implements CertificateController { } } - public void loadFile() throws LoadTruststoreException { + private void loadFile() throws LoadTruststoreException { try { - keyStore.load(new FileInputStream(this.storeFile), this.password.toCharArray()); + keyStore.load(new FileInputStream(storeFile), this.password.toCharArray()); } catch (Exception e) { - LOGGER.error("Cannot load file: {}", this.storeFile.getPath()); + LOGGER.error("Cannot load file: {}", storeFile.getPath()); throw new LoadTruststoreException(e); } } @@ -133,7 +143,7 @@ public class JavaCertificateStoreController implements CertificateController { } } - private List<String> getTruststoreAliasesList() throws TruststoreDataOperationException { + private List<String> getTruststoreAliases() throws TruststoreDataOperationException { try { List<String> aliases = Collections.list(keyStore.aliases()); return getFilteredAlias(aliases); diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/JavaTruststoreFactory.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/JavaTruststoreFactory.java new file mode 100644 index 00000000..c36510c6 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/JavaTruststoreFactory.java @@ -0,0 +1,51 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.merger.model; + +import java.io.File; +import java.security.KeyStore; +import java.security.KeyStoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.KeystoreInstanceException; +import org.onap.oom.certservice.postprocessor.merger.exception.LoadTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.PasswordReaderException; +import org.onap.oom.certservice.postprocessor.common.PasswordReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JavaTruststoreFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(JavaTruststoreFactory.class); + + private JavaTruststoreFactory() { + } + + public static Truststore create(File certFile, String truststorePasswordPath, String keystoreType) + throws LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { + String password = PasswordReader.readPassword(new File(truststorePasswordPath)); + try { + return JavaTruststore + .createWithLoadingFile(KeyStore.getInstance(keystoreType), certFile, password); + } catch (KeyStoreException e) { + LOGGER.error("Cannot initialize Java Keystore instance"); + throw new KeystoreInstanceException(e); + } + } +} + diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/PemCertificateController.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/PemTruststore.java index 9ff42b87..d7f4bfd2 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/PemCertificateController.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/PemTruststore.java @@ -17,10 +17,10 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider; +package org.onap.oom.certservice.postprocessor.merger.model; -import static org.onap.oom.truststoremerger.api.CertificateConstants.BOUNCY_CASTLE_PROVIDER; -import static org.onap.oom.truststoremerger.api.CertificateConstants.X_509_CERTIFICATE; +import static org.onap.oom.certservice.postprocessor.api.CertificateConstants.BOUNCY_CASTLE_PROVIDER; +import static org.onap.oom.certservice.postprocessor.api.CertificateConstants.X_509_CERTIFICATE; import java.io.File; import java.io.FileInputStream; @@ -37,30 +37,31 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator; import org.bouncycastle.util.io.pem.PemObjectGenerator; import org.bouncycastle.util.io.pem.PemWriter; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAliasFactory; -import org.onap.oom.truststoremerger.certification.file.exception.MissingTruststoreException; -import org.onap.oom.truststoremerger.certification.file.exception.TruststoreDataOperationException; -import org.onap.oom.truststoremerger.certification.file.exception.WriteTruststoreFileException; +import org.onap.oom.certservice.postprocessor.merger.exception.MissingTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.TruststoreDataOperationException; +import org.onap.oom.certservice.postprocessor.merger.exception.WriteTruststoreFileException; +import org.onap.oom.certservice.postprocessor.common.FileTools; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAlias; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAliasFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class PemCertificateController implements CertificateController { +public class PemTruststore extends Truststore { - private static final Logger LOGGER = LoggerFactory.getLogger(PemCertificateController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PemTruststore.class); private static final boolean APPEND_TO_FILE = true; private final CertificateWithAliasFactory factory = new CertificateWithAliasFactory(); private final List<CertificateWithAlias> certificatesToBeSaved = new ArrayList<>(); - private final File file; - public PemCertificateController(File file) { - this.file = file; + public PemTruststore(File storeFile) { + super(storeFile, new FileTools()); } - public List<CertificateWithAlias> getNotEmptyCertificateList() + public List<CertificateWithAlias> getCertificates() throws TruststoreDataOperationException, MissingTruststoreException { + LOGGER.debug("Attempt to read certificates from file: {}", storeFile.getPath()); if (isFileWithoutPemCertificate()) { throw new MissingTruststoreException("File does not contain any certificate"); } @@ -70,14 +71,16 @@ public class PemCertificateController implements CertificateController { public void addCertificates(List<CertificateWithAlias> certificates) throws TruststoreDataOperationException, MissingTruststoreException { + LOGGER.debug("Attempt to add certificates for saving to file"); if (isFileWithoutPemCertificate()) { - LOGGER.error("File does not contain any certificate. File path: {} ", this.file.getPath()); + LOGGER.error("File does not contain any certificate. File path: {} ", storeFile.getPath()); throw new MissingTruststoreException("File does not contain any certificate"); } certificatesToBeSaved.addAll(certificates); } public void saveFile() throws WriteTruststoreFileException, TruststoreDataOperationException { + LOGGER.debug("Attempt to save file: {}", storeFile.getPath()); List<Certificate> certificates = certificatesToBeSaved.stream() .map(CertificateWithAlias::getCertificate) .collect(Collectors.toList()); @@ -104,19 +107,17 @@ public class PemCertificateController implements CertificateController { return sw.toString(); } - private List<Certificate> extractCertificatesFromFile() throws TruststoreDataOperationException { - try (FileInputStream inputStream = new FileInputStream(this.file)) { + try (FileInputStream inputStream = new FileInputStream(storeFile)) { Security.addProvider(new BouncyCastleProvider()); CertificateFactory factory = CertificateFactory.getInstance(X_509_CERTIFICATE, BOUNCY_CASTLE_PROVIDER); return new ArrayList<>(factory.generateCertificates(inputStream)); } catch (Exception e) { - LOGGER.error("Cannot read certificates from file: {}", this.file.getPath()); + LOGGER.error("Cannot read certificates from file: {}", storeFile.getPath()); throw new TruststoreDataOperationException(e); } } - private List<PemObjectGenerator> transformToPemGenerators(List<Certificate> certificates) throws TruststoreDataOperationException { List<PemObjectGenerator> generators = new ArrayList<>(); @@ -145,7 +146,7 @@ public class PemCertificateController implements CertificateController { private void appendToFile(String certificatesAsString) throws WriteTruststoreFileException { try { - FileOutputStream fileOutputStream = new FileOutputStream(this.file, APPEND_TO_FILE); + FileOutputStream fileOutputStream = new FileOutputStream(storeFile, APPEND_TO_FILE); fileOutputStream.write(certificatesAsString.getBytes()); } catch (Exception e) { LOGGER.error("Cannot write certificates to file"); diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/model/Truststore.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/Truststore.java index 153805a7..51722d0e 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/model/Truststore.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/Truststore.java @@ -17,46 +17,33 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.model; +package org.onap.oom.certservice.postprocessor.merger.model; import java.io.File; -import java.io.FileOutputStream; -import java.nio.file.Files; import java.util.List; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.exception.CreateBackupException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.onap.oom.certservice.postprocessor.merger.exception.CreateBackupException; +import org.onap.oom.certservice.postprocessor.api.ExitableException; +import org.onap.oom.certservice.postprocessor.common.FileTools; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAlias; public abstract class Truststore { - private static final Logger LOGGER = LoggerFactory.getLogger(Truststore.class); - private static final String BACKUP_EXTENSION = ".bak"; - private final File file; + final File storeFile; - Truststore(File file) { - this.file = file; + private final FileTools fileTools; + + public Truststore(File storeFile, FileTools fileTools) { + this.storeFile = storeFile; + this.fileTools = fileTools; + } + + public void createBackup() throws CreateBackupException { + fileTools.createBackup(storeFile); } public abstract List<CertificateWithAlias> getCertificates() throws ExitableException; - public abstract void addCertificate(List<CertificateWithAlias> certificates) throws ExitableException; + public abstract void addCertificates(List<CertificateWithAlias> certificates) throws ExitableException; public abstract void saveFile() throws ExitableException; - - public File getFile() { - return file; - } - - public void createBackup() throws CreateBackupException { - LOGGER.debug("Create backup of file: {}", file.getPath()); - String backupFilePath = file.getAbsolutePath() + BACKUP_EXTENSION; - try (FileOutputStream fileOutputStream = new FileOutputStream(backupFilePath)) { - Files.copy(file.toPath(), fileOutputStream); - } catch (Exception e) { - LOGGER.error("Cannot create backup of file: {} ", getFile().getPath()); - throw new CreateBackupException(e); - } - } } diff --git a/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/TruststoreFactory.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/TruststoreFactory.java new file mode 100644 index 00000000..b6984f36 --- /dev/null +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/TruststoreFactory.java @@ -0,0 +1,69 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.merger.model; + +import static org.onap.oom.certservice.postprocessor.api.CertificateConstants.JKS_TYPE; +import static org.onap.oom.certservice.postprocessor.api.CertificateConstants.PKCS12_TYPE; + +import java.io.File; +import org.onap.oom.certservice.postprocessor.merger.exception.KeystoreInstanceException; +import org.onap.oom.certservice.postprocessor.merger.exception.LoadTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.PasswordReaderException; +import org.onap.oom.certservice.postprocessor.common.ExtensionResolver; +import org.onap.oom.certservice.postprocessor.merger.exception.TruststoreFileFactoryException; + +public class TruststoreFactory { + + private static final String JKS_EXTENSION = ".jks"; + private static final String P12_EXTENSION = ".p12"; + private static final String PEM_EXTENSION = ".pem"; + private static final String FILE_DOES_NOT_EXIST_MSG_TEMPLATE = "File: %s does not exist"; + private static final String UNKNOWN_TRUSTSTORE_TYPE_MSG_TEMPLATE = "Unknown truststore extension type: %s"; + + + private TruststoreFactory() { + } + + public static Truststore create(String truststoreFilePath, String truststorePasswordPath) + throws TruststoreFileFactoryException, PasswordReaderException, KeystoreInstanceException, LoadTruststoreException { + File truststoreFile = new File(truststoreFilePath); + if (!ExtensionResolver.checkIfFileExists(truststoreFile)) { + throw new TruststoreFileFactoryException(String.format(FILE_DOES_NOT_EXIST_MSG_TEMPLATE, truststoreFile)); + } + return createTypedTruststore(truststoreFile, truststorePasswordPath); + } + + private static Truststore createTypedTruststore(File truststoreFile, String truststorePasswordPath) + throws KeystoreInstanceException, PasswordReaderException, LoadTruststoreException, TruststoreFileFactoryException { + String extension = ExtensionResolver.get(truststoreFile); + switch (extension) { + case JKS_EXTENSION: + return JavaTruststoreFactory.create(truststoreFile, truststorePasswordPath, JKS_TYPE); + case P12_EXTENSION: + return JavaTruststoreFactory.create(truststoreFile, truststorePasswordPath, PKCS12_TYPE); + case PEM_EXTENSION: + return new PemTruststore(truststoreFile); + default: + throw new TruststoreFileFactoryException( + String.format(UNKNOWN_TRUSTSTORE_TYPE_MSG_TEMPLATE, extension)); + } + } + +} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/entry/CertificateWithAlias.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/certificate/CertificateWithAlias.java index decc3977..098ffcd0 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/entry/CertificateWithAlias.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/certificate/CertificateWithAlias.java @@ -17,7 +17,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider.entry; +package org.onap.oom.certservice.postprocessor.merger.model.certificate; import java.security.cert.Certificate; diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/entry/CertificateWithAliasFactory.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/certificate/CertificateWithAliasFactory.java index 0889650e..4ad2b417 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/entry/CertificateWithAliasFactory.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/certificate/CertificateWithAliasFactory.java @@ -17,7 +17,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider.entry; +package org.onap.oom.certservice.postprocessor.merger.model.certificate; import java.security.cert.Certificate; diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/entry/PemAliasGenerator.java b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/certificate/PemAliasGenerator.java index 56faa1f6..a89b1031 100644 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/entry/PemAliasGenerator.java +++ b/trustStoreMerger/src/main/java/org/onap/oom/certservice/postprocessor/merger/model/certificate/PemAliasGenerator.java @@ -17,7 +17,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider.entry; +package org.onap.oom.certservice.postprocessor.merger.model.certificate; import java.util.concurrent.atomic.AtomicInteger; diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/TrustStoreMerger.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/TrustStoreMerger.java deleted file mode 100644 index c8cc84df..00000000 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/TrustStoreMerger.java +++ /dev/null @@ -1,95 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger; - -import org.onap.oom.truststoremerger.api.ExitStatus; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.model.Truststore; -import org.onap.oom.truststoremerger.certification.file.provider.FileManager; -import org.onap.oom.truststoremerger.certification.file.provider.PasswordReader; -import org.onap.oom.truststoremerger.certification.file.TruststoreFileFactory; -import org.onap.oom.truststoremerger.certification.file.TruststoreFilesListProvider; -import org.onap.oom.truststoremerger.certification.path.EnvProvider; -import org.onap.oom.truststoremerger.certification.path.TruststoresPathsProvider; -import org.onap.oom.truststoremerger.configuration.MergerConfiguration; -import org.onap.oom.truststoremerger.configuration.MergerConfigurationFactory; -import org.onap.oom.truststoremerger.certification.path.PathValidator; - -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -class TrustStoreMerger { - - private static final Logger LOGGER = LoggerFactory.getLogger(TrustStoreMerger.class); - private static final int FIRST_TRUSTSTORE_INDEX = 0; - private static final int SECOND_TRUSTSTORE_INDEX = 1; - - private final AppExitHandler appExitHandler; - - TrustStoreMerger(AppExitHandler appExitHandler) { - this.appExitHandler = appExitHandler; - } - - void run() { - try { - mergeTruststores(); - appExitHandler.exit(ExitStatus.SUCCESS); - } catch (ExitableException e) { - LOGGER.error("Truststore Merger fails in execution: ", e); - appExitHandler.exit(e.applicationExitStatus()); - } - } - - private void mergeTruststores() throws ExitableException { - MergerConfiguration configuration = loadConfiguration(); - List<Truststore> truststoreFilesList = getTruststoreFilesList(configuration); - - Truststore baseFile = truststoreFilesList.get(FIRST_TRUSTSTORE_INDEX); - baseFile.createBackup(); - - for (int i = SECOND_TRUSTSTORE_INDEX; i < truststoreFilesList.size(); i++) { - List<CertificateWithAlias> certificateWrappers = truststoreFilesList.get(i).getCertificates(); - baseFile.addCertificate(certificateWrappers); - } - - baseFile.saveFile(); - } - - private MergerConfiguration loadConfiguration() throws ExitableException { - TruststoresPathsProvider truststoresPathsProvider = new TruststoresPathsProvider(new EnvProvider(), - new PathValidator()); - MergerConfigurationFactory factory = new MergerConfigurationFactory(truststoresPathsProvider); - return factory.createConfiguration(); - } - - private List<Truststore> getTruststoreFilesList(MergerConfiguration configuration) throws ExitableException { - TruststoreFileFactory truststoreFileFactory = new TruststoreFileFactory(new FileManager(), - new PasswordReader()); - TruststoreFilesListProvider truststoreFilesListProvider = new TruststoreFilesListProvider( - truststoreFileFactory); - return truststoreFilesListProvider - .getTruststoreFilesList( - configuration.getTruststoreFilePaths(), - configuration.getTruststoreFilePasswordPaths() - ); - } -} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/TruststoreFileFactory.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/TruststoreFileFactory.java deleted file mode 100644 index d93409b6..00000000 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/TruststoreFileFactory.java +++ /dev/null @@ -1,99 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file; - -import org.onap.oom.truststoremerger.certification.file.model.JavaTruststore; -import org.onap.oom.truststoremerger.certification.file.model.PemTruststore; -import org.onap.oom.truststoremerger.certification.file.model.Truststore; - -import java.io.File; -import org.onap.oom.truststoremerger.certification.file.exception.KeystoreInstanceException; -import org.onap.oom.truststoremerger.certification.file.exception.LoadTruststoreException; -import org.onap.oom.truststoremerger.certification.file.exception.PasswordReaderException; -import org.onap.oom.truststoremerger.certification.file.exception.TruststoreFileFactoryException; -import org.onap.oom.truststoremerger.certification.file.provider.CertificateStoreControllerFactory; -import org.onap.oom.truststoremerger.certification.file.provider.FileManager; -import org.onap.oom.truststoremerger.certification.file.provider.JavaCertificateStoreController; -import org.onap.oom.truststoremerger.certification.file.provider.PasswordReader; -import org.onap.oom.truststoremerger.certification.file.provider.PemCertificateController; - -public class TruststoreFileFactory { - - private static final String JKS_EXTENSION = ".jks"; - private static final String P12_EXTENSION = ".p12"; - private static final String PEM_EXTENSION = ".pem"; - private static final String FILE_DOES_NOT_EXIST_MSG_TEMPLATE = "File: %s does not exist"; - private static final String UNKNOWN_TRUSTSTORE_TYPE_MSG_TEMPLATE = "Unknown truststore extension type: %s"; - - private final FileManager fileManager; - private final PasswordReader passwordReader; - private final CertificateStoreControllerFactory certificateStoreControllerFactory = - new CertificateStoreControllerFactory(); - - public TruststoreFileFactory(FileManager fileManager, PasswordReader passwordReader) { - this.fileManager = fileManager; - this.passwordReader = passwordReader; - } - - public Truststore create(String truststoreFilePath, String truststorePasswordPath) - throws TruststoreFileFactoryException, PasswordReaderException, KeystoreInstanceException, LoadTruststoreException { - File truststoreFile = new File(truststoreFilePath); - if (!fileManager.checkIfFileExists(truststoreFile)) { - throw new TruststoreFileFactoryException(String.format(FILE_DOES_NOT_EXIST_MSG_TEMPLATE, truststoreFile)); - } - return createTypedTruststore(truststoreFile, truststorePasswordPath); - } - - private Truststore createTypedTruststore(File truststoreFile, String truststorePasswordPath) - throws KeystoreInstanceException, PasswordReaderException, LoadTruststoreException, TruststoreFileFactoryException { - String extension = fileManager.getExtension(truststoreFile); - switch (extension) { - case JKS_EXTENSION: - return createJksTruststore(truststoreFile, truststorePasswordPath); - case P12_EXTENSION: - return createP12Truststore(truststoreFile, truststorePasswordPath); - case PEM_EXTENSION: - return createPemTruststore(truststoreFile); - default: - throw new TruststoreFileFactoryException( - String.format(UNKNOWN_TRUSTSTORE_TYPE_MSG_TEMPLATE, extension)); - } - } - - private JavaTruststore createJksTruststore(File truststoreFile, String truststorePasswordPath) - throws PasswordReaderException, LoadTruststoreException, KeystoreInstanceException { - String password = passwordReader.readPassword(new File(truststorePasswordPath)); - JavaCertificateStoreController storeController = certificateStoreControllerFactory - .createLoadedJksCertificateStoreController(truststoreFile, password); - return new JavaTruststore(truststoreFile, storeController); - } - - private JavaTruststore createP12Truststore(File truststoreFile, String truststorePasswordPath) - throws LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { - String password = passwordReader.readPassword(new File(truststorePasswordPath)); - JavaCertificateStoreController storeController = certificateStoreControllerFactory - .createLoadedPkcs12CertificateStoreController(truststoreFile, password); - return new JavaTruststore(truststoreFile, storeController); - } - - private PemTruststore createPemTruststore(File truststoreFile) { - return new PemTruststore(truststoreFile, new PemCertificateController(truststoreFile)); - } -} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/model/JavaTruststore.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/model/JavaTruststore.java deleted file mode 100644 index d46fba1e..00000000 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/model/JavaTruststore.java +++ /dev/null @@ -1,58 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file.model; - -import java.io.File; -import java.util.List; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.exception.WriteTruststoreFileException; -import org.onap.oom.truststoremerger.certification.file.provider.JavaCertificateStoreController; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class JavaTruststore extends Truststore { - - private static final Logger LOGGER = LoggerFactory.getLogger(JavaTruststore.class); - private final JavaCertificateStoreController storeController; - - public JavaTruststore(File truststoreFile, JavaCertificateStoreController storeController) { - super(truststoreFile); - this.storeController = storeController; - } - - @Override - public List<CertificateWithAlias> getCertificates() throws ExitableException { - LOGGER.debug("Attempt ro read certificates from file: {} ", this.getFile().getPath()); - return storeController.getNotEmptyCertificateList(); - } - - @Override - public void addCertificate(List<CertificateWithAlias> certificates) throws ExitableException { - LOGGER.debug("Attempt to add certificates for saving to file"); - storeController.addCertificates(certificates); - } - - @Override - public void saveFile() throws WriteTruststoreFileException { - LOGGER.debug("Attempt to save file: {}", this.getFile().getPath()); - storeController.saveFile(); - } -} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/model/PemTruststore.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/model/PemTruststore.java deleted file mode 100644 index 36195267..00000000 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/model/PemTruststore.java +++ /dev/null @@ -1,58 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file.model; - -import java.io.File; -import java.util.List; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.provider.PemCertificateController; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PemTruststore extends Truststore { - - private static final Logger LOGGER = LoggerFactory.getLogger(PemTruststore.class); - private final PemCertificateController pemCertificateController; - - public PemTruststore(File truststoreFile, PemCertificateController pemCertificateController) { - super(truststoreFile); - this.pemCertificateController = pemCertificateController; - } - - @Override - public List<CertificateWithAlias> getCertificates() throws ExitableException { - LOGGER.debug("Attempt ro read certificates from file: {}", this.getFile().getPath()); - return pemCertificateController.getNotEmptyCertificateList(); - } - - @Override - public void addCertificate(List<CertificateWithAlias> certificates) throws ExitableException { - LOGGER.debug("Attempt to add certificates for saving to file"); - pemCertificateController.addCertificates(certificates); - } - - @Override - public void saveFile() throws ExitableException { - LOGGER.debug("Attempt to save file: {}", this.getFile().getPath()); - pemCertificateController.saveFile(); - } - -} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/CertificateController.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/CertificateController.java deleted file mode 100644 index f2ed2c45..00000000 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/CertificateController.java +++ /dev/null @@ -1,33 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file.provider; - -import java.util.List; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; - -public interface CertificateController { - - List<CertificateWithAlias> getNotEmptyCertificateList() throws ExitableException; - - void addCertificates(List<CertificateWithAlias> certificates) throws ExitableException; - - void saveFile() throws ExitableException; -} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/CertificateStoreControllerFactory.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/CertificateStoreControllerFactory.java deleted file mode 100644 index 66e2aed2..00000000 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/file/provider/CertificateStoreControllerFactory.java +++ /dev/null @@ -1,61 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file.provider; - -import static org.onap.oom.truststoremerger.api.CertificateConstants.JKS_INSTANCE; -import static org.onap.oom.truststoremerger.api.CertificateConstants.PKCS12_INSTANCE; - -import java.io.File; -import java.security.KeyStore; -import java.security.KeyStoreException; -import org.onap.oom.truststoremerger.certification.file.exception.KeystoreInstanceException; -import org.onap.oom.truststoremerger.certification.file.exception.LoadTruststoreException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CertificateStoreControllerFactory { - - private static final Logger LOGGER = LoggerFactory.getLogger(CertificateStoreControllerFactory.class); - - public JavaCertificateStoreController createLoadedJksCertificateStoreController(File certFile, String certPassword) - throws LoadTruststoreException, KeystoreInstanceException { - return createLoadedCertificateStoreController(certFile, certPassword, JKS_INSTANCE); - } - - public JavaCertificateStoreController createLoadedPkcs12CertificateStoreController(File certFile, String certPassword) - throws KeystoreInstanceException, LoadTruststoreException { - return createLoadedCertificateStoreController(certFile, certPassword, PKCS12_INSTANCE); - } - - private JavaCertificateStoreController createLoadedCertificateStoreController(File certFile, String certPassword, - String instanceType) - throws LoadTruststoreException, KeystoreInstanceException { - try { - JavaCertificateStoreController javaCertificateStoreController = new JavaCertificateStoreController( - KeyStore.getInstance(instanceType), certFile, certPassword); - javaCertificateStoreController.loadFile(); - return javaCertificateStoreController; - } catch (KeyStoreException e) { - LOGGER.error("Cannot initialize Java Keystore instance"); - throw new KeystoreInstanceException(e); - } - } -} - diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/path/TruststoresPathsProvider.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/path/TruststoresPathsProvider.java deleted file mode 100644 index 9d86a8b9..00000000 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/certification/path/TruststoresPathsProvider.java +++ /dev/null @@ -1,72 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.path; - -import static org.onap.oom.truststoremerger.api.ConfigurationEnvs.TRUSTSTORES_PATHS_ENV; -import static org.onap.oom.truststoremerger.api.ConfigurationEnvs.TRUSTSTORES_PASSWORDS_PATHS_ENV; - -import java.util.Arrays; -import java.util.List; -import java.util.function.Predicate; - -public class TruststoresPathsProvider { - - private static final String DELIMITER = ":"; - private static final int NEGATIVE_SPLIT_LIMIT = -1; - - private final EnvProvider envProvider; - private final PathValidator pathValidator; - - public TruststoresPathsProvider(EnvProvider envProvider, PathValidator pathValidator) { - this.envProvider = envProvider; - this.pathValidator = pathValidator; - } - - public List<String> getTruststores() throws TruststoresPathsProviderException { - return envProvider.getEnv(TRUSTSTORES_PATHS_ENV) - .filter(Predicate.not(String::isEmpty)) - .map(this::splitToList) - .filter(this::validateTruststores) - .orElseThrow(() -> new TruststoresPathsProviderException( - TRUSTSTORES_PATHS_ENV + " environment variable does not contain valid truststores paths")); - } - - public List<String> getTruststoresPasswords() throws TruststoresPathsProviderException { - return envProvider.getEnv(TRUSTSTORES_PASSWORDS_PATHS_ENV) - .map(this::splitToList) - .filter(this::validateTruststoresPasswords) - .orElseThrow(() -> new TruststoresPathsProviderException( - TRUSTSTORES_PASSWORDS_PATHS_ENV + " environment variable does not contain valid passwords paths")); - } - - private boolean validateTruststores(List<String> truststores) { - return truststores.stream() - .allMatch(pathValidator::isTruststorePathValid); - } - - private boolean validateTruststoresPasswords(List<String> truststoresPasswords) { - return truststoresPasswords.stream() - .allMatch(pathValidator::isTruststorePasswordPathValid); - } - - private List<String> splitToList(String stringToSplit) { - return Arrays.asList(stringToSplit.split(DELIMITER, NEGATIVE_SPLIT_LIMIT)); - } -} diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationFactory.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationFactory.java deleted file mode 100644 index acd9a840..00000000 --- a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationFactory.java +++ /dev/null @@ -1,51 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.configuration; - -import org.onap.oom.truststoremerger.certification.path.TruststoresPathsProvider; -import org.onap.oom.truststoremerger.certification.path.TruststoresPathsProviderException; - -import static org.onap.oom.truststoremerger.api.ConfigurationEnvs.TRUSTSTORES_PATHS_ENV; -import static org.onap.oom.truststoremerger.api.ConfigurationEnvs.TRUSTSTORES_PASSWORDS_PATHS_ENV; - -import java.util.List; - -public class MergerConfigurationFactory { - - private final TruststoresPathsProvider pathsProvider; - - public MergerConfigurationFactory(TruststoresPathsProvider pathsProvider) { - this.pathsProvider = pathsProvider; - } - - public MergerConfiguration createConfiguration() - throws MergerConfigurationException, TruststoresPathsProviderException { - List<String> truststores = pathsProvider.getTruststores(); - List<String> truststoresPasswords = pathsProvider.getTruststoresPasswords(); - - if (truststores.size() != truststoresPasswords.size()) { - throw new MergerConfigurationException( - "Size of " + TRUSTSTORES_PATHS_ENV - + " does not match size of " + TRUSTSTORES_PASSWORDS_PATHS_ENV + " environment variables"); - } - - return new MergerConfiguration(truststores, truststoresPasswords); - } -} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/AppExecutorTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/AppExecutorTest.java new file mode 100644 index 00000000..5c79f6e9 --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/AppExecutorTest.java @@ -0,0 +1,76 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor; + +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.onap.oom.certservice.postprocessor.api.ExitStatus.ALIAS_CONFLICT_EXCEPTION; +import static org.onap.oom.certservice.postprocessor.api.ExitStatus.SUCCESS; +import static org.onap.oom.certservice.postprocessor.api.ExitStatus.UNEXPECTED_EXCEPTION; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.oom.certservice.postprocessor.merger.exception.AliasConflictException; + +@ExtendWith(MockitoExtension.class) +public class AppExecutorTest { + + @Mock + Runnable logic; + @Mock + AppExitHandler exitHandler; + @InjectMocks + AppExecutor executor = new AppExecutor(); + + @Test + void shouldExitWithUnexpectedException() { + doThrow(new NullPointerException()).when(logic).run(); + doNothing().when(exitHandler).exit(UNEXPECTED_EXCEPTION); + + executor.execute(logic); + + verify(exitHandler).exit(UNEXPECTED_EXCEPTION); + } + + @Test + void shouldExitWithKnownException() { + doThrow(new AliasConflictException("")).when(logic).run(); + doNothing().when(exitHandler).exit(ALIAS_CONFLICT_EXCEPTION); + + executor.execute(logic); + + verify(exitHandler).exit(ALIAS_CONFLICT_EXCEPTION); + } + + @Test + void shouldExitWithSuccess() { + doNothing().when(logic).run(); + doNothing().when(exitHandler).exit(SUCCESS); + + executor.execute(logic); + + verify(exitHandler).exit(SUCCESS); + } +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/FileManagerTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/common/ExtensionResolverTest.java index c649ba68..8450ab6d 100644 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/FileManagerTest.java +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/common/ExtensionResolverTest.java @@ -17,8 +17,7 @@ * ============LICENSE_END========================================================= */ - -package org.onap.oom.truststoremerger.certification.file.provider; +package org.onap.oom.certservice.postprocessor.common; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -27,9 +26,7 @@ import java.io.File; import static org.assertj.core.api.Assertions.assertThat; -class FileManagerTest { - - private FileManager fileManager = new FileManager(); +class ExtensionResolverTest { @ParameterizedTest @CsvSource(value = { @@ -40,7 +37,7 @@ class FileManagerTest { "opt/app/truststore:''", }, delimiter = ':') void shouldReturnCorrectExtension(String filePath, String expectedExtension) { - String extension = fileManager.getExtension(new File(filePath)); + String extension = ExtensionResolver.get(new File(filePath)); assertThat(extension).isEqualTo(expectedExtension); } diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/common/FileToolsTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/common/FileToolsTest.java new file mode 100644 index 00000000..56f76e17 --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/common/FileToolsTest.java @@ -0,0 +1,71 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.common; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import org.apache.commons.io.FileUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class FileToolsTest { + + public static final String BAK_EXTENSION = ".bak"; + + @TempDir + File dir; + + @Test + void shouldCreateBackupProvidedFile() throws Exception { + //given + File fileToBackup = createFile("truststore.pem", "arbitrary content"); + String backupFilePath = fileToBackup.getPath() + BAK_EXTENSION; + //when + new FileTools().createBackup(fileToBackup); + //then + assertThat(fileToBackup.equals(new File(backupFilePath))); + } + + @Test + void shouldCopyFile() throws IOException { + //given + File sourceFile = createFile("source.p12", "any content"); + File destinationFile = new File(dir.getAbsolutePath() + "destination.p12"); + //when + new FileTools().copy(sourceFile, destinationFile); + //then + assertThat(sourceFile.equals(destinationFile)); + } + + + private File createFile(String name, String content) throws IOException { + File file = new File(dir.getAbsolutePath() + File.pathSeparator + name); + if (file.createNewFile()) { + FileUtils.write(file, content, Charset.defaultCharset()); + } else { + throw new IllegalStateException("File could not be created: " + file.getAbsolutePath()); + } + return file; + } + +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/PasswordReaderTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/common/PasswordReaderTest.java index 40eda4dd..697eaa83 100644 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/PasswordReaderTest.java +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/common/PasswordReaderTest.java @@ -17,12 +17,12 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider; +package org.onap.oom.certservice.postprocessor.common; import org.junit.jupiter.api.Test; import java.io.File; -import org.onap.oom.truststoremerger.certification.file.exception.PasswordReaderException; +import org.onap.oom.certservice.postprocessor.merger.exception.PasswordReaderException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -31,15 +31,13 @@ class PasswordReaderTest { @Test void shouldReturnCorrectPasswordFromFile() throws PasswordReaderException { - PasswordReader passwordReader = new PasswordReader(); - String fileData = passwordReader.readPassword(new File("src/test/resources/truststore-jks.pass")); + String fileData = PasswordReader.readPassword(new File("src/test/resources/truststore-jks.pass")); assertThat(fileData).isEqualTo("EOyuFbuYDyq_EhpboM72RHua"); } @Test void shouldThrowExceptionForNonExistingFile() { - PasswordReader passwordReader = new PasswordReader(); assertThatExceptionOfType(PasswordReaderException.class) - .isThrownBy(() -> passwordReader.readPassword(new File("src/test/resources/non-esisting-file.pass"))); + .isThrownBy(() -> PasswordReader.readPassword(new File("src/test/resources/non-esisting-file.pass"))); } } diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/AppConfigurationProviderTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/AppConfigurationProviderTest.java new file mode 100644 index 00000000..24e2dab8 --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/AppConfigurationProviderTest.java @@ -0,0 +1,141 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.configuration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.when; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.KEYSTORE_DESTINATION_PATHS; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.KEYSTORE_SOURCE_PATHS; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.TRUSTSTORES_PASSWORDS_PATHS; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.TRUSTSTORES_PATHS; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.oom.certservice.postprocessor.configuration.exception.CertificatesPathsValidationException; +import org.onap.oom.certservice.postprocessor.configuration.exception.ConfigurationException; +import org.onap.oom.certservice.postprocessor.configuration.model.AppConfiguration; +import org.onap.oom.certservice.postprocessor.configuration.path.DelimitedPathsSplitter; +import org.onap.oom.certservice.postprocessor.configuration.path.env.EnvReader; + +@ExtendWith(MockitoExtension.class) +class AppConfigurationProviderTest { + + private static final String BASE_TRUSTSTORE_PATH = "/opt/app/truststore_"; + private static final String JKS_EXTENSION = ".jks"; + private static final String PASS_EXTENSION = ".pass"; + private static final String SAMPLE_TRUSTSTORES_PATHS = "/opt/app/certificates/truststore.jks:/opt/app/certificates/truststore.pem"; + private static final String SAMPLE_TRUSTSTORES_PASSWORDS_PATHS = "/opt/app/certificates/truststore.pass:/trust.pass"; + + @Mock + private DelimitedPathsSplitter pathsSplitter; + @Mock + private EnvReader envReader; + private AppConfigurationProvider provider; + + @BeforeEach + void setUp() { + provider = new AppConfigurationProvider(pathsSplitter, envReader); + } + + @Test + void shouldThrowExceptionWhenMandatoryEnvNotPresent() { + // given + when(envReader.getEnv(TRUSTSTORES_PATHS.name())).thenReturn(Optional.empty()); + // when, then + assertThatExceptionOfType(ConfigurationException.class).isThrownBy(() -> provider.createConfiguration()) + .withMessageContaining(TRUSTSTORES_PATHS + " mandatory environment variable is not defined"); + } + + @Test + void shouldThrowExceptionWhenTrustorePathsSizesDoNotMatch() { + // given + List<String> truststores = createListOfPathsWithExtension(2, JKS_EXTENSION); + List<String> truststoresPasswords = createListOfPathsWithExtension(1, PASS_EXTENSION); + + mockTruststorePaths(truststores, truststoresPasswords); + // when, then + assertThatExceptionOfType(ConfigurationException.class) + .isThrownBy(() -> provider.createConfiguration()) + .withMessageContaining("Size of " + TRUSTSTORES_PATHS + + " does not match size of " + TRUSTSTORES_PASSWORDS_PATHS + " environment variables"); + } + + @Test + void shouldReturnEmptyListWhenOptionalEnvNotPresent() { + // given + List<String> truststores = createListOfPathsWithExtension(2, JKS_EXTENSION); + List<String> truststoresPasswords = createListOfPathsWithExtension(2, PASS_EXTENSION); + mockTruststorePaths(truststores, truststoresPasswords); + mockKeystorePaths(Optional.empty(), Optional.empty()); + // when + AppConfiguration paths = provider.createConfiguration(); + // then + assertThat(paths.getDestinationKeystorePaths()).isEmpty(); + assertThat(paths.getSourceKeystorePaths()).isEmpty(); + } + + private void mockTruststorePaths(List<String> truststores, List<String> truststoresPasswords) { + mockTruststores(truststores); + mockTruststoresPasswords(truststoresPasswords); + } + + private void mockKeystorePaths(Optional<String> sourceKeystoresPairPaths, Optional<String> destKeystoresPairPaths) { + mockKeystoreCopierSourcePaths(sourceKeystoresPairPaths); + mockKeystoreCopierDestinationPaths(destKeystoresPairPaths); + } + + private void mockTruststores(List<String> truststores) throws CertificatesPathsValidationException { + when(envReader.getEnv(TRUSTSTORES_PATHS.name())).thenReturn(Optional.of(SAMPLE_TRUSTSTORES_PATHS)); + when(pathsSplitter.getValidatedPaths(TRUSTSTORES_PATHS, Optional.of(SAMPLE_TRUSTSTORES_PATHS))) + .thenReturn(truststores); + } + + private void mockTruststoresPasswords(List<String> truststoresPasswords) + throws CertificatesPathsValidationException { + Optional<String> passwordsPaths = Optional.of(SAMPLE_TRUSTSTORES_PASSWORDS_PATHS); + when(envReader.getEnv(TRUSTSTORES_PASSWORDS_PATHS.name())).thenReturn(passwordsPaths); + when(pathsSplitter.getValidatedPaths(TRUSTSTORES_PASSWORDS_PATHS, passwordsPaths)) + .thenReturn(truststoresPasswords); + } + + private void mockKeystoreCopierSourcePaths(Optional<String> paths) { + when(envReader.getEnv(KEYSTORE_SOURCE_PATHS.name())).thenReturn(paths); + } + + private void mockKeystoreCopierDestinationPaths(Optional<String> paths) { + when(envReader.getEnv(KEYSTORE_DESTINATION_PATHS.name())).thenReturn(paths); + } + + private List<String> createListOfPathsWithExtension(int numberOfPaths, String passwordExtension) { + List<String> paths = new ArrayList<>(); + while (numberOfPaths-- > 0) { + paths.add(BASE_TRUSTSTORE_PATH + numberOfPaths + passwordExtension); + } + return paths; + } + +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/path/DelimitedPathsSplitterTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/path/DelimitedPathsSplitterTest.java new file mode 100644 index 00000000..be1bc394 --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/path/DelimitedPathsSplitterTest.java @@ -0,0 +1,107 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.configuration.path; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.TRUSTSTORES_PASSWORDS_PATHS; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.TRUSTSTORES_PATHS; + +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.oom.certservice.postprocessor.configuration.exception.CertificatesPathsValidationException; + +@ExtendWith(MockitoExtension.class) +class DelimitedPathsSplitterTest { + + private static final String VALID_TRUSTSTORES = "/opt/app/certificates/truststore.jks:/opt/app/certificates/truststore.pem"; + private static final String VALID_TRUSTSTORES_PASSWORDS = "/opt/app/certificates/truststore.pass:"; + private static final String VALID_TRUSTSTORES_PASSWORDS_WITH_EMPTY_IN_THE_MIDDLE = "/opt/app/certificates/truststore.pass::/etc/truststore.pass"; + private static final String INVALID_TRUSTSTORES = "/opt/app/certificates/truststore.jks:/opt/app/certificates/truststore.invalid"; + private static final String INVALID_TRUSTSTORES_PASSWORDS = "/opt/app/certificates/truststore.pass:/.pass"; + + private DelimitedPathsSplitter delimitedPathsSplitter; + + @BeforeEach + void setUp() { + delimitedPathsSplitter = new DelimitedPathsSplitter(); + } + + @Test + void shouldReturnCorrectListWhenTruststoresValid() { + // when, then + assertThat(delimitedPathsSplitter.getValidatedPaths(TRUSTSTORES_PATHS, Optional.of(VALID_TRUSTSTORES))) + .containsSequence("/opt/app/certificates/truststore.jks", + "/opt/app/certificates/truststore.pem"); + } + + @Test + void shouldThrowExceptionWhenTruststoresPathsEnvIsEmpty() { + // when, then + assertThatExceptionOfType(CertificatesPathsValidationException.class) + .isThrownBy(() -> delimitedPathsSplitter.getValidatedPaths(TRUSTSTORES_PATHS, Optional.of(""))); + } + + @Test + void shouldThrowExceptionWhenOneOfTruststoresPathsInvalid() { + // when, then + assertThatExceptionOfType(CertificatesPathsValidationException.class) + .isThrownBy(() -> delimitedPathsSplitter + .getValidatedPaths(TRUSTSTORES_PATHS, Optional.of(INVALID_TRUSTSTORES))); + } + + @Test + void shouldReturnCorrectListWhenTruststoresPasswordsValid() { + // when, then + assertThat(delimitedPathsSplitter + .getValidatedPaths(TRUSTSTORES_PASSWORDS_PATHS, Optional.of(VALID_TRUSTSTORES_PASSWORDS))) + .containsSequence("/opt/app/certificates/truststore.pass", ""); + } + + @Test + void shouldReturnCorrectListWhenTruststoresPasswordsContainsEmptyPathsInTheMiddle() { + // when, then + assertThat(delimitedPathsSplitter.getValidatedPaths(TRUSTSTORES_PASSWORDS_PATHS, + Optional.of(VALID_TRUSTSTORES_PASSWORDS_WITH_EMPTY_IN_THE_MIDDLE))).containsSequence( + "/opt/app/certificates/truststore.pass", + "", + "/etc/truststore.pass" + ); + } + + @Test + void shouldThrowExceptionWhenTruststoresPasswordsPathEnvIsEmpty() { + // when, then + assertThatExceptionOfType(CertificatesPathsValidationException.class) + .isThrownBy( + () -> delimitedPathsSplitter.getValidatedPaths(TRUSTSTORES_PASSWORDS_PATHS, Optional.of(""))); + } + + @Test + void shouldThrowExceptionWhenOneOfTruststorePasswordPathsInvalid() { + // when, then + assertThatExceptionOfType(CertificatesPathsValidationException.class) + .isThrownBy(() -> delimitedPathsSplitter + .getValidatedPaths(TRUSTSTORES_PASSWORDS_PATHS, Optional.of(INVALID_TRUSTSTORES_PASSWORDS))); + } +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/path/env/EnvReaderTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/path/env/EnvReaderTest.java new file mode 100644 index 00000000..343e5655 --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/path/env/EnvReaderTest.java @@ -0,0 +1,62 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.configuration.path.env; + + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; +import static org.onap.oom.certservice.postprocessor.configuration.model.EnvVariable.TRUSTSTORES_PASSWORDS_PATHS; + +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class EnvReaderTest { + + private static final String SAMPLE_PASS_PATH = "/sample/path/trust.pass"; + EnvReader provider; + + @BeforeEach + void setUp() { + provider = Mockito.spy(EnvReader.class); + } + + @Test + void shouldReturnOptionalWithEnv() { + // given + String envName = TRUSTSTORES_PASSWORDS_PATHS.name(); + when(provider.getSystemEnv(envName)).thenReturn(Optional.of(SAMPLE_PASS_PATH)); + // when + Optional<String> result = provider.getEnv(envName); + // then + assertThat(result).isEqualTo(Optional.of(SAMPLE_PASS_PATH)); + } + + @Test + void shouldReturnEmptyOptional() { + // given + String envName = TRUSTSTORES_PASSWORDS_PATHS.name(); + // when + Optional<String> result = provider.getEnv(envName); + // then + assertThat(result).isEmpty(); + } +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/path/validation/ValidationFunctionsTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/path/validation/ValidationFunctionsTest.java new file mode 100644 index 00000000..f65147a9 --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/configuration/path/validation/ValidationFunctionsTest.java @@ -0,0 +1,135 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.configuration.path.validation; + + +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.oom.certservice.postprocessor.configuration.path.validation.ValidationFunctions.doesItContainValidCertificatesPaths; +import static org.onap.oom.certservice.postprocessor.configuration.path.validation.ValidationFunctions.doesItContainValidPasswordPaths; +import static org.onap.oom.certservice.postprocessor.configuration.path.validation.ValidationFunctions.doesItContainValidPathsToCopy; + +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +class ValidationFunctionsTest { + + @Test + void shouldValidateWithSuccessCorrectCertificatesPaths() { + // given + List<String> certPaths = Arrays.asList("/opt/app/certificates/truststore.p12"); + // when + boolean result = doesItContainValidCertificatesPaths().test(certPaths); + // then + assertThat(result).isTrue(); + } + + @Test + void shouldValidateWithFailureCertificatesPathsWithOneEmptyPath() { + // given + List<String> certPaths = Arrays.asList("/opt/app/certificates/truststore.p12", ""); + // when + boolean result = doesItContainValidCertificatesPaths().test(certPaths); + // then + assertThat(result).isFalse(); + } + + @Test + void shouldValidateWithFailureCertificatesPathsWithOnePathWhichHasIncorrectExtension() { + // given + List<String> certPaths = Arrays.asList("/opt/app/certificates/truststore.txt", "/opt/cert.p12"); + // when + boolean result = doesItContainValidCertificatesPaths().test(certPaths); + // then + assertThat(result).isFalse(); + } + + @Test + void shouldValidateWithSuccessCertificatesPasswordPaths() { + // given + List<String> passwordPaths = Arrays.asList("/opt/app/certificates/truststore.pass", ""); + // when + boolean result = doesItContainValidPasswordPaths().test(passwordPaths); + // then + assertThat(result).isTrue(); + } + + @Test + void shouldValidateWithSuccessCertificatePasswordsPathsWhichContainsEmptyPathsInTheMiddle() { + // given + List<String> passwordPaths = Arrays.asList("/opt/app/certificates/truststore.pass", "", "/etc/truststore.pass"); + // when + boolean result = doesItContainValidPasswordPaths().test(passwordPaths); + // then + assertThat(result).isTrue(); + } + + @Test + void shouldValidateWithFailureCertificatesPasswordsPathsWithIncorrectExtension() { + // given + List<String> passwordPaths = Arrays.asList("/pass.txt"); + // when + boolean result = doesItContainValidPasswordPaths().test(passwordPaths); + // then + assertThat(result).isFalse(); + } + + @Test + void shouldValidateWithFailureCertificatesPasswordPathsWithMissingPrecedingSlash() { + // given + List<String> passwordPaths = Arrays.asList("jks.pass"); + // when + boolean result = doesItContainValidPasswordPaths().test(passwordPaths); + // then + assertThat(result).isFalse(); + } + + @Test + void shouldValidateWithSuccessSourcePathsToCopyFiles() { + // given + List<String> sourcePaths = Arrays.asList("/opt/dcae/cacert/external/keystore.p12", + "/opt/dcae/cacert/external/keystore.pass"); + // when + boolean result = doesItContainValidPathsToCopy().test(sourcePaths); + // then + assertThat(result).isTrue(); + } + + @Test + void shouldValidateWithSuccessDestinationPathsToCopyFiles() { + // given + List<String> sourcePaths = Arrays.asList("/opt/dcae/cacert/cert.p12","/opt/dcae/cacert/p12.pass"); + // when + boolean result = doesItContainValidPathsToCopy().test(sourcePaths); + // then + assertThat(result).isTrue(); + } + + @Test + void shouldValidateWithFailureDestinationPathsWithIncorrectExtension() { + // given + List<String> sourcePaths = Arrays.asList("/opt/dcae/cacert/cert.txt","/opt/dcae/cacert/p12.other"); + // when + boolean result = doesItContainValidPathsToCopy().test(sourcePaths); + // then + assertThat(result).isFalse(); + } + +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/copier/KeystoreCopierTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/copier/KeystoreCopierTest.java new file mode 100644 index 00000000..99193a8d --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/copier/KeystoreCopierTest.java @@ -0,0 +1,147 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.copier; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Collections; +import org.apache.commons.io.FileUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.onap.oom.certservice.postprocessor.common.FileTools; +import org.onap.oom.certservice.postprocessor.configuration.model.AppConfiguration; +import org.onap.oom.certservice.postprocessor.copier.exception.KeystoreFileCopyException; +import org.onap.oom.certservice.postprocessor.copier.exception.KeystoreNotExistException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class KeystoreCopierTest { + + private static final String SOURCE_CONTENT = "source content"; + private static final String DESTINATION_CONTENT = "destination content"; + + @TempDir + File dir; + + private KeystoreCopier copier = new KeystoreCopier(new FileTools()); + + @Test + void shouldDoNothingForEmptySourceFileList() { + AppConfiguration configuration = createEmptyConfiguration(); + + copier.copyKeystores(configuration); + + assertThat(dir.listFiles()).isEmpty(); + } + + + @Test + void shouldCopyFileAndCreateBackup() throws IOException { + File source = createFile("source.p12", SOURCE_CONTENT); + File destination = createFile("destination.p12", DESTINATION_CONTENT); + File backup = declareFile("destination.p12.bak"); + AppConfiguration configuration = createConfiguration(source, destination); + + copier.copyKeystores(configuration); + + assertThat(readFile(destination)).isEqualTo(readFile(source)); + assertThat(backup.exists()).isTrue(); + assertThat(readFile(backup)).isEqualTo(DESTINATION_CONTENT); + } + + @Test + void shouldCopyFileWithoutCreatingBackup() throws IOException { + File source = createFile("source.p12", SOURCE_CONTENT); + File destination = declareFile("destination.p12"); + File backup = declareFile("destination.p12.bak"); + AppConfiguration configuration = createConfiguration(source, destination); + + copier.copyKeystores(configuration); + + assertThat(destination.exists()).isTrue(); + assertThat(readFile(destination)).isEqualTo(readFile(source)); + assertThat(backup.exists()).isFalse(); + } + + @Test + void shouldThrowKeystoreNotExistException() throws IOException { + File source = declareFile("source.p12"); + File destination = declareFile("destination.p12"); + File backup = declareFile("destination.p12.bak"); + AppConfiguration configuration = createConfiguration(source, destination); + + assertThatExceptionOfType(KeystoreNotExistException.class).isThrownBy( () -> + copier.copyKeystores(configuration) + ); + + assertThat(source.exists()).isFalse(); + assertThat(destination.exists()).isFalse(); + assertThat(backup.exists()).isFalse(); + } + + @Test + void shouldThrowKeystoreFileCopyException() throws IOException { + File source = createFile("source.p12", SOURCE_CONTENT); + source.setReadable(false); + File destination = declareFile("destination.p12"); + File backup = declareFile("destination.p12.bak"); + AppConfiguration configuration = createConfiguration(source, destination); + + assertThatExceptionOfType(KeystoreFileCopyException.class).isThrownBy( () -> + copier.copyKeystores(configuration) + ); + + assertThat(source.exists()).isTrue(); + assertThat(destination.exists()).isFalse(); + assertThat(backup.exists()).isFalse(); + } + + private AppConfiguration createConfiguration(File source, File destination) { + return new AppConfiguration(Collections.emptyList(), Collections.emptyList(), + Collections.singletonList(source.getAbsolutePath()), + Collections.singletonList(destination.getAbsolutePath())); + } + + private AppConfiguration createEmptyConfiguration() { + return new AppConfiguration(Collections.emptyList(), Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList()); + } + + private String readFile(File file) throws IOException { + return FileUtils.readFileToString(file, Charset.defaultCharset()); + } + + private File declareFile(String name) { + return new File(dir.getAbsolutePath() + File.pathSeparator + name); + } + + private File createFile(String name, String content) throws IOException { + File file = new File(dir.getAbsolutePath() + File.pathSeparator + name); + if (file.createNewFile()) { + FileUtils.write(file, content, Charset.defaultCharset()); + } else { + throw new IllegalStateException("File could not be created: " + file.getAbsolutePath()); + } + return file; + } +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/TruststoreFilesProviderTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/TruststoreFilesProviderTest.java new file mode 100644 index 00000000..9040b53d --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/TruststoreFilesProviderTest.java @@ -0,0 +1,63 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.merger; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.postprocessor.merger.exception.KeystoreInstanceException; +import org.onap.oom.certservice.postprocessor.merger.exception.LoadTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.PasswordReaderException; +import org.onap.oom.certservice.postprocessor.merger.exception.TruststoreFileFactoryException; +import org.onap.oom.certservice.postprocessor.merger.model.Truststore; +import org.onap.oom.certservice.postprocessor.merger.model.TruststoreFactory; + +class TruststoreFilesProviderTest { + + private static final String TRUSTSTORE_JKS_PATH = "src/test/resources/truststore-jks.jks"; + private static final String TRUSTSTORE_JKS_PASS_PATH = "src/test/resources/truststore-jks.pass"; + private static final String TRUSTSTORE_P12_PATH = "src/test/resources/truststore-p12.p12"; + private static final String TRUSTSTORE_P12_PASS_PATH = "src/test/resources/truststore-p12.pass"; + private static final String TRUSTSTORE_PEM_PATH = "src/test/resources/truststore.pem"; + private static final String EMPTY_PASS_PATH = ""; + + @Test + void shouldReturnTruststoreFilesList() + throws TruststoreFileFactoryException, PasswordReaderException, LoadTruststoreException, KeystoreInstanceException { + //given + List<String> truststorePaths = Arrays.asList(TRUSTSTORE_JKS_PATH, TRUSTSTORE_P12_PATH, TRUSTSTORE_PEM_PATH); + List<String> truststorePasswordPaths = Arrays + .asList(TRUSTSTORE_JKS_PASS_PATH, TRUSTSTORE_P12_PASS_PATH, EMPTY_PASS_PATH); + + //when + List<Truststore> truststoreFilesList = TruststoreFilesProvider + .getTruststoreFiles(truststorePaths, truststorePasswordPaths); + + //then + assertThat(truststoreFilesList.size()).isEqualTo(3); + TruststoreFactory.create(TRUSTSTORE_JKS_PATH, TRUSTSTORE_JKS_PASS_PATH); + TruststoreFactory.create(TRUSTSTORE_P12_PATH, TRUSTSTORE_P12_PASS_PATH); + TruststoreFactory.create(TRUSTSTORE_PEM_PATH, EMPTY_PASS_PATH); + } + +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/JavaCertificateStoreControllerTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/JavaTruststoreTest.java index 8ee77ef2..93a5359b 100644 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/JavaCertificateStoreControllerTest.java +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/JavaTruststoreTest.java @@ -17,43 +17,40 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider; +package org.onap.oom.certservice.postprocessor.merger.model; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.onap.oom.truststoremerger.certification.file.TestCertificateProvider.getSampleJksTruststoreFile; import java.util.List; import org.junit.jupiter.api.Test; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.TestCertificateProvider; -import org.onap.oom.truststoremerger.certification.file.exception.AliasConflictException; -import org.onap.oom.truststoremerger.certification.file.exception.MissingTruststoreException; -import org.onap.oom.truststoremerger.certification.file.model.JavaTruststore; - -class JavaCertificateStoreControllerTest { +import org.onap.oom.certservice.postprocessor.api.ExitableException; +import org.onap.oom.certservice.postprocessor.merger.exception.AliasConflictException; +import org.onap.oom.certservice.postprocessor.merger.exception.MissingTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAlias; +class JavaTruststoreTest { @Test void throwExceptionWhenAliasConflictDetected() throws Exception { //given - JavaTruststore p12Truststore = TestCertificateProvider.getSampleP12Truststore(); - List<CertificateWithAlias> jksTruststoreCertificates = getSampleJksTruststoreFile().getCertificates(); + Truststore p12Truststore = TestCertificateProvider.getSampleP12Truststore(); + + List<CertificateWithAlias> certificateFromJks = TestCertificateProvider + .getSampleJksTruststoreFile().getCertificates(); //when //then assertThatExceptionOfType(AliasConflictException.class) - .isThrownBy(() -> p12Truststore.addCertificate(jksTruststoreCertificates)); + .isThrownBy(() -> p12Truststore.addCertificates(certificateFromJks)); } - @Test void throwExceptionWhenFileNotContainsTruststoreEntry() throws ExitableException { //given - JavaTruststore p12Truststore = TestCertificateProvider.getSampleP12Keystore(); + Truststore p12Truststore = TestCertificateProvider.getSampleP12Keystore(); //when//then assertThatExceptionOfType(MissingTruststoreException.class) - .isThrownBy(p12Truststore::getCertificates); + .isThrownBy(() -> p12Truststore.getCertificates()); } } diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/PemTruststoreTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/PemTruststoreTest.java new file mode 100644 index 00000000..af254896 --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/PemTruststoreTest.java @@ -0,0 +1,128 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.merger.model; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.mock; + +import java.io.File; +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreSpi; +import java.security.cert.Certificate; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.postprocessor.api.ExitableException; +import org.onap.oom.certservice.postprocessor.merger.exception.MissingTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.TruststoreDataOperationException; +import org.onap.oom.certservice.postprocessor.merger.exception.WriteTruststoreFileException; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAlias; + +class PemTruststoreTest { + + private static final int EXPECTED_ONE = 1; + + @Test + void getCertificatesShouldThrowExceptionWhenFileNotContainsCertificate() { + //given + File emptyPemFile = TestCertificateProvider.getEmptyPemFile(); + PemTruststore pemCertificate = new PemTruststore(emptyPemFile); + //when//then + assertThatExceptionOfType(MissingTruststoreException.class) + .isThrownBy(pemCertificate::getCertificates); + } + + @Test + void shouldThrowExceptionWhenCannotSaveFile() { + //given + KeyStoreSpi keyStoreSpi = mock(KeyStoreSpi.class); + KeyStore keyStore = new KeyStore(keyStoreSpi, null, "") { + }; + File pemFile = TestCertificateProvider.getEmptyPemFile(); + pemFile.setWritable(false); + PemTruststore pem = new PemTruststore(pemFile); + + //when. then + assertThatExceptionOfType(WriteTruststoreFileException.class) + .isThrownBy(pem::saveFile); + } + + @Test + void transformToStringInPemFormatShouldCorrectlyTransform() throws ExitableException, IOException { + //given + Truststore pemTruststore = TestCertificateProvider.getSamplePemTruststoreFile(); + + List<CertificateWithAlias> wrappedCertificates = pemTruststore.getCertificates(); + List<Certificate> certificateList = unWrapCertificate(wrappedCertificates); + File notEmptyPemFile = TestCertificateProvider.getNotEmptyPemFile(); + PemTruststore pemCertificate = new PemTruststore(notEmptyPemFile); + + //when + String certificateTransformed = pemCertificate.transformToStringInPemFormat(certificateList); + + //then + String expected = TestCertificateProvider.getExpectedPemCertificateAsString(); + assertThat(certificateTransformed).isEqualTo(expected); + } + + @Test + void fileNotContainsPemCertificateShouldReturnTrueIfFileNotContainsCertificate() + throws TruststoreDataOperationException { + //given + File emptyPemFile = TestCertificateProvider.getEmptyPemFile(); + PemTruststore pemCertificate = new PemTruststore(emptyPemFile); + //when//then + assertThat(pemCertificate.isFileWithoutPemCertificate()).isTrue(); + } + + @Test + void fileNotContainsPemCertificateShouldReturnFalseIfFileContainsCertificate() + throws TruststoreDataOperationException { + //given + File notEmptyPemFile = TestCertificateProvider.getNotEmptyPemFile(); + PemTruststore pemCertificate = new PemTruststore(notEmptyPemFile); + + //when//then + assertThat(pemCertificate.isFileWithoutPemCertificate()).isFalse(); + } + + @Test + void privateKeyIsSkippedWhileReadingCertificates() throws ExitableException { + //given + File pemTruststoreFile = TestCertificateProvider.getPemWithPrivateKeyFile(); + PemTruststore pemCertificate = new PemTruststore(pemTruststoreFile); + + //when + List<CertificateWithAlias> certificate = pemCertificate.getCertificates(); + + //then + assertThat(certificate).hasSize(EXPECTED_ONE); + } + + private List<Certificate> unWrapCertificate(List<CertificateWithAlias> certificateWithAliases) { + return certificateWithAliases + .stream() + .map(CertificateWithAlias::getCertificate) + .collect(Collectors.toList()); + } + +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/TestCertificateProvider.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/TestCertificateProvider.java index c971ca17..f32e09ce 100644 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/TestCertificateProvider.java +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/TestCertificateProvider.java @@ -17,7 +17,10 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file; +package org.onap.oom.certservice.postprocessor.merger.model; + +import static org.onap.oom.certservice.postprocessor.api.CertificateConstants.JKS_TYPE; +import static org.onap.oom.certservice.postprocessor.api.CertificateConstants.PKCS12_TYPE; import java.io.File; import java.io.IOException; @@ -25,26 +28,22 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; -import org.onap.oom.truststoremerger.certification.file.exception.KeystoreInstanceException; -import org.onap.oom.truststoremerger.certification.file.exception.LoadTruststoreException; -import org.onap.oom.truststoremerger.certification.file.model.JavaTruststore; -import org.onap.oom.truststoremerger.certification.file.model.PemTruststore; -import org.onap.oom.truststoremerger.certification.file.provider.JavaCertificateStoreController; -import org.onap.oom.truststoremerger.certification.file.provider.CertificateStoreControllerFactory; -import org.onap.oom.truststoremerger.certification.file.provider.PemCertificateController; +import org.onap.oom.certservice.postprocessor.merger.exception.KeystoreInstanceException; +import org.onap.oom.certservice.postprocessor.merger.exception.LoadTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.PasswordReaderException; -public class TestCertificateProvider { +public final class TestCertificateProvider { public static final String SAMPLE_P12_TRUSTSTORE_FILE_PATH = "src/test/resources/truststore-p12.p12"; - public static final String SAMPLE_P12_TRUSTSTORE_PASSWORD = "88y9v5D8H3SG6bZWRVHDfOAo"; + public static final String SAMPLE_P12_TRUSTSTORE_PASSWORD_PATH = "src/test/resources/truststore-p12.pass"; public static final String TMP_P12_TRUSTSTORE_FILE_PATH = "src/test/resources/tmp-truststore-p12.p12"; public static final String SAMPLE_P12_KEYSTORE_FILE_PATH = "src/test/resources/keystore.p12"; - public static final String SAMPLE_P12_KEYSTORE_PASSWORD = "Foh49MJNYI7S_pEzE9gvUDSu"; + public static final String SAMPLE_P12_KEYSTORE_PASSWORD_PATH = "src/test/resources/keystore.pass"; public static final String SAMPLE_JKS_TRUSTSTORE_FILE_PATH = "src/test/resources/truststore-jks.jks"; public static final String SAMPLE_JKS_TRUSTSTORE_UNIQUE_ALIAS_FILE_PATH = "src/test/resources/truststore-jks-uniq.jks"; - public static final String SAMPLE_JKS_TRUSTSTORE_PASSWORD = "EOyuFbuYDyq_EhpboM72RHua"; + public static final String SAMPLE_JKS_TRUSTSTORE_PASSWORD_PATH = "src/test/resources/truststore-jks.pass"; public static final String TMP_JKS_TRUSTSTORE_FILE_PATH = "src/test/resources/tmp-truststore-jks.jks"; public static final String SAMPLE_PEM_TRUSTSTORE_FILE_PATH = "src/test/resources/truststore.pem"; @@ -52,99 +51,95 @@ public class TestCertificateProvider { public static final String TMP_PEM_TRUSTSTORE_FILE_PATH = "src/test/resources/tmp-truststore.pem"; public static final String SAMPLE_PEM_TRUSTSTORE_WITH_PRIVATE_KEY_FILE_PATH = "src/test/resources/truststore-with-private-key.pem"; - private static final CertificateStoreControllerFactory certificateStoreControllerFactory = new CertificateStoreControllerFactory(); + public static final String PEM_FILE_PATH = "src/test/resources/truststore.pem"; + public static final String PEM_BACKUP_FILE_PATH = "src/test/resources/truststore.pem.bak"; - public static JavaTruststore getSampleP12Truststore() throws LoadTruststoreException, KeystoreInstanceException { - return createP12TruststoreInstance(SAMPLE_P12_TRUSTSTORE_FILE_PATH, SAMPLE_P12_TRUSTSTORE_PASSWORD); + private TestCertificateProvider() { } - public static JavaTruststore getSampleP12Keystore() throws LoadTruststoreException, KeystoreInstanceException { - return createP12TruststoreInstance(SAMPLE_P12_KEYSTORE_FILE_PATH, SAMPLE_P12_KEYSTORE_PASSWORD); + public static Truststore getSampleP12Truststore() + throws LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { + return createJavaTruststore(SAMPLE_P12_TRUSTSTORE_FILE_PATH, SAMPLE_P12_TRUSTSTORE_PASSWORD_PATH, PKCS12_TYPE); } - public static JavaTruststore createTmpP12TruststoreFile() - throws IOException, LoadTruststoreException, KeystoreInstanceException { - copyFile(SAMPLE_P12_TRUSTSTORE_FILE_PATH, TMP_P12_TRUSTSTORE_FILE_PATH); - return createP12TruststoreInstance(TMP_P12_TRUSTSTORE_FILE_PATH, SAMPLE_P12_TRUSTSTORE_PASSWORD); + public static Truststore getSampleP12Keystore() + throws LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { + return createJavaTruststore(SAMPLE_P12_KEYSTORE_FILE_PATH, SAMPLE_P12_KEYSTORE_PASSWORD_PATH, PKCS12_TYPE); } - public static JavaTruststore getTmpP12TruststoreFile() throws LoadTruststoreException, KeystoreInstanceException { - return createP12TruststoreInstance(TMP_P12_TRUSTSTORE_FILE_PATH, SAMPLE_P12_TRUSTSTORE_PASSWORD); - } - - private static JavaTruststore createP12TruststoreInstance(String filePath, String password) - throws LoadTruststoreException, KeystoreInstanceException { - File certFile = getFile(filePath); - JavaCertificateStoreController storeController = certificateStoreControllerFactory - .createLoadedPkcs12CertificateStoreController(certFile, password); - return new JavaTruststore(certFile, storeController); + public static Truststore createTmpP12TruststoreFile() + throws IOException, LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { + copyFile(SAMPLE_P12_TRUSTSTORE_FILE_PATH, TMP_P12_TRUSTSTORE_FILE_PATH); + return createJavaTruststore(TMP_P12_TRUSTSTORE_FILE_PATH, SAMPLE_P12_TRUSTSTORE_PASSWORD_PATH, PKCS12_TYPE); } - public static PemTruststore getSamplePemTruststoreFile() { + public static Truststore getSamplePemTruststoreFile() { return getPemTruststoreInstance(SAMPLE_PEM_TRUSTSTORE_FILE_PATH); } - public static PemTruststore getEmptyPemTruststoreFile() { - return getPemTruststoreInstance(EMPTY_PEM_TRUSTSTORE_FILE_PATH); - } - - public static PemTruststore createEmptyTmpPemTruststoreFile() throws IOException { + public static Truststore createEmptyTmpPemTruststoreFile() + throws IOException { copyFile(EMPTY_PEM_TRUSTSTORE_FILE_PATH, TMP_PEM_TRUSTSTORE_FILE_PATH); return getPemTruststoreInstance(TMP_PEM_TRUSTSTORE_FILE_PATH); } - public static PemTruststore createTmpPemTruststoreFile() throws IOException { + public static Truststore createTmpPemTruststoreFile() + throws IOException { copyFile(SAMPLE_PEM_TRUSTSTORE_FILE_PATH, TMP_PEM_TRUSTSTORE_FILE_PATH); return getPemTruststoreInstance(TMP_PEM_TRUSTSTORE_FILE_PATH); } - public static PemTruststore getTmpPemTruststoreFile() { - return getPemTruststoreInstance(TMP_PEM_TRUSTSTORE_FILE_PATH); - } - - public static PemTruststore getPemWithPrivateKeyTruststoreFile() { - return getPemTruststoreInstance(SAMPLE_PEM_TRUSTSTORE_WITH_PRIVATE_KEY_FILE_PATH); - } - public static String getExpectedPemCertificateAsString() throws IOException { Path samplePemFilePath = Paths.get(SAMPLE_PEM_TRUSTSTORE_FILE_PATH); return Files.readString(samplePemFilePath); } - public static JavaTruststore getSampleJksTruststoreFile() - throws LoadTruststoreException, KeystoreInstanceException { - return createJKSTruststoreInstance(SAMPLE_JKS_TRUSTSTORE_FILE_PATH, SAMPLE_JKS_TRUSTSTORE_PASSWORD); + public static Truststore getSampleJksTruststoreFile() + throws LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { + return createJavaTruststore(SAMPLE_JKS_TRUSTSTORE_FILE_PATH, SAMPLE_JKS_TRUSTSTORE_PASSWORD_PATH, JKS_TYPE); } - public static JavaTruststore getSampleJksTruststoreFileWithUniqueAlias() - throws LoadTruststoreException, KeystoreInstanceException { - return createJKSTruststoreInstance(SAMPLE_JKS_TRUSTSTORE_UNIQUE_ALIAS_FILE_PATH, - SAMPLE_JKS_TRUSTSTORE_PASSWORD); + public static Truststore getSampleJksTruststoreFileWithUniqueAlias() + throws LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { + return createJavaTruststore(SAMPLE_JKS_TRUSTSTORE_UNIQUE_ALIAS_FILE_PATH, SAMPLE_JKS_TRUSTSTORE_PASSWORD_PATH, + JKS_TYPE); } - public static JavaTruststore createTmpJksTruststoreFileWithUniqAlias() - throws IOException, LoadTruststoreException, KeystoreInstanceException { + public static Truststore createTmpJksTruststoreFileWithUniqAlias() + throws IOException, LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { copyFile(SAMPLE_JKS_TRUSTSTORE_UNIQUE_ALIAS_FILE_PATH, TMP_JKS_TRUSTSTORE_FILE_PATH); - return createJKSTruststoreInstance(TMP_JKS_TRUSTSTORE_FILE_PATH, SAMPLE_JKS_TRUSTSTORE_PASSWORD); + return createJavaTruststore(TMP_JKS_TRUSTSTORE_FILE_PATH, SAMPLE_JKS_TRUSTSTORE_PASSWORD_PATH, JKS_TYPE); + } + + public static File getEmptyPemFile() { + return getFile(EMPTY_PEM_TRUSTSTORE_FILE_PATH); + } + + public static File getNotEmptyPemFile() { + return getFile(SAMPLE_PEM_TRUSTSTORE_FILE_PATH); + } + + public static File getPemWithPrivateKeyFile() { + return getFile(SAMPLE_PEM_TRUSTSTORE_WITH_PRIVATE_KEY_FILE_PATH); } public static void removeTemporaryFiles() throws IOException { Files.deleteIfExists(Paths.get(TMP_PEM_TRUSTSTORE_FILE_PATH)); Files.deleteIfExists(Paths.get(TMP_JKS_TRUSTSTORE_FILE_PATH)); Files.deleteIfExists(Paths.get(TMP_P12_TRUSTSTORE_FILE_PATH)); + Files.deleteIfExists(Paths.get(PEM_BACKUP_FILE_PATH)); } - private static JavaTruststore createJKSTruststoreInstance(String filePath, String password) - throws LoadTruststoreException, KeystoreInstanceException { + private static Truststore createJavaTruststore(String filePath, String password, String instanceType) + throws LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { File certFile = getFile(filePath); - JavaCertificateStoreController storeController = certificateStoreControllerFactory - .createLoadedJksCertificateStoreController(certFile, password); - return new JavaTruststore(certFile, storeController); + return JavaTruststoreFactory.create(certFile, password, instanceType); } - private static PemTruststore getPemTruststoreInstance(String tmpPemTruststoreFilePath) { + private static Truststore getPemTruststoreInstance( + String tmpPemTruststoreFilePath) { File file = getFile(tmpPemTruststoreFilePath); - return new PemTruststore(file, new PemCertificateController(file)); + return new PemTruststore(file); } private static void copyFile(String sourcePath, String destPath) throws IOException { diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/TruststoreFactoryTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/TruststoreFactoryTest.java index b2063cc3..42bf533a 100644 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/TruststoreFactoryTest.java +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/TruststoreFactoryTest.java @@ -18,25 +18,18 @@ */ -package org.onap.oom.truststoremerger.certification.file.provider; +package org.onap.oom.certservice.postprocessor.merger.model; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; -import org.onap.oom.truststoremerger.certification.file.TruststoreFileFactory; -import org.onap.oom.truststoremerger.certification.file.model.JavaTruststore; -import org.onap.oom.truststoremerger.certification.file.model.PemTruststore; -import org.onap.oom.truststoremerger.certification.file.model.Truststore; -import org.onap.oom.truststoremerger.certification.file.exception.KeystoreInstanceException; -import org.onap.oom.truststoremerger.certification.file.exception.LoadTruststoreException; - -import java.io.File; -import org.onap.oom.truststoremerger.certification.file.exception.PasswordReaderException; -import org.onap.oom.truststoremerger.certification.file.exception.TruststoreFileFactoryException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import org.onap.oom.certservice.postprocessor.merger.exception.KeystoreInstanceException; +import org.onap.oom.certservice.postprocessor.merger.exception.LoadTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.PasswordReaderException; +import org.onap.oom.certservice.postprocessor.merger.exception.TruststoreFileFactoryException; @ExtendWith(MockitoExtension.class) class TruststoreFactoryTest { @@ -50,66 +43,66 @@ class TruststoreFactoryTest { private static final String TRUSTSTORE_UNKNOWN_EXTENSION_PATH = "src/test/resources/truststore-jks.unknown"; private static final String NON_EXISTING_TRUSTSTORE_PATH = "src/test/resources/non-existing-truststore.jks"; - private TruststoreFileFactory truststoreFileFactory; - - @BeforeEach - void setUp() { - truststoreFileFactory = new TruststoreFileFactory(new FileManager(), new PasswordReader()); - } - @Test void shouldReturnCorrectJksTruststoreForJksFile() throws LoadTruststoreException, PasswordReaderException, TruststoreFileFactoryException, KeystoreInstanceException { - Truststore truststore = truststoreFileFactory - .create(TRUSTSTORE_JKS_PATH, TRUSTSTORE_JKS_PASS_PATH); - assertThat(truststore).isInstanceOf(JavaTruststore.class); - JavaTruststore jksTruststore = (JavaTruststore) truststore; - assertThat(jksTruststore.getFile()).isEqualTo(new File(TRUSTSTORE_JKS_PATH)); + //given, when + Truststore truststore = TruststoreFactory + .create(TRUSTSTORE_JKS_PATH, TRUSTSTORE_JKS_PASS_PATH); + + //then + assertThat(truststore).isInstanceOf(Truststore.class); } @Test void shouldReturnCorrectP12TruststoreForP12File() throws LoadTruststoreException, PasswordReaderException, TruststoreFileFactoryException, KeystoreInstanceException { - Truststore truststore = truststoreFileFactory - .create(TRUSTSTORE_P12_PATH, - TRUSTSTORE_P12_PASS_PATH); - assertThat(truststore).isInstanceOf(JavaTruststore.class); + //given, when + Truststore truststore = TruststoreFactory + .create(TRUSTSTORE_P12_PATH, TRUSTSTORE_P12_PASS_PATH); + + //then + assertThat(truststore).isInstanceOf(Truststore.class); } @Test void shouldReturnCorrectPemTruststoreForPemFile() throws LoadTruststoreException, PasswordReaderException, TruststoreFileFactoryException, KeystoreInstanceException { - Truststore truststore = truststoreFileFactory - .create(TRUSTSTORE_PEM_PATH, - EMPTY_PASS_PATH); - assertThat(truststore).isInstanceOf(PemTruststore.class); + //given, when + Truststore truststore = TruststoreFactory + .create(TRUSTSTORE_PEM_PATH, + EMPTY_PASS_PATH); + + //then + assertThat(truststore).isInstanceOf(Truststore.class); } @Test void shouldThrowExceptionForInvalidP12PassPath() { assertThatExceptionOfType(PasswordReaderException.class).isThrownBy( - () -> truststoreFileFactory.create(TRUSTSTORE_P12_PATH, EMPTY_PASS_PATH) + () -> TruststoreFactory.create(TRUSTSTORE_P12_PATH, EMPTY_PASS_PATH) ); } @Test void shouldThrowExceptionForInvalidJksPassPath() { assertThatExceptionOfType(PasswordReaderException.class).isThrownBy( - () -> truststoreFileFactory.create(TRUSTSTORE_JKS_PATH, EMPTY_PASS_PATH) + () -> TruststoreFactory.create(TRUSTSTORE_JKS_PATH, EMPTY_PASS_PATH) ); } @Test void shouldThrowExceptionForUnknownTruststoreExtension() { assertThatExceptionOfType(TruststoreFileFactoryException.class).isThrownBy( - () -> truststoreFileFactory.create(TRUSTSTORE_UNKNOWN_EXTENSION_PATH, TRUSTSTORE_JKS_PASS_PATH) + () -> TruststoreFactory + .create(TRUSTSTORE_UNKNOWN_EXTENSION_PATH, TRUSTSTORE_JKS_PASS_PATH) ); } @Test void shouldThrowExceptionForNonExistingTruststoreFile() { assertThatExceptionOfType(TruststoreFileFactoryException.class).isThrownBy( - () -> truststoreFileFactory.create(NON_EXISTING_TRUSTSTORE_PATH, TRUSTSTORE_JKS_PASS_PATH) + () -> TruststoreFactory.create(NON_EXISTING_TRUSTSTORE_PATH, TRUSTSTORE_JKS_PASS_PATH) ); } diff --git a/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/TruststoreTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/TruststoreTest.java new file mode 100644 index 00000000..8ef148a8 --- /dev/null +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/TruststoreTest.java @@ -0,0 +1,206 @@ +/*============LICENSE_START======================================================= + * oom-truststore-merger + * ================================================================================ + * 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.postprocessor.merger.model; + +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.postprocessor.api.CertificateConstants.X_509_CERTIFICATE; +import static org.onap.oom.certservice.postprocessor.merger.model.TestCertificateProvider.PEM_BACKUP_FILE_PATH; + +import java.io.File; +import java.io.IOException; +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.onap.oom.certservice.postprocessor.api.CertificateConstants; +import org.onap.oom.certservice.postprocessor.api.ExitableException; +import org.onap.oom.certservice.postprocessor.merger.exception.CreateBackupException; +import org.onap.oom.certservice.postprocessor.merger.exception.KeystoreInstanceException; +import org.onap.oom.certservice.postprocessor.merger.exception.LoadTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.MissingTruststoreException; +import org.onap.oom.certservice.postprocessor.merger.exception.PasswordReaderException; +import org.onap.oom.certservice.postprocessor.merger.exception.TruststoreDataOperationException; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAlias; +import org.onap.oom.certservice.postprocessor.merger.model.certificate.CertificateWithAliasFactory; + +class TruststoreTest { + + private static final String BACKUP_EXTENSION = ".bak"; + + private static final int EXPECTED_ONE = 1; + public static final int EXPECTED_THREE = 3; + public static final int FIRST_ELEMENT = 0; + + private final CertificateWithAliasFactory factory = new CertificateWithAliasFactory(); + + @Test + void createBackupShouldCreateFileWithExtension() throws CreateBackupException { + //given + File pemFile = new File(TestCertificateProvider.PEM_FILE_PATH); + Truststore truststore = new PemTruststore(pemFile); + //when + truststore.createBackup(); + + //then + File backupFile = new File(PEM_BACKUP_FILE_PATH); + assertThat(backupFile.getName().endsWith(BACKUP_EXTENSION)).isTrue(); + assertThat(backupFile.isFile()).isTrue(); + } + + @ParameterizedTest + @MethodSource("truststoreProvider") + void truststoreShouldReadCertificatesFromFile(Truststore truststore) throws ExitableException { + //when + + List<CertificateWithAlias> certificates = truststore.getCertificates(); + Certificate certificate = certificates.get(FIRST_ELEMENT).getCertificate(); + + //then + assertThat(certificates).hasSize(EXPECTED_ONE); + assertThat(certificate.getType()).isEqualTo(X_509_CERTIFICATE); + } + + @Test + void jksTruststoreShouldAddDifferentCertificates() throws Exception { + //given + Truststore jksTruststore = TestCertificateProvider.createTmpJksTruststoreFileWithUniqAlias(); + + List<CertificateWithAlias> certificateFromP12 = TestCertificateProvider.getSampleP12Truststore() + .getCertificates(); + + List<CertificateWithAlias> certificateFromPem = TestCertificateProvider + .getSamplePemTruststoreFile().getCertificates(); + + //when + + jksTruststore.addCertificates(certificateFromP12); + + jksTruststore.addCertificates(certificateFromPem); + + jksTruststore.saveFile(); + + //then + + assertThat(jksTruststore.getCertificates()).hasSize(EXPECTED_THREE); + } + + @Test + void p12TruststoreShouldAddDifferentCertificates() throws Exception { + //given + Truststore p12Truststore = TestCertificateProvider.createTmpP12TruststoreFile(); + + List<CertificateWithAlias> certificateFromJks = TestCertificateProvider + .getSampleJksTruststoreFileWithUniqueAlias().getCertificates(); + + List<CertificateWithAlias> certificateFromPem = TestCertificateProvider + .getSamplePemTruststoreFile().getCertificates(); + + //when + + p12Truststore.addCertificates(certificateFromJks); + p12Truststore.addCertificates(certificateFromPem); + p12Truststore.saveFile(); + + //then + + assertThat(p12Truststore.getCertificates()).hasSize(EXPECTED_THREE); + } + + @Test + void pemTruststoreShouldAddDifferentCertificates() throws IOException, ExitableException { + //given + Truststore pemTruststore = TestCertificateProvider + .createTmpPemTruststoreFile(); + + List<CertificateWithAlias> certificateFromJks = TestCertificateProvider + .getSampleJksTruststoreFileWithUniqueAlias().getCertificates(); + + List<CertificateWithAlias> certificateFromP12 = TestCertificateProvider.getSampleP12Truststore() + .getCertificates(); + + //when + + pemTruststore.addCertificates(certificateFromJks); + + pemTruststore.addCertificates(certificateFromP12); + + pemTruststore.saveFile(); + + //then + + List<CertificateWithAlias> addedCertificates = pemTruststore.getCertificates(); + Certificate certificate = addedCertificates.get(FIRST_ELEMENT).getCertificate(); + + assertThat(pemTruststore.getCertificates()).hasSize(EXPECTED_THREE); + assertThat(certificate.getType()).isEqualTo(X_509_CERTIFICATE); + } + + @Test + void shouldThrowExceptionWhenFileNotContainsCertificate() throws IOException { + //given + Truststore tmpPemTruststoreFile = TestCertificateProvider + .createEmptyTmpPemTruststoreFile(); + //when//then + assertThatExceptionOfType(MissingTruststoreException.class) + .isThrownBy(() -> tmpPemTruststoreFile.getCertificates()); + } + + @Test + void shouldThrowExceptionWhenCannotConvertCertificateToPem() throws Exception { + //given + Truststore pemTruststore = TestCertificateProvider.createTmpPemTruststoreFile(); + Certificate certificate = mock(Certificate.class); + + when(certificate.getEncoded()).thenThrow(new CertificateEncodingException()); + + List<CertificateWithAlias> certificateFromPem = new ArrayList<>(); + certificateFromPem.add(factory.createPemCertificate(certificate)); + + pemTruststore.addCertificates(certificateFromPem); + + //when //then + assertThatExceptionOfType(TruststoreDataOperationException.class) + .isThrownBy(() -> pemTruststore.saveFile()); + } + + @AfterEach + void removeTemporaryFiles() throws IOException { + TestCertificateProvider.removeTemporaryFiles(); + } + + private static Stream<Arguments> truststoreProvider() + throws LoadTruststoreException, KeystoreInstanceException, PasswordReaderException { + return Stream.of( + Arguments.of(TestCertificateProvider.getSampleJksTruststoreFile()), + Arguments.of(TestCertificateProvider.getSampleP12Truststore()), + Arguments.of(TestCertificateProvider.getSamplePemTruststoreFile()) + ); + } + +} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/entry/PemAliasGeneratorTest.java b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/certificate/PemAliasGeneratorTest.java index 0897de29..bde23003 100644 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/entry/PemAliasGeneratorTest.java +++ b/trustStoreMerger/src/test/java/org/onap/oom/certservice/postprocessor/merger/model/certificate/PemAliasGeneratorTest.java @@ -17,7 +17,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.truststoremerger.certification.file.provider.entry; +package org.onap.oom.certservice.postprocessor.merger.model.certificate; import static org.assertj.core.api.Assertions.assertThat; @@ -27,7 +27,7 @@ import org.junit.jupiter.api.Test; class PemAliasGeneratorTest { - private final static String PREFIX_ALIAS_NAME = "pem-trusted-certificate-"; + private static final String PREFIX_ALIAS_NAME = "pem-trusted-certificate-"; static final int GENERATED_ALIASES_NUMBER = 100; @Test diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/TrustStoreMergerTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/TrustStoreMergerTest.java deleted file mode 100644 index a7c62361..00000000 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/TrustStoreMergerTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger; - -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.truststoremerger.api.ExitStatus; - -import static org.mockito.Mockito.verify; - -@ExtendWith(MockitoExtension.class) -class TrustStoreMergerTest { - - @Mock - AppExitHandler appExitHandler; - - @Test - void shouldExitWithTruststoresPathsProviderExceptionDueToMissingTrustoresPathEnvs() { - new TrustStoreMerger(appExitHandler).run(); - - verify(appExitHandler).exit(ExitStatus.TRUSTSTORES_PATHS_PROVIDER_EXCEPTION); - } -} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/model/JavaTruststoreTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/model/JavaTruststoreTest.java deleted file mode 100644 index eccf36bc..00000000 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/model/JavaTruststoreTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file.model; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.onap.oom.truststoremerger.api.CertificateConstants.X_509_CERTIFICATE; - -import java.io.IOException; -import java.security.cert.Certificate; -import java.util.List; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Test; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.TestCertificateProvider; - - -class JavaTruststoreTest { - public static final int FIRST_ELEMENT = 0; - private static final int EXPECTED_ONE = 1; - public static final int EXPECTED_THREE = 3; - - @Test - void jksTruststoreShouldReadCertificatesFromFile() throws ExitableException { - - //given - JavaTruststore jksTruststoreFile = TestCertificateProvider.getSampleJksTruststoreFile(); - - //when - List<CertificateWithAlias> certificates = jksTruststoreFile.getCertificates(); - Certificate certificate = certificates.get(FIRST_ELEMENT).getCertificate(); - - //then - assertThat(certificates).hasSize(EXPECTED_ONE); - assertThat(certificate.getType()).isEqualTo(X_509_CERTIFICATE); - } - - @Test - void jksTruststoreShouldAddDifferentCertificates() throws Exception { - - //given - JavaTruststore jksTruststore = TestCertificateProvider.createTmpJksTruststoreFileWithUniqAlias(); - List<CertificateWithAlias> p12certificates = TestCertificateProvider.getSampleP12Truststore() - .getCertificates(); - List<CertificateWithAlias> pemCertificates = TestCertificateProvider.getSamplePemTruststoreFile() - .getCertificates(); - - //when - jksTruststore.addCertificate(p12certificates); - jksTruststore.addCertificate(pemCertificates); - - //then - assertThat(jksTruststore.getCertificates()).hasSize(EXPECTED_THREE); - - } - - @Test - void p12TruststoreShouldReadCertificatesFromFile() throws ExitableException { - //given - JavaTruststore p12Truststore = TestCertificateProvider.getSampleP12Truststore(); - - //when - List<CertificateWithAlias> certificatesWithAliases = p12Truststore.getCertificates(); - Certificate certificate = certificatesWithAliases.get(FIRST_ELEMENT).getCertificate(); - - //then - assertThat(certificatesWithAliases).hasSize(EXPECTED_ONE); - assertThat(certificate.getType()).isEqualTo(X_509_CERTIFICATE); - } - - - @Test - void p12TruststoreShouldAddDifferentCertificates() throws Exception { - //given - JavaTruststore p12Truststore = TestCertificateProvider.createTmpP12TruststoreFile(); - List<CertificateWithAlias> jksTruststoreCertificates = TestCertificateProvider - .getSampleJksTruststoreFileWithUniqueAlias() - .getCertificates(); - List<CertificateWithAlias> pemTruststoreCertificates = TestCertificateProvider.getSamplePemTruststoreFile() - .getCertificates(); - - //when - p12Truststore.addCertificate(jksTruststoreCertificates); - p12Truststore.addCertificate(pemTruststoreCertificates); - p12Truststore.saveFile(); - - - //then - JavaTruststore p12TruststoreSaved = TestCertificateProvider.getTmpP12TruststoreFile(); - assertThat(p12TruststoreSaved.getCertificates()).hasSize(EXPECTED_THREE); - } - - - - @AfterAll - static void removeTemporaryFiles() throws IOException { - TestCertificateProvider.removeTemporaryFiles(); - } -} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/model/PemTruststoreTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/model/PemTruststoreTest.java deleted file mode 100644 index e7ffa093..00000000 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/model/PemTruststoreTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file.model; - -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.truststoremerger.api.CertificateConstants.X_509_CERTIFICATE; - -import java.io.IOException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Test; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAliasFactory; -import org.onap.oom.truststoremerger.certification.file.TestCertificateProvider; -import org.onap.oom.truststoremerger.certification.file.exception.MissingTruststoreException; -import org.onap.oom.truststoremerger.certification.file.exception.TruststoreDataOperationException; -import org.onap.oom.truststoremerger.certification.file.exception.WriteTruststoreFileException; - -class PemTruststoreTest { - - public static final int EXPECTED_ONE = 1; - public static final int EXPECTED_THREE = 3; - public static final int FIRST_ELEMENT = 0; - - private final CertificateWithAliasFactory factory = new CertificateWithAliasFactory(); - - @Test - void pemTruststoreShouldReadCertificatesFromFile() throws ExitableException { - - //given - PemTruststore pemTruststore = TestCertificateProvider.getSamplePemTruststoreFile(); - - //when - List<CertificateWithAlias> certificates = pemTruststore.getCertificates(); - Certificate certificate = certificates.get(FIRST_ELEMENT).getCertificate(); - //then - - assertThat(certificates).hasSize(EXPECTED_ONE); - assertThat(certificate.getType()).isEqualTo(X_509_CERTIFICATE); - } - - @Test - void pemTruststoreShouldAddDifferentCertificates() throws IOException, ExitableException { - - //given - PemTruststore tmpPemTruststoreFile = TestCertificateProvider.createTmpPemTruststoreFile(); - List<CertificateWithAlias> jksTruststoreCertificates = TestCertificateProvider - .getSampleJksTruststoreFileWithUniqueAlias().getCertificates(); - List<CertificateWithAlias> p12TruststoreCertificates = TestCertificateProvider.getSampleP12Truststore() - .getCertificates(); - - //when - tmpPemTruststoreFile.addCertificate(jksTruststoreCertificates); - tmpPemTruststoreFile.addCertificate(p12TruststoreCertificates); - tmpPemTruststoreFile.saveFile(); - - PemTruststore tmpPemTruststoreSaved = TestCertificateProvider.getTmpPemTruststoreFile(); - List<CertificateWithAlias> addedCertificates = tmpPemTruststoreSaved.getCertificates(); - Certificate certificate = addedCertificates.get(FIRST_ELEMENT).getCertificate(); - - //then - assertThat(addedCertificates).hasSize(EXPECTED_THREE); - assertThat(certificate.getType()).isEqualTo(X_509_CERTIFICATE); - - } - - @Test - void privateKeyIsSkippedWhileReadingCertificates() throws ExitableException { - //given - PemTruststore pemTruststore = TestCertificateProvider.getPemWithPrivateKeyTruststoreFile(); - - //when - List<CertificateWithAlias> certificate = pemTruststore.getCertificates(); - //then - - assertThat(certificate).hasSize(EXPECTED_ONE); - } - - @Test - void shouldThrowExceptionWhenCannotSaveFile() throws IOException, ExitableException { - //given - PemTruststore tmpPemTruststoreFile = TestCertificateProvider.createTmpPemTruststoreFile(); - List<CertificateWithAlias> pemTruststoreCertificates = - TestCertificateProvider.getSamplePemTruststoreFile().getCertificates(); - //when - tmpPemTruststoreFile.addCertificate(pemTruststoreCertificates); - tmpPemTruststoreFile.getFile().setWritable(false); - //then - assertThatExceptionOfType(WriteTruststoreFileException.class) - .isThrownBy(tmpPemTruststoreFile::saveFile); - - } - - @Test - void shouldThrowExceptionWhenFileNotContainsCertificate() throws IOException { - //given - PemTruststore tmpPemTruststoreFile = TestCertificateProvider.createEmptyTmpPemTruststoreFile(); - //when//then - assertThatExceptionOfType(MissingTruststoreException.class) - .isThrownBy(tmpPemTruststoreFile::getCertificates); - } - - @Test - void shouldThrowExceptionWhenCannotConvertCertificateToPem() throws Exception { - //given - PemTruststore pemTruststore = TestCertificateProvider.createTmpPemTruststoreFile(); - Certificate certificate = mock(Certificate.class); - - when(certificate.getEncoded()).thenThrow(new CertificateEncodingException()); - - List<CertificateWithAlias> certificatesWithAliases = new ArrayList<>(); - certificatesWithAliases.add(factory.createPemCertificate(certificate)); - pemTruststore.addCertificate(certificatesWithAliases); - - //when //then - assertThatExceptionOfType(TruststoreDataOperationException.class) - .isThrownBy(pemTruststore::saveFile); - } - - @AfterAll - static void removeTemporaryFiles() throws IOException { - TestCertificateProvider.removeTemporaryFiles(); - } - -} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/model/TruststoreTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/model/TruststoreTest.java deleted file mode 100644 index eea1f9c7..00000000 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/model/TruststoreTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file.model; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Test; -import org.onap.oom.truststoremerger.certification.file.exception.CreateBackupException; -import org.onap.oom.truststoremerger.certification.file.provider.PemCertificateController; - -import static org.assertj.core.api.Assertions.assertThat; - -class TruststoreTest { - - private static final String PEM_FILE_PATH = "src/test/resources/truststore.pem"; - private static final String PEM_BACKUP_FILE_PATH = "src/test/resources/truststore.pem.bak"; - private static final String BACKUP_EXTENSION = ".bak"; - - - @Test - void createBackupShouldCreateFileWithExtension() throws CreateBackupException { - //given - File pemFile = new File(PEM_FILE_PATH); - Truststore truststore = new PemTruststore(pemFile, new PemCertificateController(pemFile)); - //when - truststore.createBackup(); - - //then - File backupFile = new File(PEM_BACKUP_FILE_PATH); - assertThat(backupFile.getName().endsWith(BACKUP_EXTENSION)).isTrue(); - assertThat(backupFile.isFile()).isTrue(); - } - - - @AfterAll - static void removeBackupFile() throws IOException { - Files.deleteIfExists(Paths.get(PEM_BACKUP_FILE_PATH)); - } - -} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/PemCertificateControllerTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/PemCertificateControllerTest.java deleted file mode 100644 index 080fcca3..00000000 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/PemCertificateControllerTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file.provider; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -import java.io.File; -import java.io.IOException; -import java.security.cert.Certificate; -import java.util.List; -import java.util.stream.Collectors; -import org.junit.jupiter.api.Test; -import org.onap.oom.truststoremerger.api.ExitableException; -import org.onap.oom.truststoremerger.certification.file.provider.entry.CertificateWithAlias; -import org.onap.oom.truststoremerger.certification.file.TestCertificateProvider; -import org.onap.oom.truststoremerger.certification.file.exception.MissingTruststoreException; -import org.onap.oom.truststoremerger.certification.file.exception.TruststoreDataOperationException; -import org.onap.oom.truststoremerger.certification.file.model.PemTruststore; - -class PemCertificateControllerTest { - - @Test - void getNotEmptyCertificateListShouldThrowExceptionWhenFileNotContainsCertificate() { - //given - File emptyPemFile = TestCertificateProvider.getEmptyPemTruststoreFile().getFile(); - PemCertificateController pemCertificateController = new PemCertificateController(emptyPemFile); - //when//then - assertThatExceptionOfType(MissingTruststoreException.class) - .isThrownBy(pemCertificateController::getNotEmptyCertificateList); - } - - @Test - void transformToStringInPemFormatShouldCorrectlyTransform() throws ExitableException, IOException { - //given - PemTruststore pemTruststore = TestCertificateProvider.getSamplePemTruststoreFile(); - List<CertificateWithAlias> wrappedCertificates = pemTruststore.getCertificates(); - File notEmptyPemFile = pemTruststore.getFile(); - List<Certificate> certificateList = unWrapCertificate(wrappedCertificates); - PemCertificateController pemCertificateController = new PemCertificateController(notEmptyPemFile); - String expected = TestCertificateProvider.getExpectedPemCertificateAsString(); - - //when - String certificateTransformed = pemCertificateController.transformToStringInPemFormat(certificateList); - - //then - assertThat(certificateTransformed).isEqualTo(expected); - } - - @Test - void fileNotContainsPemCertificateShouldReturnTrueIfFileNotContainsCertificate() - throws TruststoreDataOperationException { - //given - File emptyPemFile = TestCertificateProvider.getEmptyPemTruststoreFile().getFile(); - PemCertificateController pemCertificateController = new PemCertificateController(emptyPemFile); - //when//then - assertThat(pemCertificateController.isFileWithoutPemCertificate()).isTrue(); - } - - @Test - void fileNotContainsPemCertificateShouldReturnFalseIfFileContainsCertificate() - throws TruststoreDataOperationException { - //given - File notEmptyPemFile = TestCertificateProvider.getSamplePemTruststoreFile().getFile(); - PemCertificateController pemCertificateController = new PemCertificateController(notEmptyPemFile); - - //when//then - assertThat(pemCertificateController.isFileWithoutPemCertificate()).isFalse(); - } - - private List<Certificate> unWrapCertificate(List<CertificateWithAlias> certificateWithAliases) { - return certificateWithAliases - .stream() - .map(CertificateWithAlias::getCertificate) - .collect(Collectors.toList()); - } - -} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/TruststoreFilesListProviderTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/TruststoreFilesListProviderTest.java deleted file mode 100644 index 0dadcfef..00000000 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/file/provider/TruststoreFilesListProviderTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.file.provider; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.oom.truststoremerger.certification.file.TruststoreFileFactory; -import org.onap.oom.truststoremerger.certification.file.TruststoreFilesListProvider; -import org.onap.oom.truststoremerger.certification.file.model.JavaTruststore; -import org.onap.oom.truststoremerger.certification.file.model.PemTruststore; -import org.onap.oom.truststoremerger.certification.file.model.Truststore; -import org.onap.oom.truststoremerger.certification.file.exception.KeystoreInstanceException; -import org.onap.oom.truststoremerger.certification.file.exception.LoadTruststoreException; - -import java.io.File; -import java.util.Arrays; -import java.util.List; -import org.onap.oom.truststoremerger.certification.file.exception.PasswordReaderException; -import org.onap.oom.truststoremerger.certification.file.exception.TruststoreFileFactoryException; - -import static org.assertj.core.api.Assertions.assertThat; - -class TruststoreFilesListProviderTest { - - private static final String TRUSTSTORE_JKS_PATH = "src/test/resources/truststore-jks.jks"; - private static final String TRUSTSTORE_JKS_PASS_PATH = "src/test/resources/truststore-jks.pass"; - private static final String TRUSTSTORE_P12_PATH = "src/test/resources/truststore-p12.p12"; - private static final String TRUSTSTORE_P12_PASS_PATH = "src/test/resources/truststore-p12.pass"; - private static final String TRUSTSTORE_PEM_PATH = "src/test/resources/truststore.pem"; - private static final String EMPTY_PASS_PATH = ""; - - private TruststoreFilesListProvider truststoreFilesListProvider; - - @BeforeEach - void setUp() { - TruststoreFileFactory truststoreFileFactory = new TruststoreFileFactory(new FileManager(), new PasswordReader()); - truststoreFilesListProvider = new TruststoreFilesListProvider(truststoreFileFactory); - } - - @Test - void shouldReturnTruststoreFilesList() - throws TruststoreFileFactoryException, PasswordReaderException, LoadTruststoreException, KeystoreInstanceException { - List<String> truststorePaths = Arrays.asList(TRUSTSTORE_JKS_PATH, TRUSTSTORE_P12_PATH, TRUSTSTORE_PEM_PATH); - List<String> truststorePasswordPaths = Arrays.asList(TRUSTSTORE_JKS_PASS_PATH, TRUSTSTORE_P12_PASS_PATH, EMPTY_PASS_PATH); - List<Truststore> truststoreFilesList = truststoreFilesListProvider.getTruststoreFilesList(truststorePaths, truststorePasswordPaths); - assertThat(truststoreFilesList.size()).isEqualTo(3); - assertCorrectJksTruststore(truststoreFilesList.get(0), TRUSTSTORE_JKS_PATH); - assertCorrectP12Truststore(truststoreFilesList.get(1), TRUSTSTORE_P12_PATH); - assertCorrectPemTruststore(truststoreFilesList.get(2), TRUSTSTORE_PEM_PATH); - } - - private void assertCorrectJksTruststore(Truststore truststore, String truststorePath) { - assertCorrectTypeAndTruststorePath(truststore, truststorePath, JavaTruststore.class); - } - - private void assertCorrectP12Truststore(Truststore truststore, String truststorePath) { - assertCorrectTypeAndTruststorePath(truststore, truststorePath, JavaTruststore.class); - } - - private void assertCorrectPemTruststore(Truststore truststore, String truststorePath) { - assertCorrectTypeAndTruststorePath(truststore, truststorePath, PemTruststore.class); - } - - private void assertCorrectTypeAndTruststorePath(Truststore truststore, String truststorePath, Class<?> truststoreType) { - assertThat(truststore).isInstanceOf(truststoreType); - assertThat(truststore.getFile()).isEqualTo(new File(truststorePath)); - } - -} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/path/PathValidatorTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/path/PathValidatorTest.java deleted file mode 100644 index a11bb232..00000000 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/path/PathValidatorTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.path; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import static org.assertj.core.api.Assertions.assertThat; - -class PathValidatorTest { - - private final PathValidator validator = new PathValidator(); - - @ParameterizedTest() - @ValueSource(strings = {"/opt/app/truststore.pem", "/opt/app/truststore.jks", - "/opt/app/truststore.p12", "/truststore.pem"}) - void shouldAcceptValidTruststorePaths(String path) { - assertThat(validator.isTruststorePathValid(path)).isTrue(); - } - - @ParameterizedTest() - @ValueSource(strings = {"/opt/app/truststore.pass", "/opt/app/truststore.invalid", "/", - "truststore", "opt/app/truststore.p12", "/?.pem", "/.pem"}) - void shouldRejectInValidTruststorePaths(String path) { - assertThat(validator.isTruststorePathValid(path)).isFalse(); - } - - @ParameterizedTest() - @ValueSource(strings = {"", "/opt/app/truststore.pass", "/truststore.pass"}) - void shouldAcceptValidTruststorePasswordPaths(String path) { - assertThat(validator.isTruststorePasswordPathValid(path)).isTrue(); - } - - @ParameterizedTest() - @ValueSource(strings = {"/opt/app/truststore.pem", "/opt/app/truststore.jks", - "/opt/app/truststore.p12", "/", "truststore", "opt/app/truststore.p12", "/?.pass", "/.pass"}) - void shouldRejectInValidTruststorePasswordPaths(String path) { - assertThat(validator.isTruststorePasswordPathValid(path)).isFalse(); - } - -} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/path/TruststoresPathsProviderTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/path/TruststoresPathsProviderTest.java deleted file mode 100644 index 38422d5c..00000000 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/certification/path/TruststoresPathsProviderTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.certification.path; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.when; -import static org.onap.oom.truststoremerger.api.ConfigurationEnvs.TRUSTSTORES_PATHS_ENV; -import static org.onap.oom.truststoremerger.api.ConfigurationEnvs.TRUSTSTORES_PASSWORDS_PATHS_ENV; - - -@ExtendWith(MockitoExtension.class) -class TruststoresPathsProviderTest { - - private static final String VALID_TRUSTSTORES = "/opt/app/certificates/truststore.jks:/opt/app/certificates/truststore.pem"; - private static final String VALID_TRUSTSTORES_PASSWORDS = "/opt/app/certificates/truststore.pass:"; - private static final String INVALID_TRUSTSTORES = "/opt/app/certificates/truststore.jks:/opt/app/certificates/truststore.invalid"; - private static final String INVALID_TRUSTSTORES_PASSWORDS = "/opt/app/certificates/truststore.pass:/.pass"; - - @Mock - private EnvProvider envProvider; - private TruststoresPathsProvider truststoresPathsProvider; - - @BeforeEach - void setUp() { - truststoresPathsProvider = new TruststoresPathsProvider(envProvider, new PathValidator()); - } - - @Test - void shouldReturnCorrectListWhenTruststoresValid() throws TruststoresPathsProviderException { - mockTruststoresEnv(VALID_TRUSTSTORES); - - assertThat(truststoresPathsProvider.getTruststores()) - .contains("/opt/app/certificates/truststore.jks", - "/opt/app/certificates/truststore.pem"); - } - - @Test - void shouldReturnCorrectListWhenTruststoresPasswordsValid() throws TruststoresPathsProviderException { - mockTruststoresPasswordsEnv(VALID_TRUSTSTORES_PASSWORDS); - - assertThat(truststoresPathsProvider.getTruststoresPasswords()) - .contains("/opt/app/certificates/truststore.pass", - ""); - } - - @Test - void shouldThrowExceptionWhenTruststoresEmpty() { - mockTruststoresEnv(""); - - assertThatExceptionOfType(TruststoresPathsProviderException.class) - .isThrownBy(truststoresPathsProvider::getTruststores); - } - - @Test - void shouldThrowExceptionWhenOneOfTruststoresPathsInvalid() { - mockTruststoresEnv(INVALID_TRUSTSTORES); - - assertThatExceptionOfType(TruststoresPathsProviderException.class) - .isThrownBy(truststoresPathsProvider::getTruststores); - } - - @Test - void shouldThrowExceptionWhenOneOfTruststorePasswordPathsInvalid() { - mockTruststoresPasswordsEnv(INVALID_TRUSTSTORES_PASSWORDS); - - assertThatExceptionOfType(TruststoresPathsProviderException.class) - .isThrownBy(truststoresPathsProvider::getTruststoresPasswords); - } - - private void mockTruststoresEnv(String truststores) { - mockEnv(truststores, TRUSTSTORES_PATHS_ENV); - } - - private void mockTruststoresPasswordsEnv(String truststoresPasswords) { - mockEnv(truststoresPasswords, TRUSTSTORES_PASSWORDS_PATHS_ENV); - } - - private void mockEnv(String envValue, String envName) { - when(envProvider.getEnv(envName)) - .thenReturn(Optional.of(envValue)); - } -} diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationFactoryTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationFactoryTest.java deleted file mode 100644 index 43b7b9e1..00000000 --- a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationFactoryTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/*============LICENSE_START======================================================= - * oom-truststore-merger - * ================================================================================ - * 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.truststoremerger.configuration; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.onap.oom.truststoremerger.certification.path.TruststoresPathsProvider; -import org.onap.oom.truststoremerger.certification.path.TruststoresPathsProviderException; - -import java.util.ArrayList; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.when; - -@ExtendWith(MockitoExtension.class) -class MergerConfigurationFactoryTest { - - private static final String BASE_TRUSTSTORE_PATH = "/opt/app/truststore_"; - private static final String TRUSTSTORE_EXTENSION = ".jks"; - private static final String PASSWORD_EXTENSION = ".pass"; - - @Mock - private TruststoresPathsProvider pathsProvider; - private MergerConfigurationFactory factory; - - @BeforeEach - void setUp() { - factory = new MergerConfigurationFactory(pathsProvider); - } - - @Test - void shouldReturnConfigurationWithCorrectPaths() throws TruststoresPathsProviderException, MergerConfigurationException { - int numberOfPaths = 5; - List<String> truststoresPaths = createListOfPathsWithExtension(numberOfPaths, TRUSTSTORE_EXTENSION); - List<String> truststorePasswordPaths = createListOfPathsWithExtension(numberOfPaths, PASSWORD_EXTENSION); - mockPaths(truststoresPaths, truststorePasswordPaths); - - MergerConfiguration configuration = factory.createConfiguration(); - - assertThat(configuration.getTruststoreFilePaths()).containsAll(truststoresPaths); - assertThat(configuration.getTruststoreFilePasswordPaths()).containsAll(truststorePasswordPaths); - } - - @Test - void shouldThrowExceptionWhenTruststoresLenghtDifferentThanTruststoresPasswordsLength() throws TruststoresPathsProviderException { - int numberOfTruststores = 5; - int numberOfTruststoresPasswords = 4; - List<String> truststoresPaths = createListOfPathsWithExtension(numberOfTruststores, TRUSTSTORE_EXTENSION); - List<String> truststorePasswordPaths = createListOfPathsWithExtension(numberOfTruststoresPasswords, PASSWORD_EXTENSION); - mockPaths(truststoresPaths, truststorePasswordPaths); - - assertThatExceptionOfType(MergerConfigurationException.class) - .isThrownBy(factory::createConfiguration); - } - - private void mockPaths(List<String> truststores, List<String> truststoresPasswords) throws TruststoresPathsProviderException { - mockTruststores(truststores); - mockTruststoresPasswords(truststoresPasswords); - } - - private void mockTruststores(List<String> truststores) throws TruststoresPathsProviderException { - when(pathsProvider.getTruststores()).thenReturn(truststores); - } - - private void mockTruststoresPasswords(List<String> truststoresPasswords) throws TruststoresPathsProviderException { - when(pathsProvider.getTruststoresPasswords()).thenReturn(truststoresPasswords); - } - - private List<String> createListOfPathsWithExtension(int numberOfPaths, String password_extension) { - List<String> paths = new ArrayList<>(); - while (numberOfPaths-- > 0) { - paths.add(BASE_TRUSTSTORE_PATH + numberOfPaths + password_extension); - } - return paths; - } -} diff --git a/trustStoreMerger/src/test/resources/keystore.pass b/trustStoreMerger/src/test/resources/keystore.pass new file mode 100644 index 00000000..665ff8e6 --- /dev/null +++ b/trustStoreMerger/src/test/resources/keystore.pass @@ -0,0 +1 @@ +Foh49MJNYI7S_pEzE9gvUDSu
\ No newline at end of file diff --git a/version.properties b/version.properties index 00ef5645..358e99ce 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ -major=1 -minor=2 +major=2 +minor=0 patch=0 base_version=${major}.${minor}.${patch} release_version=${base_version} |