From b8c4e6867d6b26652f4382e93665c220769cdc9f Mon Sep 17 00:00:00 2001 From: baniewsk Date: Wed, 29 Jul 2020 16:01:27 +0200 Subject: Removing AAF references from Cert-Service in OOM repo. Certificates regenerated External files (from legacy AAF) removed Still left: * Sonar link, * Link to documentation, * Names of K8s resources in RTD documentation, * Link to CSITs Issue-ID: OOM-2526 Signed-off-by: Pawel Baniewski Change-Id: I675f7485160b9b8e46e9ea573550e62ed28ca607 --- certServiceClient/Dockerfile | 4 +- certServiceClient/README.md | 6 +- certServiceClient/pom.xml | 16 +- .../aaf/certservice/client/AppExitHandler.java | 34 ---- .../aaf/certservice/client/CertServiceClient.java | 93 ---------- .../org/onap/aaf/certservice/client/MainApp.java | 28 --- .../aaf/certservice/client/api/ExitStatus.java | 51 ----- .../certservice/client/api/ExitableException.java | 32 ---- .../certification/ArtifactsCreatorProvider.java | 66 ------- .../client/certification/CsrFactory.java | 153 --------------- .../EncryptionAlgorithmConstants.java | 38 ---- .../client/certification/KeyPairFactory.java | 56 ------ .../certification/PrivateKeyToPemEncoder.java | 50 ----- .../certification/conversion/ArtifactsCreator.java | 30 --- .../conversion/ConvertedArtifactsCreator.java | 92 --------- .../ConvertedArtifactsCreatorFactory.java | 37 ---- .../client/certification/conversion/Password.java | 44 ----- .../conversion/PemArtifactsCreator.java | 63 ------- .../certification/conversion/PemConverter.java | 138 -------------- .../conversion/RandomPasswordGenerator.java | 52 ------ .../conversion/StoreEntryOperation.java | 34 ---- .../exception/CertFileWriterException.java | 35 ---- .../exception/CsrGenerationException.java | 35 ---- .../exception/KeyPairGenerationException.java | 36 ---- .../exception/PemConversionException.java | 40 ---- .../exception/PkEncodingException.java | 35 ---- .../certification/writer/CertFileWriter.java | 62 ------- .../certservice/client/common/Base64Encoder.java | 28 --- .../configuration/ClientConfigurationEnvs.java | 29 --- .../client/configuration/CsrConfigurationEnvs.java | 31 ---- .../client/configuration/EnvProvider.java | 38 ---- .../client/configuration/EnvsForClient.java | 51 ----- .../client/configuration/EnvsForCsr.java | 59 ------ .../client/configuration/EnvsForTls.java | 47 ----- .../client/configuration/TlsConfigurationEnvs.java | 28 --- .../exception/ClientConfigurationException.java | 36 ---- .../exception/CsrConfigurationException.java | 36 ---- .../exception/TlsConfigurationException.java | 36 ---- .../factory/AbstractConfigurationFactory.java | 77 -------- .../factory/ClientConfigurationFactory.java | 76 -------- .../factory/CsrConfigurationFactory.java | 77 -------- .../configuration/factory/SslContextFactory.java | 85 --------- .../configuration/model/ClientConfiguration.java | 99 ---------- .../configuration/model/ConfigurationModel.java | 24 --- .../configuration/model/CsrConfiguration.java | 111 ----------- .../httpclient/CloseableHttpsClientProvider.java | 51 ----- .../certservice/client/httpclient/HttpClient.java | 111 ----------- .../exception/CertServiceApiResponseException.java | 41 ---- .../httpclient/exception/HttpClientException.java | 37 ---- .../httpclient/model/CertServiceResponse.java | 44 ----- .../httpclient/model/ErrorCertServiceResponse.java | 35 ---- .../oom/certservice/client/AppExitHandler.java | 34 ++++ .../oom/certservice/client/CertServiceClient.java | 93 ++++++++++ .../org/onap/oom/certservice/client/MainApp.java | 28 +++ .../oom/certservice/client/api/ExitStatus.java | 51 +++++ .../certservice/client/api/ExitableException.java | 32 ++++ .../certification/ArtifactsCreatorProvider.java | 66 +++++++ .../client/certification/CsrFactory.java | 153 +++++++++++++++ .../EncryptionAlgorithmConstants.java | 38 ++++ .../client/certification/KeyPairFactory.java | 56 ++++++ .../certification/PrivateKeyToPemEncoder.java | 50 +++++ .../certification/conversion/ArtifactsCreator.java | 30 +++ .../conversion/ConvertedArtifactsCreator.java | 92 +++++++++ .../ConvertedArtifactsCreatorFactory.java | 37 ++++ .../client/certification/conversion/Password.java | 44 +++++ .../conversion/PemArtifactsCreator.java | 63 +++++++ .../certification/conversion/PemConverter.java | 138 ++++++++++++++ .../conversion/RandomPasswordGenerator.java | 52 ++++++ .../conversion/StoreEntryOperation.java | 34 ++++ .../exception/CertFileWriterException.java | 35 ++++ .../exception/CsrGenerationException.java | 35 ++++ .../exception/KeyPairGenerationException.java | 36 ++++ .../exception/PemConversionException.java | 40 ++++ .../exception/PkEncodingException.java | 35 ++++ .../certification/writer/CertFileWriter.java | 62 +++++++ .../certservice/client/common/Base64Encoder.java | 28 +++ .../configuration/ClientConfigurationEnvs.java | 29 +++ .../client/configuration/CsrConfigurationEnvs.java | 31 ++++ .../client/configuration/EnvProvider.java | 38 ++++ .../client/configuration/EnvsForClient.java | 51 +++++ .../client/configuration/EnvsForCsr.java | 59 ++++++ .../client/configuration/EnvsForTls.java | 47 +++++ .../client/configuration/TlsConfigurationEnvs.java | 28 +++ .../exception/ClientConfigurationException.java | 36 ++++ .../exception/CsrConfigurationException.java | 36 ++++ .../exception/TlsConfigurationException.java | 36 ++++ .../factory/AbstractConfigurationFactory.java | 77 ++++++++ .../factory/ClientConfigurationFactory.java | 76 ++++++++ .../factory/CsrConfigurationFactory.java | 77 ++++++++ .../configuration/factory/SslContextFactory.java | 85 +++++++++ .../configuration/model/ClientConfiguration.java | 99 ++++++++++ .../configuration/model/ConfigurationModel.java | 24 +++ .../configuration/model/CsrConfiguration.java | 111 +++++++++++ .../httpclient/CloseableHttpsClientProvider.java | 51 +++++ .../certservice/client/httpclient/HttpClient.java | 111 +++++++++++ .../exception/CertServiceApiResponseException.java | 41 ++++ .../httpclient/exception/HttpClientException.java | 37 ++++ .../httpclient/model/CertServiceResponse.java | 44 +++++ .../httpclient/model/ErrorCertServiceResponse.java | 35 ++++ certServiceClient/src/main/resources/log4j2.xml | 2 +- .../client/CerServiceRequestTestData.java | 89 --------- .../certservice/client/CertServiceClientTest.java | 49 ----- .../ArtifactsCreatorProviderTest.java | 73 -------- .../client/certification/CsrFactoryTest.java | 56 ------ .../client/certification/KeyPairFactoryTest.java | 53 ------ .../certification/PrivateKeyToPemEncoderTest.java | 66 ------- .../conversion/ConvertedArtifactsCreatorTest.java | 125 ------------- .../conversion/PemArtifactsCreatorTest.java | 58 ------ .../certification/conversion/PemConverterTest.java | 206 --------------------- .../conversion/RandomPasswordGeneratorTest.java | 33 ---- .../certification/writer/CertFileWriterTest.java | 76 -------- .../client/configuration/EnvProviderTest.java | 65 ------- .../client/configuration/EnvsForCsrTest.java | 201 -------------------- .../client/configuration/EnvsForTlsTest.java | 133 ------------- .../exception/TlsConfigurationExceptionTest.java | 48 ----- .../factory/AbstractConfigurationFactoryTest.java | 93 ---------- .../factory/ClientConfigurationFactoryTest.java | 155 ---------------- .../factory/CsrConfigurationFactoryTest.java | 186 ------------------- .../factory/SslContextFactoryTest.java | 197 -------------------- .../client/httpclient/HttpClientTest.java | 144 -------------- .../client/CerServiceRequestTestData.java | 89 +++++++++ .../certservice/client/CertServiceClientTest.java | 49 +++++ .../ArtifactsCreatorProviderTest.java | 73 ++++++++ .../client/certification/CsrFactoryTest.java | 56 ++++++ .../client/certification/KeyPairFactoryTest.java | 53 ++++++ .../certification/PrivateKeyToPemEncoderTest.java | 66 +++++++ .../conversion/ConvertedArtifactsCreatorTest.java | 125 +++++++++++++ .../conversion/PemArtifactsCreatorTest.java | 58 ++++++ .../certification/conversion/PemConverterTest.java | 206 +++++++++++++++++++++ .../conversion/RandomPasswordGeneratorTest.java | 33 ++++ .../certification/writer/CertFileWriterTest.java | 76 ++++++++ .../client/configuration/EnvProviderTest.java | 65 +++++++ .../client/configuration/EnvsForCsrTest.java | 201 ++++++++++++++++++++ .../client/configuration/EnvsForTlsTest.java | 133 +++++++++++++ .../exception/TlsConfigurationExceptionTest.java | 48 +++++ .../factory/AbstractConfigurationFactoryTest.java | 93 ++++++++++ .../factory/ClientConfigurationFactoryTest.java | 155 ++++++++++++++++ .../factory/CsrConfigurationFactoryTest.java | 186 +++++++++++++++++++ .../factory/SslContextFactoryTest.java | 197 ++++++++++++++++++++ .../client/httpclient/HttpClientTest.java | 144 ++++++++++++++ 140 files changed, 4741 insertions(+), 4741 deletions(-) delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/AppExitHandler.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/CertServiceClient.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/MainApp.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitStatus.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitableException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProvider.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/CsrFactory.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/EncryptionAlgorithmConstants.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/KeyPairFactory.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoder.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ArtifactsCreator.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreator.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorFactory.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/Password.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreator.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemConverter.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGenerator.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/StoreEntryOperation.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CertFileWriterException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CsrGenerationException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/KeyPairGenerationException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PemConversionException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PkEncodingException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriter.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/common/Base64Encoder.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/ClientConfigurationEnvs.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/CsrConfigurationEnvs.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvProvider.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForClient.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForCsr.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForTls.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/TlsConfigurationEnvs.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/ClientConfigurationException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/CsrConfigurationException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactory.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactory.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactory.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactory.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ClientConfiguration.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ConfigurationModel.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/CsrConfiguration.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/CloseableHttpsClientProvider.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/HttpClient.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/CertServiceApiResponseException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/HttpClientException.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/CertServiceResponse.java delete mode 100644 certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/ErrorCertServiceResponse.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/AppExitHandler.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/CertServiceClient.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/MainApp.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/api/ExitStatus.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/api/ExitableException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProvider.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/CsrFactory.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/EncryptionAlgorithmConstants.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/KeyPairFactory.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoder.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ArtifactsCreator.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreator.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorFactory.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/Password.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreator.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/PemConverter.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGenerator.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/StoreEntryOperation.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/CertFileWriterException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/CsrGenerationException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/KeyPairGenerationException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/PemConversionException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/PkEncodingException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/writer/CertFileWriter.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/common/Base64Encoder.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/ClientConfigurationEnvs.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/CsrConfigurationEnvs.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvProvider.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForClient.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForCsr.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForTls.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/TlsConfigurationEnvs.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/ClientConfigurationException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/CsrConfigurationException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactory.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactory.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactory.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactory.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/ClientConfiguration.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/ConfigurationModel.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/CsrConfiguration.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/CloseableHttpsClientProvider.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/HttpClient.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/exception/CertServiceApiResponseException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/exception/HttpClientException.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/model/CertServiceResponse.java create mode 100644 certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/model/ErrorCertServiceResponse.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/CerServiceRequestTestData.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProviderTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/CsrFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/KeyPairFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoderTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreatorTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemConverterTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriterTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvProviderTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForCsrTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForTlsTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactoryTest.java delete mode 100644 certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/CerServiceRequestTestData.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/CertServiceClientTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProviderTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/CsrFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/KeyPairFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoderTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreatorTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemConverterTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/writer/CertFileWriterTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvProviderTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForCsrTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForTlsTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java create mode 100644 certServiceClient/src/test/java/org/onap/oom/certservice/client/httpclient/HttpClientTest.java (limited to 'certServiceClient') diff --git a/certServiceClient/Dockerfile b/certServiceClient/Dockerfile index 9da47295..f6d96dfd 100644 --- a/certServiceClient/Dockerfile +++ b/certServiceClient/Dockerfile @@ -8,6 +8,6 @@ RUN chown -R certServiceClient:certServiceClient /var/log USER certServiceClient:certServiceClient -COPY target/aaf-certservice-client-${VERSION}.jar ./opt/onap/aaf/certservice/aaf-certservice-client.jar +COPY target/oom-certservice-client-${VERSION}.jar ./opt/onap/oom/certservice/oom-certservice-client.jar -ENTRYPOINT ["java","-jar","./opt/onap/aaf/certservice/aaf-certservice-client.jar"] +ENTRYPOINT ["java","-jar","./opt/onap/oom/certservice/oom-certservice-client.jar"] diff --git a/certServiceClient/README.md b/certServiceClient/README.md index b3005345..277f7a1c 100644 --- a/certServiceClient/README.md +++ b/certServiceClient/README.md @@ -18,7 +18,7 @@ mvn clean install -P docker ### Nexus container image ``` -nexus3.onap.org:10001/onap/org.onap.aaf.certservice.aaf-certservice-client:latest +nexus3.onap.org:10001/onap/org.onap.oom.certservice.oom-certservice-client:latest ``` ### Running local client application as standalone docker container @@ -33,11 +33,11 @@ Information how to run you can find in CertService main README and official docu path: ``` -var/log/onap/aaf/certservice-client/certservice-client.log +var/log/onap/oom/certservice-client/certservice-client.log ``` ### Logs in Docker container ``` -docker logs aaf-certservice-client +docker logs oom-certservice-client ``` ###Exit codes ``` diff --git a/certServiceClient/pom.xml b/certServiceClient/pom.xml index e176b18e..c05ecc46 100644 --- a/certServiceClient/pom.xml +++ b/certServiceClient/pom.xml @@ -3,16 +3,16 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - aaf-certservice - org.onap.aaf.certservice + oom-certservice + org.onap.oom.platform.cert-service 1.2.0-SNAPSHOT 4.0.0 - aaf-certservice-client + oom-certservice-client 1.2.0-SNAPSHOT - aaf-certservice-client - AAF Certification Service Api Client + oom-certservice-client + OOM Certification Service Api Client jar @@ -70,7 +70,7 @@ - org.onap.aaf.certservice.client.MainApp + org.onap.oom.certservice.client.MainApp @@ -125,12 +125,12 @@ ecomp-releases - AAF Release Repository + OOM Release Repository ${nexusproxy}${releaseNexusPath} ecomp-snapshots - AAF Snapshot Repository + OOM Snapshot Repository ${nexusproxy}${snapshotNexusPath} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/AppExitHandler.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/AppExitHandler.java deleted file mode 100644 index af30ff3e..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/AppExitHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -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: {}", - exitStatus.getExitCodeValue(), exitStatus.getMessage()); - System.exit(exitStatus.getExitCodeValue()); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/CertServiceClient.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/CertServiceClient.java deleted file mode 100644 index 56c355e4..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/CertServiceClient.java +++ /dev/null @@ -1,93 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client; - -import org.onap.aaf.certservice.client.api.ExitableException; -import org.onap.aaf.certservice.client.certification.ArtifactsCreatorProvider; -import org.onap.aaf.certservice.client.certification.CsrFactory; -import org.onap.aaf.certservice.client.certification.KeyPairFactory; -import org.onap.aaf.certservice.client.certification.PrivateKeyToPemEncoder; -import org.onap.aaf.certservice.client.common.Base64Encoder; -import org.onap.aaf.certservice.client.configuration.EnvsForClient; -import org.onap.aaf.certservice.client.configuration.EnvsForCsr; -import org.onap.aaf.certservice.client.configuration.EnvsForTls; -import org.onap.aaf.certservice.client.configuration.factory.ClientConfigurationFactory; -import org.onap.aaf.certservice.client.configuration.factory.CsrConfigurationFactory; -import org.onap.aaf.certservice.client.configuration.factory.SslContextFactory; -import org.onap.aaf.certservice.client.configuration.model.ClientConfiguration; -import org.onap.aaf.certservice.client.configuration.model.CsrConfiguration; -import org.onap.aaf.certservice.client.httpclient.CloseableHttpsClientProvider; -import org.onap.aaf.certservice.client.httpclient.HttpClient; -import org.onap.aaf.certservice.client.httpclient.model.CertServiceResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.SSLContext; -import java.security.KeyPair; - -import static org.onap.aaf.certservice.client.api.ExitStatus.SUCCESS; -import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.KEY_SIZE; -import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM; - -public class CertServiceClient { - - private static final Logger LOGGER = LoggerFactory.getLogger(CertServiceClient.class); - - private AppExitHandler appExitHandler; - - public CertServiceClient(AppExitHandler appExitHandler) { - this.appExitHandler = appExitHandler; - } - - public void run() { - KeyPairFactory keyPairFactory = new KeyPairFactory(RSA_ENCRYPTION_ALGORITHM, KEY_SIZE); - PrivateKeyToPemEncoder pkEncoder = new PrivateKeyToPemEncoder(); - Base64Encoder base64Encoder = new Base64Encoder(); - try { - ClientConfiguration clientConfiguration = new ClientConfigurationFactory(new EnvsForClient()).create(); - CsrConfiguration csrConfiguration = new CsrConfigurationFactory(new EnvsForCsr()).create(); - KeyPair keyPair = keyPairFactory.create(); - CsrFactory csrFactory = new CsrFactory(csrConfiguration); - SSLContext sslContext = new SslContextFactory(new EnvsForTls()).create(); - - CloseableHttpsClientProvider provider = new CloseableHttpsClientProvider( - sslContext, clientConfiguration.getRequestTimeout()); - HttpClient httpClient = new HttpClient(provider, clientConfiguration.getUrlToCertService()); - - CertServiceResponse certServiceData = - httpClient.retrieveCertServiceData( - clientConfiguration.getCaName(), - base64Encoder.encode(csrFactory.createCsrInPem(keyPair)), - base64Encoder.encode(pkEncoder.encodePrivateKeyToPem(keyPair.getPrivate()))); - - ArtifactsCreatorProvider - .get(clientConfiguration.getOutputType(), - clientConfiguration.getCertsOutputPath()) - .create(certServiceData.getCertificateChain(), - certServiceData.getTrustedCertificates(), - keyPair.getPrivate()); - - } catch (ExitableException e) { - LOGGER.error("Cert Service Client fails in execution: ", e); - appExitHandler.exit(e.applicationExitStatus()); - } - appExitHandler.exit(SUCCESS); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/MainApp.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/MainApp.java deleted file mode 100644 index 6a29241f..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/MainApp.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client; - -public class MainApp { - public static void main(String[] args) { - CertServiceClient certServiceClient = new CertServiceClient(new AppExitHandler()); - certServiceClient.run(); - } -} \ No newline at end of file diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitStatus.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitStatus.java deleted file mode 100644 index a84485eb..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitStatus.java +++ /dev/null @@ -1,51 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.api; - -public enum ExitStatus { - - SUCCESS(0, "Success"), - CLIENT_CONFIGURATION_EXCEPTION(1, "Invalid client configuration"), - CSR_CONFIGURATION_EXCEPTION(2, "Invalid CSR configuration"), - KEY_PAIR_GENERATION_EXCEPTION(3, "Fail in key pair generation"), - CSR_GENERATION_EXCEPTION(4, "Fail in CSR generation"), - CERT_SERVICE_API_CONNECTION_EXCEPTION(5, "CertService HTTP unsuccessful response"), - HTTP_CLIENT_EXCEPTION(6, "Internal HTTP Client connection problem"), - PEM_CONVERSION_EXCEPTION(7, "Fail in PEM conversion"), - PK_TO_PEM_ENCODING_EXCEPTION(8, "Fail in Private Key to PEM Encoding"), - TLS_CONFIGURATION_EXCEPTION(9, "Invalid TLS configuration"), - FILE_CREATION_EXCEPTION(10, "File could not be created"); - - private final int value; - private final String message; - - ExitStatus(int value, String message) { - this.value = value; - this.message = message; - } - - public int getExitCodeValue() { - return value; - } - - public String getMessage() { - return message; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitableException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitableException.java deleted file mode 100644 index 3a7a542b..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitableException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.api; - -public abstract class ExitableException extends Exception { - public ExitableException(Throwable cause) { - super(cause); - } - - public ExitableException(String message) { - super(message); - } - - public abstract ExitStatus applicationExitStatus(); -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProvider.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProvider.java deleted file mode 100644 index 954f3d30..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProvider.java +++ /dev/null @@ -1,66 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification; - -import org.onap.aaf.certservice.client.certification.conversion.ArtifactsCreator; -import org.onap.aaf.certservice.client.certification.conversion.ConvertedArtifactsCreatorFactory; -import org.onap.aaf.certservice.client.certification.conversion.PemArtifactsCreator; -import org.onap.aaf.certservice.client.certification.writer.CertFileWriter; - -public enum ArtifactsCreatorProvider { - P12("PKCS12") { - @Override - ArtifactsCreator create(String destPath) { - return ConvertedArtifactsCreatorFactory.createConverter(destPath, getExtension(), getKeyStoreType()); - } - }, - JKS("JKS") { - @Override - ArtifactsCreator create(String destPath) { - return ConvertedArtifactsCreatorFactory.createConverter(destPath, getExtension(), getKeyStoreType()); - } - }, - PEM("PEM") { - @Override - ArtifactsCreator create(String destPath) { - return new PemArtifactsCreator(CertFileWriter.createWithDir(destPath), new PrivateKeyToPemEncoder()); - } - }; - - private final String keyStoreType; - - ArtifactsCreatorProvider(String keyStoreType) { - this.keyStoreType = keyStoreType; - } - - public static ArtifactsCreator get(String outputType, String destPath) { - return valueOf(outputType).create(destPath); - } - - String getKeyStoreType() { - return keyStoreType; - } - - String getExtension() { - return this.toString().toLowerCase(); - } - - abstract ArtifactsCreator create(String destPath); -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/CsrFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/CsrFactory.java deleted file mode 100644 index 0faf5cab..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/CsrFactory.java +++ /dev/null @@ -1,153 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification; - -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.ExtensionsGenerator; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.openssl.jcajce.JcaPEMWriter; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; -import org.onap.aaf.certservice.client.certification.exception.CsrGenerationException; -import org.onap.aaf.certservice.client.configuration.model.CsrConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.security.auth.x500.X500Principal; -import java.io.IOException; -import java.io.StringWriter; -import java.security.KeyPair; -import java.util.Optional; - -import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.COMMON_NAME; -import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.COUNTRY; -import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.LOCATION; -import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.ORGANIZATION; -import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.ORGANIZATION_UNIT; -import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.SIGN_ALGORITHM; -import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.STATE; - - -public class CsrFactory { - - private static final Logger LOGGER = LoggerFactory.getLogger(CsrFactory.class); - private static final String SANS_DELIMITER = ":"; - private final CsrConfiguration configuration; - - - public CsrFactory(CsrConfiguration configuration) { - this.configuration = configuration; - } - - - public String createCsrInPem(KeyPair keyPair) throws CsrGenerationException { - LOGGER.info("Creation of CSR has been started with following parameters: {}", configuration.toString()); - String csrParameters = getMandatoryParameters().append(getOptionalParameters()).toString(); - X500Principal subject = new X500Principal(csrParameters); - PKCS10CertificationRequest request = createPkcs10Csr(subject, keyPair); - - LOGGER.info("Creation of CSR has been completed successfully"); - return convertPkcs10CsrToPem(request); - } - - private StringBuilder getMandatoryParameters() { - return new StringBuilder(String.format("%s=%s, %s=%s, %s=%s, %s=%s", - COMMON_NAME, configuration.getCommonName(), - COUNTRY, configuration.getCountry(), - STATE, configuration.getState(), - ORGANIZATION, configuration.getOrganization())); - } - - private String getOptionalParameters() { - StringBuilder optionalParameters = new StringBuilder(); - Optional.ofNullable(configuration.getOrganizationUnit()) - .filter(CsrFactory::isParameterPresent) - .map(unit -> optionalParameters.append(String.format(", %s=%s", ORGANIZATION_UNIT, unit))); - Optional.ofNullable(configuration.getLocation()) - .filter(CsrFactory::isParameterPresent) - .map(location -> optionalParameters.append(String.format(", %s=%s", LOCATION, location))); - return optionalParameters.toString(); - } - - private PKCS10CertificationRequest createPkcs10Csr(X500Principal subject, KeyPair keyPair) throws CsrGenerationException { - JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic()); - - if (isParameterPresent(configuration.getSans())) { - builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, generateSansExtension()); - } - - return builder.build(getContentSigner(keyPair)); - } - - private ContentSigner getContentSigner(KeyPair keyPair) throws CsrGenerationException { - ContentSigner contentSigner; - try { - contentSigner = new JcaContentSignerBuilder(SIGN_ALGORITHM).build(keyPair.getPrivate()); - } catch (OperatorCreationException e) { - LOGGER.error("Creation of PKCS10Csr failed, exception message: {}", e.getMessage()); - throw new CsrGenerationException(e); - - } - return contentSigner; - } - - private String convertPkcs10CsrToPem(PKCS10CertificationRequest request) throws CsrGenerationException { - final StringWriter stringWriter = new StringWriter(); - try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) { - LOGGER.info("Conversion of CSR to PEM has been started"); - pemWriter.writeObject(request); - } catch (IOException e) { - LOGGER.error("Conversion to PEM failed, exception message: {}", e.getMessage()); - throw new CsrGenerationException(e); - } - return stringWriter.toString(); - } - - private Extensions generateSansExtension() throws CsrGenerationException { - ExtensionsGenerator generator = new ExtensionsGenerator(); - try { - generator.addExtension(Extension.subjectAlternativeName, false, createGeneralNames()); - } catch (IOException e) { - LOGGER.error("Generation of SANs parameter failed, exception message: {}", e.getMessage()); - throw new CsrGenerationException(e); - } - return generator.generate(); - } - - private GeneralNames createGeneralNames() { - String[] sansTable = this.configuration.getSans().split(SANS_DELIMITER); - int length = sansTable.length; - GeneralName[] generalNames = new GeneralName[length]; - for (int i = 0; i < length; i++) { - generalNames[i] = new GeneralName(GeneralName.dNSName, sansTable[i]); - } - return new GeneralNames(generalNames); - } - - private static Boolean isParameterPresent(String parameter) { - return parameter != null && !"".equals(parameter); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/EncryptionAlgorithmConstants.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/EncryptionAlgorithmConstants.java deleted file mode 100644 index 63ede568..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/EncryptionAlgorithmConstants.java +++ /dev/null @@ -1,38 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification; - -public final class EncryptionAlgorithmConstants { - - private EncryptionAlgorithmConstants() { - } - - public static final String RSA_ENCRYPTION_ALGORITHM = "RSA"; - public static final String SIGN_ALGORITHM = "SHA1withRSA"; - public static final int KEY_SIZE = 2048; - - public static final String COMMON_NAME = "CN"; - public static final String ORGANIZATION = "O"; - public static final String ORGANIZATION_UNIT = "OU"; - public static final String LOCATION = "L"; - public static final String STATE = "ST"; - public static final String COUNTRY = "C"; - -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/KeyPairFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/KeyPairFactory.java deleted file mode 100644 index e997cd0d..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/KeyPairFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification; - -import org.onap.aaf.certservice.client.certification.exception.KeyPairGenerationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; - -public class KeyPairFactory { - - private static final Logger LOGGER = LoggerFactory.getLogger(KeyPairFactory.class); - private final String encryptionAlgorithm; - private final int keySize; - - public KeyPairFactory(String encryptionAlgorithm, int keySize) { - this.encryptionAlgorithm = encryptionAlgorithm; - this.keySize = keySize; - } - - public KeyPair create() throws KeyPairGenerationException { - try { - LOGGER.info("KeyPair generation started with algorithm: {} and key size: {}", encryptionAlgorithm, keySize); - return createKeyPairGenerator().generateKeyPair(); - } catch (NoSuchAlgorithmException e) { - String errorMessage = String.format("Generation of KeyPair failed, exception message: %s", e.getMessage()); - throw new KeyPairGenerationException(errorMessage); - } - } - - private KeyPairGenerator createKeyPairGenerator() throws NoSuchAlgorithmException { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(encryptionAlgorithm); - keyPairGenerator.initialize(keySize); - return keyPairGenerator; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoder.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoder.java deleted file mode 100644 index fa6485e5..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoder.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification; - - -import org.bouncycastle.openssl.jcajce.JcaPEMWriter; -import org.bouncycastle.util.io.pem.PemObject; -import org.onap.aaf.certservice.client.certification.exception.PkEncodingException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.StringWriter; -import java.security.PrivateKey; - -public class PrivateKeyToPemEncoder { - - private static final Logger LOGGER = LoggerFactory.getLogger(PrivateKeyToPemEncoder.class); - private static final String PEM_OBJECT_TYPE = "RSA PRIVATE KEY"; - - public String encodePrivateKeyToPem(PrivateKey pk) throws PkEncodingException { - LOGGER.info("Attempt to encode private key to PEM"); - StringWriter stringWriter = new StringWriter(); - try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) { - pemWriter.writeObject(new PemObject(PEM_OBJECT_TYPE, pk.getEncoded())); - } catch (IOException e) { - LOGGER.error("Encode of private key to PEM failed. Exception message: {}", e.getMessage()); - throw new PkEncodingException(e); - } - return stringWriter.toString(); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ArtifactsCreator.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ArtifactsCreator.java deleted file mode 100644 index 428b85aa..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ArtifactsCreator.java +++ /dev/null @@ -1,30 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.onap.aaf.certservice.client.api.ExitableException; - -import java.security.PrivateKey; -import java.util.List; - -public interface ArtifactsCreator { - void create(List keystoreData, List truststoreData, PrivateKey privateKey) - throws ExitableException; -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreator.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreator.java deleted file mode 100644 index 4826732c..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreator.java +++ /dev/null @@ -1,92 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.onap.aaf.certservice.client.certification.exception.CertFileWriterException; -import org.onap.aaf.certservice.client.certification.exception.PemConversionException; -import org.onap.aaf.certservice.client.certification.writer.CertFileWriter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.security.PrivateKey; -import java.util.List; - -public class ConvertedArtifactsCreator implements ArtifactsCreator { - - private static final Logger LOGGER = LoggerFactory.getLogger(ConvertedArtifactsCreator.class); - private static final String CERTIFICATE_ALIAS = "certificate"; - private static final String TRUSTED_CERTIFICATE_ALIAS = "trusted-certificate-"; - private static final int PASSWORD_LENGTH = 24; - private static final String PASS_EXT = "pass"; - private static final String KEYSTORE = "keystore"; - private static final String TRUSTSTORE = "truststore"; - - private final String fileExtension; - private final RandomPasswordGenerator passwordGenerator; - private final PemConverter converter; - private final CertFileWriter fileWriter; - - ConvertedArtifactsCreator(CertFileWriter fileWriter, RandomPasswordGenerator passwordGenerator, - PemConverter converter, String fileExtension) { - this.passwordGenerator = passwordGenerator; - this.converter = converter; - this.fileWriter = fileWriter; - this.fileExtension = fileExtension; - } - - @Override - public void create(List keystoreData, List truststoreData, PrivateKey privateKey) - throws PemConversionException, CertFileWriterException { - createKeystore(keystoreData, privateKey); - createTruststore(truststoreData); - } - - private void createKeystore(List data, PrivateKey privateKey) - throws PemConversionException, CertFileWriterException { - Password password = passwordGenerator.generate(PASSWORD_LENGTH); - String keystoreArtifactName = getFilenameWithExtension(KEYSTORE, fileExtension); - String keystorePass = getFilenameWithExtension(KEYSTORE, PASS_EXT); - - LOGGER.debug("Attempt to create keystore files and saving data. File names: {}, {}", keystoreArtifactName, keystorePass); - - fileWriter.saveData(converter.convertKeystore(data, password, CERTIFICATE_ALIAS, privateKey), keystoreArtifactName); - fileWriter.saveData(getPasswordAsBytes(password), keystorePass); - } - - private void createTruststore(List data) - throws PemConversionException, CertFileWriterException { - Password password = passwordGenerator.generate(PASSWORD_LENGTH); - String truststoreArtifactName = getFilenameWithExtension(TRUSTSTORE, fileExtension); - String truststorePass = getFilenameWithExtension(TRUSTSTORE, PASS_EXT); - - LOGGER.debug("Attempt to create truststore files and saving data. File names: {}, {}", truststoreArtifactName, truststorePass); - - fileWriter.saveData(converter.convertTruststore(data, password, TRUSTED_CERTIFICATE_ALIAS), truststoreArtifactName); - fileWriter.saveData(getPasswordAsBytes(password), truststorePass); - } - - private byte[] getPasswordAsBytes(Password password) { - return password.getCurrentPassword().getBytes(); - } - - private String getFilenameWithExtension(String filename, String extension) { - return String.format("%s.%s", filename, extension); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorFactory.java deleted file mode 100644 index bda796eb..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorFactory.java +++ /dev/null @@ -1,37 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.onap.aaf.certservice.client.certification.writer.CertFileWriter; - -public class ConvertedArtifactsCreatorFactory { - - private ConvertedArtifactsCreatorFactory() { - } - - public static ConvertedArtifactsCreator createConverter(String destPath, String fileExtension, String keyStoreType) { - return new ConvertedArtifactsCreator( - CertFileWriter.createWithDir(destPath), - new RandomPasswordGenerator(), - new PemConverter(keyStoreType), - fileExtension); - } - -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/Password.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/Password.java deleted file mode 100644 index 6ea1a219..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/Password.java +++ /dev/null @@ -1,44 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -class Password { - // We are excluding this line in Sonar due to fact that - // PASSWORD_PATTERN does not contain password. This solution - // is safe. - private static final String PASSWORD_PATTERN = "[\\w$#]{16,}"; // NOSONAR - private final String currentPassword; - - Password(String currentPassword) { - this.currentPassword = currentPassword; - } - - String getCurrentPassword() { - return currentPassword; - } - - char[] toCharArray() { - return currentPassword.toCharArray(); - } - - boolean isCorrectPasswordPattern() { - return currentPassword.matches(PASSWORD_PATTERN); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreator.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreator.java deleted file mode 100644 index 4bec222f..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreator.java +++ /dev/null @@ -1,63 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.onap.aaf.certservice.client.certification.PrivateKeyToPemEncoder; -import org.onap.aaf.certservice.client.certification.exception.CertFileWriterException; -import org.onap.aaf.certservice.client.certification.exception.PkEncodingException; -import org.onap.aaf.certservice.client.certification.writer.CertFileWriter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.security.PrivateKey; -import java.util.List; - -public class PemArtifactsCreator implements ArtifactsCreator { - private static final Logger LOGGER = LoggerFactory.getLogger(PemArtifactsCreator.class); - - private static final String KEY_PEM = "key.pem"; - private static final String KEYSTORE_PEM = "keystore.pem"; - private static final String TRUSTSTORE_PEM = "truststore.pem"; - - private final CertFileWriter writer; - private final PrivateKeyToPemEncoder pkEncoder; - - public PemArtifactsCreator(CertFileWriter writer, PrivateKeyToPemEncoder pkEncoder) { - this.writer = writer; - this.pkEncoder = pkEncoder; - } - - @Override - public void create(List keystoreData, List truststoreData, PrivateKey privateKey) - throws PkEncodingException, CertFileWriterException { - LOGGER.debug("Attempt to create PEM private key file and saving data. File name: {}", KEY_PEM); - writer.saveData(pkEncoder.encodePrivateKeyToPem(privateKey).getBytes(), KEY_PEM); - - LOGGER.debug("Attempt to create PEM keystore file and saving data. File name: {}", KEYSTORE_PEM); - writer.saveData(getDataAsBytes(keystoreData), KEYSTORE_PEM); - - LOGGER.debug("Attempt to create PEM truststore file and saving data. File name: {}", TRUSTSTORE_PEM); - writer.saveData(getDataAsBytes(truststoreData), TRUSTSTORE_PEM); - } - - private byte[] getDataAsBytes(List data) { - return String.join("\n", data).getBytes(); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemConverter.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemConverter.java deleted file mode 100644 index 5e82c177..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemConverter.java +++ /dev/null @@ -1,138 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.openssl.PEMParser; -import org.onap.aaf.certservice.client.certification.exception.PemConversionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.StringReader; -import java.security.KeyStore; -import java.security.KeyStore.LoadStoreParameter; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.util.List; -import java.util.Optional; - -class PemConverter { - - private static final Logger LOGGER = LoggerFactory.getLogger(PemConverter.class); - private static final String PASSWORD_ERROR_MSG = "Password should be min. 16 chars long and should contain only alphanumeric characters and special characters like Underscore (_), Dollar ($) and Pound (#)"; - private static final LoadStoreParameter EMPTY_KEYSTORE_CONFIGURATION = null; - private final String keyStoreType; - - public PemConverter(String keyStoreType) { - this.keyStoreType = keyStoreType; - } - - byte[] convertKeystore(List certificateChain, Password password, String alias, PrivateKey privateKey) - throws PemConversionException { - LOGGER.info("Conversion of PEM certificates to " + keyStoreType + " keystore"); - return convert(certificateChain, password, certs -> getKeyStore(alias, password, certs, privateKey)); - } - - byte[] convertTruststore(List trustAnchors, Password password, String alias) - throws PemConversionException { - LOGGER.info("Conversion of PEM certificates to " + keyStoreType + " truststore"); - return convert(trustAnchors, password, certs -> getTrustStore(alias, certs)); - } - - private byte[] convert(List certificates, Password password, StoreEntryOperation operation) - throws PemConversionException { - checkPassword(password); - final Certificate[] X509Certificates = convertToCertificateArray(certificates); - return getKeyStoreBytes(password, operation, X509Certificates); - } - - private void checkPassword(Password password) throws PemConversionException { - if (!password.isCorrectPasswordPattern()) { - LOGGER.error(PASSWORD_ERROR_MSG); - throw new PemConversionException(PASSWORD_ERROR_MSG); - } - } - - private byte[] getKeyStoreBytes(Password password, StoreEntryOperation op, Certificate[] x509Certificates) - throws PemConversionException { - try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { - KeyStore ks = op.getStore(x509Certificates); - ks.store(bos, password.toCharArray()); - return bos.toByteArray(); - } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) { - LOGGER.error("Pem to " + keyStoreType + " converter failed, exception message: {}", e.getMessage()); - throw new PemConversionException(e); - } - } - - private KeyStore getKeyStore(String alias, Password password, Certificate[] certificates, PrivateKey privateKey) - throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { - KeyStore ks = getKeyStoreInstance(); - ks.setKeyEntry(alias, privateKey, password.toCharArray(), certificates); - return ks; - } - - private KeyStore getTrustStore(String alias, Certificate[] certificates) - throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { - KeyStore ks = getKeyStoreInstance(); - long index = 1L; - for (Certificate c : certificates) { - ks.setCertificateEntry(alias + index++, c); - } - return ks; - } - - private KeyStore getKeyStoreInstance() - throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { - KeyStore ks = KeyStore.getInstance(keyStoreType); - ks.load(EMPTY_KEYSTORE_CONFIGURATION); - return ks; - } - - private Certificate[] convertToCertificateArray(List certificates) - throws PemConversionException { - Certificate[] parsedCertificates = new Certificate[certificates.size()]; - for (String certificate : certificates) { - parsedCertificates[certificates.indexOf(certificate)] = parseCertificate(certificate); - } - return parsedCertificates; - } - - private Certificate parseCertificate(String certificate) throws PemConversionException { - try (PEMParser pem = new PEMParser(new StringReader(certificate))) { - X509CertificateHolder certHolder = Optional.ofNullable((X509CertificateHolder) pem.readObject()) - .orElseThrow( - () -> new PemConversionException("The certificate couldn't be parsed correctly. " + certificate)); - return new JcaX509CertificateConverter() - .setProvider(new BouncyCastleProvider()) - .getCertificate(certHolder); - } catch (IOException | CertificateException e) { - LOGGER.error("Certificates conversion failed, exception message: {}", e.getMessage()); - throw new PemConversionException(e); - } - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGenerator.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGenerator.java deleted file mode 100644 index 8ad85d2c..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGenerator.java +++ /dev/null @@ -1,52 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.apache.commons.lang3.RandomStringUtils; - -import java.security.SecureRandom; - -class RandomPasswordGenerator { - - private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; - private static final String NUMBERS = "0123456789"; - private static final String SPECIAL_CHARS = "_$#"; - private static final char[] SET_OF_CHARS = (ALPHA + ALPHA.toUpperCase() + NUMBERS + SPECIAL_CHARS).toCharArray(); - private static final char START_POSITION_IN_ASCII_CHARS = 0; - private static final char END_POSITION_IN_ASCII_CHARS = 0; - private static final boolean USE_LETTERS_ONLY = false; - private static final boolean USE_NUMBERS_ONLY = false; - - // We are excluding this line in Sonar due to fact that - //we are using new SecureRandom which provides - //cryptographic security - Password generate(int passwordLength) { - return new Password(RandomStringUtils.random(//NOSONAR - passwordLength, - START_POSITION_IN_ASCII_CHARS, - END_POSITION_IN_ASCII_CHARS, - USE_LETTERS_ONLY, - USE_NUMBERS_ONLY, - SET_OF_CHARS, - new SecureRandom()) - ); - } -} - diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/StoreEntryOperation.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/StoreEntryOperation.java deleted file mode 100644 index 7a41d1fe..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/StoreEntryOperation.java +++ /dev/null @@ -1,34 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import java.io.IOException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; - -@FunctionalInterface -public interface StoreEntryOperation { - - KeyStore getStore(Certificate[] certificates) - throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException; -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CertFileWriterException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CertFileWriterException.java deleted file mode 100644 index 7912f6d7..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CertFileWriterException.java +++ /dev/null @@ -1,35 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class CertFileWriterException extends ExitableException { - - public CertFileWriterException(Throwable cause) { - super(cause); - } - - @Override - public ExitStatus applicationExitStatus() { - return ExitStatus.FILE_CREATION_EXCEPTION; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CsrGenerationException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CsrGenerationException.java deleted file mode 100644 index ba501cd6..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CsrGenerationException.java +++ /dev/null @@ -1,35 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class CsrGenerationException extends ExitableException { - private static final ExitStatus EXIT_STATUS = ExitStatus.CSR_GENERATION_EXCEPTION; - - public CsrGenerationException(Throwable cause) { - super(cause); - } - - public ExitStatus applicationExitStatus() { - return EXIT_STATUS; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/KeyPairGenerationException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/KeyPairGenerationException.java deleted file mode 100644 index 11030ff3..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/KeyPairGenerationException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class KeyPairGenerationException extends ExitableException { - private static final ExitStatus EXIT_STATUS = ExitStatus.KEY_PAIR_GENERATION_EXCEPTION; - - public KeyPairGenerationException(String errorMessage) { - super(errorMessage); - } - - - public ExitStatus applicationExitStatus() { - return EXIT_STATUS; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PemConversionException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PemConversionException.java deleted file mode 100644 index cad3388b..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PemConversionException.java +++ /dev/null @@ -1,40 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class PemConversionException extends ExitableException { - private static final ExitStatus EXIT_STATUS = ExitStatus.PEM_CONVERSION_EXCEPTION; - - public PemConversionException(Throwable cause) { - super(cause); - } - - public PemConversionException(String message) { - super(message); - } - - @Override - public ExitStatus applicationExitStatus() { - return EXIT_STATUS; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PkEncodingException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PkEncodingException.java deleted file mode 100644 index 89976bf3..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PkEncodingException.java +++ /dev/null @@ -1,35 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class PkEncodingException extends ExitableException { - private static final ExitStatus EXIT_STATUS = ExitStatus.PK_TO_PEM_ENCODING_EXCEPTION; - - public PkEncodingException(Throwable cause) { - super(cause); - } - - public ExitStatus applicationExitStatus() { - return EXIT_STATUS; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriter.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriter.java deleted file mode 100644 index fec3ebd3..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriter.java +++ /dev/null @@ -1,62 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.writer; - -import org.onap.aaf.certservice.client.certification.exception.CertFileWriterException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Path; - -public class CertFileWriter { - - private static final Logger LOGGER = LoggerFactory.getLogger(CertFileWriter.class); - private final String destPath; - - private CertFileWriter(String destPath) { - this.destPath = destPath; - } - - public static CertFileWriter createWithDir(String destPath) { - createDirIfNotExists(destPath); - return new CertFileWriter(destPath); - } - - public void saveData(byte[] data, String filename) throws CertFileWriterException { - LOGGER.debug("Attempt to save file {} in path {}", filename, destPath); - try (FileOutputStream outputStream = new FileOutputStream(Path.of(destPath, filename).toString())) { - outputStream.write(data); - } catch (IOException e) { - LOGGER.error("File creation failed, exception message: {}", e.getMessage()); - throw new CertFileWriterException(e); - } - } - - private static void createDirIfNotExists(String destPath) { - File destFolderPath = new File(destPath); - if (!destFolderPath.exists()) { - LOGGER.debug("Destination path not exists, subdirectories are created"); - destFolderPath.mkdirs(); - } - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/common/Base64Encoder.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/common/Base64Encoder.java deleted file mode 100644 index bfa43071..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/common/Base64Encoder.java +++ /dev/null @@ -1,28 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.common; - -import org.bouncycastle.util.encoders.Base64; - -public class Base64Encoder { - public String encode(String string) { - return new String(Base64.encode(string.getBytes())); - } -} \ No newline at end of file diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/ClientConfigurationEnvs.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/ClientConfigurationEnvs.java deleted file mode 100644 index f8a0e91a..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/ClientConfigurationEnvs.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -public enum ClientConfigurationEnvs { - REQUEST_URL, - REQUEST_TIMEOUT, - OUTPUT_PATH, - CA_NAME, - OUTPUT_TYPE -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/CsrConfigurationEnvs.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/CsrConfigurationEnvs.java deleted file mode 100644 index d1cfcd5a..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/CsrConfigurationEnvs.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -public enum CsrConfigurationEnvs { - COMMON_NAME, - ORGANIZATION, - ORGANIZATION_UNIT, - LOCATION, - STATE, - COUNTRY, - SANS -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvProvider.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvProvider.java deleted file mode 100644 index 15339bbd..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvProvider.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -import java.util.Optional; - -public class EnvProvider { - public Optional readEnvVariable(String envVariableName) { - return Optional.ofNullable(getSystemEnv(envVariableName)) - .filter(EnvProvider::isEnvPresent); - } - - String getSystemEnv(String envVariableName) { - return System.getenv(envVariableName); - } - - private static Boolean isEnvPresent(String envValue) { - return !"".equals(envValue); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForClient.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForClient.java deleted file mode 100644 index 9321964c..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForClient.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -import java.util.Optional; - -public class EnvsForClient { - private final EnvProvider envProvider = new EnvProvider(); - - public Optional getUrlToCertService() { - return readEnv(ClientConfigurationEnvs.REQUEST_URL); - } - - public Optional getRequestTimeOut() { - return readEnv(ClientConfigurationEnvs.REQUEST_TIMEOUT); - } - - public Optional getOutputPath() { - return readEnv(ClientConfigurationEnvs.OUTPUT_PATH); - } - - public Optional getCaName() { - return readEnv(ClientConfigurationEnvs.CA_NAME); - } - - public Optional getOutputType() { - return readEnv(ClientConfigurationEnvs.OUTPUT_TYPE); - } - - private Optional readEnv(ClientConfigurationEnvs envName) { - return envProvider.readEnvVariable(envName.toString()); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForCsr.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForCsr.java deleted file mode 100644 index 9a892b24..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForCsr.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -import java.util.Optional; - -public class EnvsForCsr { - private final EnvProvider envProvider = new EnvProvider(); - - public Optional getCommonName() { - return readEnv(CsrConfigurationEnvs.COMMON_NAME); - } - - public Optional getOrganization() { - return readEnv(CsrConfigurationEnvs.ORGANIZATION); - } - - public Optional getOrganizationUnit() { - return readEnv(CsrConfigurationEnvs.ORGANIZATION_UNIT); - } - - public Optional getLocation() { - return readEnv(CsrConfigurationEnvs.LOCATION); - } - - public Optional getState() { - return readEnv(CsrConfigurationEnvs.STATE); - } - - public Optional getCountry() { - return readEnv(CsrConfigurationEnvs.COUNTRY); - } - - public Optional getSubjectAlternativesName() { - return readEnv(CsrConfigurationEnvs.SANS); - } - - Optional readEnv(CsrConfigurationEnvs envName) { - return envProvider.readEnvVariable(envName.toString()); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForTls.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForTls.java deleted file mode 100644 index 55b536a7..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/EnvsForTls.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -import java.util.Optional; - -public class EnvsForTls { - private final EnvProvider envProvider = new EnvProvider(); - - public Optional getKeystorePath() { - return readEnv(TlsConfigurationEnvs.KEYSTORE_PATH); - } - - public Optional getKeystorePassword() { - return readEnv(TlsConfigurationEnvs.KEYSTORE_PASSWORD); - } - - public Optional getTruststorePath() { - return readEnv(TlsConfigurationEnvs.TRUSTSTORE_PATH); - } - - public Optional getTruststorePassword() { - return readEnv(TlsConfigurationEnvs.TRUSTSTORE_PASSWORD); - } - - Optional readEnv(TlsConfigurationEnvs envName) { - return envProvider.readEnvVariable(envName.toString()); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/TlsConfigurationEnvs.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/TlsConfigurationEnvs.java deleted file mode 100644 index 4009a088..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/TlsConfigurationEnvs.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -public enum TlsConfigurationEnvs { - KEYSTORE_PATH, - KEYSTORE_PASSWORD, - TRUSTSTORE_PATH, - TRUSTSTORE_PASSWORD -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/ClientConfigurationException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/ClientConfigurationException.java deleted file mode 100644 index ea280736..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/ClientConfigurationException.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class ClientConfigurationException extends ExitableException { - private static final ExitStatus EXIT_STATUS = ExitStatus.CLIENT_CONFIGURATION_EXCEPTION; - - public ClientConfigurationException(String message) { - super(message); - } - - public ExitStatus applicationExitStatus() { - return EXIT_STATUS; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/CsrConfigurationException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/CsrConfigurationException.java deleted file mode 100644 index cf785a71..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/CsrConfigurationException.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class CsrConfigurationException extends ExitableException { - private static final ExitStatus EXIT_STATUS = ExitStatus.CSR_CONFIGURATION_EXCEPTION; - - public CsrConfigurationException(String message) { - super(message); - } - - public ExitStatus applicationExitStatus() { - return EXIT_STATUS; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationException.java deleted file mode 100644 index 91f164e3..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationException.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class TlsConfigurationException extends ExitableException { - private static final ExitStatus EXIT_STATUS = ExitStatus.TLS_CONFIGURATION_EXCEPTION; - - public TlsConfigurationException(String message) { - super(message); - } - - public ExitStatus applicationExitStatus() { - return EXIT_STATUS; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactory.java deleted file mode 100644 index 24ed8b0d..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactory.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.factory; - - -import org.onap.aaf.certservice.client.certification.ArtifactsCreatorProvider; -import org.onap.aaf.certservice.client.configuration.exception.ClientConfigurationException; -import org.onap.aaf.certservice.client.configuration.exception.CsrConfigurationException; -import org.onap.aaf.certservice.client.configuration.model.ConfigurationModel; - -import java.util.Arrays; -import java.util.Locale; -import java.util.regex.Pattern; - -public abstract class AbstractConfigurationFactory { - - abstract T create() throws ClientConfigurationException, CsrConfigurationException; - - public boolean isPathValid(String path) { - return path.matches("^/|(/[a-zA-Z0-9_-]+)+/?$"); - } - - public boolean isAlphaNumeric(String caName) { - return caName.matches("^[a-zA-Z0-9]*$"); - } - - public boolean isCommonNameValid(String commonName) { - return !isSpecialCharsPresent(commonName) - && !isHttpProtocolsPresent(commonName) - && !isIpAddressPresent(commonName) - && !isPortNumberPresent(commonName); - } - - public boolean isSpecialCharsPresent(String stringToCheck) { - return Pattern.compile("[~#@*$+%!()?/{}<>\\|_^]").matcher(stringToCheck).find(); - } - - public boolean isCountryValid(String country) { - return Arrays.asList(Locale.getISOCountries()).contains(country); - } - - public boolean isOutputTypeValid(String outputType) { - return Arrays.stream(ArtifactsCreatorProvider.values()) - .map(ArtifactsCreatorProvider::toString) - .anyMatch(name -> name.equals(outputType)); - } - - private boolean isPortNumberPresent(String stringToCheck) { - return Pattern.compile(":[0-9]{1,5}").matcher(stringToCheck).find(); - } - - private boolean isIpAddressPresent(String stringToCheck) { - return Pattern.compile("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}").matcher(stringToCheck).find(); - } - - private boolean isHttpProtocolsPresent(String stringToCheck) { - return Pattern.compile("[h][t][t][p][:][/][/]|[h][t][t][p][s][:][/][/]").matcher(stringToCheck).find(); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactory.java deleted file mode 100644 index d8498d84..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactory.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.factory; - -import org.onap.aaf.certservice.client.configuration.ClientConfigurationEnvs; -import org.onap.aaf.certservice.client.configuration.EnvsForClient; -import org.onap.aaf.certservice.client.configuration.exception.ClientConfigurationException; -import org.onap.aaf.certservice.client.configuration.model.ClientConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Optional; - -public class ClientConfigurationFactory extends AbstractConfigurationFactory { - - private static final Logger LOGGER = LoggerFactory.getLogger(ClientConfigurationFactory.class); - private final EnvsForClient envsForClient; - - public ClientConfigurationFactory(EnvsForClient envsForClient) { - this.envsForClient = envsForClient; - } - - @Override - public ClientConfiguration create() throws ClientConfigurationException { - - ClientConfiguration configuration = new ClientConfiguration(); - - - envsForClient.getUrlToCertService() - .map(configuration::setUrlToCertService); - - envsForClient.getRequestTimeOut() - .map(timeout -> configuration.setRequestTimeout(Integer.valueOf(timeout))); - - envsForClient.getOutputPath() - .filter(this::isPathValid) - .map(configuration::setCertsOutputPath) - .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.OUTPUT_PATH + " is invalid.")); - - envsForClient.getCaName() - .filter(this::isAlphaNumeric) - .map(configuration::setCaName) - .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.CA_NAME + " is invalid.")); - - Optional outputType = envsForClient.getOutputType(); - - if (outputType.isPresent()) { - outputType.filter(this::isOutputTypeValid) - .map(configuration::setOutputType) - .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.OUTPUT_TYPE + " is invalid.")); - } - - LOGGER.info("Successful validation of Client configuration. Configuration data: {}", configuration.toString()); - - return configuration; - } -} - diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactory.java deleted file mode 100644 index 1d4cf2b2..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactory.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.factory; - -import org.onap.aaf.certservice.client.configuration.CsrConfigurationEnvs; -import org.onap.aaf.certservice.client.configuration.EnvsForCsr; -import org.onap.aaf.certservice.client.configuration.exception.CsrConfigurationException; -import org.onap.aaf.certservice.client.configuration.model.CsrConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class CsrConfigurationFactory extends AbstractConfigurationFactory { - - private static final Logger LOGGER = LoggerFactory.getLogger(CsrConfigurationFactory.class); - private final EnvsForCsr envsForCsr; - - public CsrConfigurationFactory(EnvsForCsr envsForCsr) { - this.envsForCsr = envsForCsr; - } - - @Override - public CsrConfiguration create() throws CsrConfigurationException { - - CsrConfiguration configuration = new CsrConfiguration(); - - envsForCsr.getCommonName() - .filter(this::isCommonNameValid) - .map(configuration::setCommonName) - .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COMMON_NAME + " is invalid.")); - - envsForCsr.getOrganization() - .filter(org -> !isSpecialCharsPresent(org)) - .map(configuration::setOrganization) - .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.ORGANIZATION + " is invalid.")); - - envsForCsr.getState() - .map(configuration::setState) - .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.STATE + " is invalid.")); - - envsForCsr.getCountry() - .filter(this::isCountryValid) - .map(configuration::setCountry) - .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COUNTRY + " is invalid.")); - - envsForCsr.getOrganizationUnit() - .map(configuration::setOrganizationUnit); - - envsForCsr.getLocation() - .map(configuration::setLocation); - - envsForCsr.getSubjectAlternativesName() - .map(configuration::setSubjectAlternativeNames); - - LOGGER.info("Successful validation of CSR configuration. Configuration data: {}", configuration.toString()); - - return configuration; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactory.java deleted file mode 100644 index 7da8fa58..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactory.java +++ /dev/null @@ -1,85 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.factory; - -import org.apache.http.ssl.SSLContexts; -import org.onap.aaf.certservice.client.configuration.EnvsForTls; -import org.onap.aaf.certservice.client.configuration.TlsConfigurationEnvs; -import org.onap.aaf.certservice.client.configuration.exception.TlsConfigurationException; - -import javax.net.ssl.SSLContext; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; - -public class SslContextFactory { - - private static final String JKS = "jks"; - - private EnvsForTls envsForTls; - - public SslContextFactory(EnvsForTls envsForTls) { - this.envsForTls = envsForTls; - } - - public SSLContext create() throws TlsConfigurationException { - String keystorePath = envsForTls.getKeystorePath() - .orElseThrow(() -> new TlsConfigurationException(createEnvMissingMessage(TlsConfigurationEnvs.KEYSTORE_PATH))); - String keystorePassword = envsForTls.getKeystorePassword() - .orElseThrow(() -> new TlsConfigurationException(createEnvMissingMessage(TlsConfigurationEnvs.KEYSTORE_PASSWORD))); - String truststorePath = envsForTls.getTruststorePath() - .orElseThrow(() -> new TlsConfigurationException(createEnvMissingMessage(TlsConfigurationEnvs.TRUSTSTORE_PATH))); - String truststorePassword = envsForTls.getTruststorePassword() - .orElseThrow(() -> new TlsConfigurationException(createEnvMissingMessage(TlsConfigurationEnvs.TRUSTSTORE_PASSWORD))); - - return createSslContext(keystorePath, keystorePassword, truststorePath, truststorePassword); - } - - private String createEnvMissingMessage(TlsConfigurationEnvs keystorePath) { - return String.format("%s env is missing.", keystorePath); - } - - private KeyStore setupKeystore(String keystorePath, String certPassword) - throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { - KeyStore keyStore = KeyStore.getInstance(JKS); - FileInputStream identityKeyStoreFile = new FileInputStream(new File( - keystorePath)); - keyStore.load(identityKeyStoreFile, certPassword.toCharArray()); - return keyStore; - } - - private SSLContext createSslContext(String keystorePath, String keystorePassword, String truststorePath, String truststorePassword) throws TlsConfigurationException { - try { - KeyStore identityKeystore = setupKeystore(keystorePath, keystorePassword); - KeyStore trustKeystore = setupKeystore(truststorePath, truststorePassword); - - return SSLContexts.custom() - .loadKeyMaterial(identityKeystore, keystorePassword.toCharArray()) - .loadTrustMaterial(trustKeystore, null) - .build(); - } catch (Exception e) { - throw new TlsConfigurationException("TLS configuration exception: " + e); - } - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ClientConfiguration.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ClientConfiguration.java deleted file mode 100644 index 78fa1b4b..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ClientConfiguration.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.model; - -import org.onap.aaf.certservice.client.configuration.ClientConfigurationEnvs; - -public class ClientConfiguration implements ConfigurationModel { - - private static final Integer DEFAULT_TIMEOUT_MS = 30000; - private static final String DEFAULT_REQUEST_URL = "https://aaf-cert-service:8443/v1/certificate/"; - private static final String DEFAULT_OUTPUT_TYPE = "P12"; - - private String urlToCertService; - private Integer requestTimeout; - private String certsOutputPath; - private String caName; - private String outputType; - - - public ClientConfiguration() { - urlToCertService = DEFAULT_REQUEST_URL; - requestTimeout = DEFAULT_TIMEOUT_MS; - outputType = DEFAULT_OUTPUT_TYPE; - } - - - public String getUrlToCertService() { - return urlToCertService; - } - - public ClientConfiguration setUrlToCertService(String urlToCertService) { - this.urlToCertService = urlToCertService; - return this; - } - - public Integer getRequestTimeout() { - return requestTimeout; - } - - public ClientConfiguration setRequestTimeout(Integer requestTimeout) { - this.requestTimeout = requestTimeout; - return this; - } - - public String getCertsOutputPath() { - return certsOutputPath; - } - - public ClientConfiguration setCertsOutputPath(String certsOutputPath) { - this.certsOutputPath = certsOutputPath; - return this; - } - - public String getCaName() { - return caName; - } - - public ClientConfiguration setCaName(String caName) { - this.caName = caName; - return this; - } - - public String getOutputType() { - return outputType; - } - - public ClientConfiguration setOutputType(String outputType) { - this.outputType = outputType; - return this; - } - - @Override - public String toString() { - return String.format("%s: %s, %s: %s, %s: %s, %s: %s, %s: %s", - ClientConfigurationEnvs.REQUEST_URL, urlToCertService, - ClientConfigurationEnvs.REQUEST_TIMEOUT, requestTimeout, - ClientConfigurationEnvs.OUTPUT_PATH, certsOutputPath, - ClientConfigurationEnvs.CA_NAME, caName, - ClientConfigurationEnvs.OUTPUT_TYPE, outputType); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ConfigurationModel.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ConfigurationModel.java deleted file mode 100644 index 15c22233..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ConfigurationModel.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.model; - -public interface ConfigurationModel { -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/CsrConfiguration.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/CsrConfiguration.java deleted file mode 100644 index 55f33c9f..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/CsrConfiguration.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.model; - - -import org.onap.aaf.certservice.client.configuration.CsrConfigurationEnvs; - -public class CsrConfiguration implements ConfigurationModel { - - private String commonName; - private String organization; - private String state; - private String country; - private String organizationUnit; - private String location; - private String sans; - - - public String getCommonName() { - return commonName; - } - - public CsrConfiguration setCommonName(String commonName) { - this.commonName = commonName; - return this; - } - - public String getOrganization() { - return organization; - } - - public CsrConfiguration setOrganization(String organization) { - this.organization = organization; - return this; - } - - public String getState() { - return state; - } - - public CsrConfiguration setState(String state) { - this.state = state; - return this; - } - - public String getCountry() { - return country; - } - - public CsrConfiguration setCountry(String country) { - this.country = country; - return this; - } - - public String getOrganizationUnit() { - return organizationUnit; - } - - public CsrConfiguration setOrganizationUnit(String organizationUnit) { - this.organizationUnit = organizationUnit; - return this; - } - - public String getLocation() { - return location; - } - - public CsrConfiguration setLocation(String location) { - this.location = location; - return this; - } - - public String getSans() { - return sans; - } - - public CsrConfiguration setSubjectAlternativeNames(String subjectAlternativeNames) { - this.sans = subjectAlternativeNames; - return this; - } - - @Override - public String toString() { - return String.format("%s: %s, %s: %s, %s: %s, %s: %s, %s: %s, %s: %s, %s: %s", - CsrConfigurationEnvs.COMMON_NAME, commonName, - CsrConfigurationEnvs.COUNTRY, country, - CsrConfigurationEnvs.STATE, state, - CsrConfigurationEnvs.ORGANIZATION, organization, - CsrConfigurationEnvs.ORGANIZATION_UNIT, organizationUnit, - CsrConfigurationEnvs.LOCATION, location, - CsrConfigurationEnvs.SANS, sans); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/CloseableHttpsClientProvider.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/CloseableHttpsClientProvider.java deleted file mode 100644 index 3b7a46ab..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/CloseableHttpsClientProvider.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.httpclient; - -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; - -import javax.net.ssl.SSLContext; - -public class CloseableHttpsClientProvider { - - private final int timeout; - private final SSLContext sslContext; - - public CloseableHttpsClientProvider(SSLContext sslContext, int timeout) { - this.sslContext = sslContext; - this.timeout = timeout; - } - - public CloseableHttpClient getClient() { - RequestConfig config = - RequestConfig.custom() - .setConnectionRequestTimeout(timeout) - .setConnectTimeout(timeout) - .setSocketTimeout(timeout) - .build(); - - return HttpClientBuilder.create() - .setSSLContext(sslContext) - .setDefaultRequestConfig(config).build(); - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/HttpClient.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/HttpClient.java deleted file mode 100644 index 0780afad..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/HttpClient.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.httpclient; - -import com.google.gson.Gson; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; -import org.onap.aaf.certservice.client.httpclient.exception.CertServiceApiResponseException; -import org.onap.aaf.certservice.client.httpclient.exception.HttpClientException; -import org.onap.aaf.certservice.client.httpclient.model.CertServiceResponse; -import org.onap.aaf.certservice.client.httpclient.model.ErrorCertServiceResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -public class HttpClient { - - private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class); - private static final String CSR_HEADER_NAME = "CSR"; - private static final String PK_HEADER_NAME = "PK"; - private static final String CHARSET_UTF_8 = "UTF-8"; - - private final Gson gson = new Gson(); - private final CloseableHttpsClientProvider httpClientProvider; - private final String certServiceAddress; - - public HttpClient(CloseableHttpsClientProvider httpClientProvider, String certServiceAddress) { - this.httpClientProvider = httpClientProvider; - this.certServiceAddress = certServiceAddress; - } - - public CertServiceResponse retrieveCertServiceData(String caName, String csr, String encodedPk) - throws CertServiceApiResponseException, HttpClientException { - - try (CloseableHttpClient httpClient = httpClientProvider.getClient()) { - LOGGER.info("Attempt to send request to API, on url: {}{} ", certServiceAddress, caName); - HttpResponse httpResponse = httpClient.execute(createHttpRequest(caName, csr, encodedPk)); - LOGGER.info("Received response from API"); - return extractCertServiceResponse(httpResponse); - - } catch (IOException e) { - LOGGER.error("Failed execute request to API for URL: {}{} , exception message: {}", - certServiceAddress, caName, e.getMessage()); - throw new HttpClientException(e); - } - } - - private HttpGet createHttpRequest(String caName, String csr, String pk) { - String url = certServiceAddress + caName; - HttpGet httpGet = new HttpGet(url); - httpGet.addHeader(CSR_HEADER_NAME, csr); - httpGet.addHeader(PK_HEADER_NAME, pk); - return httpGet; - } - - private CertServiceResponse extractCertServiceResponse(HttpResponse httpResponse) - throws CertServiceApiResponseException, HttpClientException { - int httpResponseCode = getStatusCode(httpResponse); - if (HttpStatus.SC_OK != httpResponseCode) { - LOGGER.error("Error on API response. Response Code: {}", httpResponseCode); - throw generateApiResponseException(httpResponse); - } - String jsonResponse = getStringResponse(httpResponse.getEntity()); - return gson.fromJson(jsonResponse, CertServiceResponse.class); - } - - private CertServiceApiResponseException generateApiResponseException(HttpResponse httpResponse) - throws HttpClientException { - String stringResponse = getStringResponse(httpResponse.getEntity()); - ErrorCertServiceResponse errorCertServiceResponse = - gson.fromJson(stringResponse, ErrorCertServiceResponse.class); - - return new CertServiceApiResponseException(getStatusCode(httpResponse), errorCertServiceResponse.getMessage()); - } - - private int getStatusCode(HttpResponse httpResponse) { - return httpResponse.getStatusLine().getStatusCode(); - } - - private String getStringResponse(HttpEntity httpEntity) throws HttpClientException { - try { - return EntityUtils.toString(httpEntity, CHARSET_UTF_8); - } catch (IOException e) { - LOGGER.error("Cannot parse response to string, exception message: {}", e.getMessage()); - throw new HttpClientException(e); - } - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/CertServiceApiResponseException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/CertServiceApiResponseException.java deleted file mode 100644 index ad5a5f1c..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/CertServiceApiResponseException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.httpclient.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class CertServiceApiResponseException extends ExitableException { - private static final ExitStatus EXIT_STATUS = ExitStatus.CERT_SERVICE_API_CONNECTION_EXCEPTION; - - public CertServiceApiResponseException(int responseCode, String messageFromApi) { - - super(String.format("CertService HTTP unsuccessful response. Response code: %d . Message from Service: %s", - responseCode, - messageFromApi)); - } - - @Override - public ExitStatus applicationExitStatus() { - return EXIT_STATUS; - } - -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/HttpClientException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/HttpClientException.java deleted file mode 100644 index e9f0f0ad..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/HttpClientException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.httpclient.exception; - -import org.onap.aaf.certservice.client.api.ExitStatus; -import org.onap.aaf.certservice.client.api.ExitableException; - -public class HttpClientException extends ExitableException { - private static final ExitStatus EXIT_STATUS = ExitStatus.HTTP_CLIENT_EXCEPTION; - - public HttpClientException(Throwable cause) { - super(cause); - } - - @Override - public ExitStatus applicationExitStatus() { - return EXIT_STATUS; - } -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/CertServiceResponse.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/CertServiceResponse.java deleted file mode 100644 index 4ca17999..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/CertServiceResponse.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.httpclient.model; - -import java.util.Collections; -import java.util.List; - -public class CertServiceResponse { - - private final List certificateChain; - private final List trustedCertificates; - - public CertServiceResponse(List certificateChain, List trustedCertificates) { - this.certificateChain = certificateChain; - this.trustedCertificates = trustedCertificates; - } - - public List getCertificateChain() { - return Collections.unmodifiableList(certificateChain); - } - - public List getTrustedCertificates() { - return Collections.unmodifiableList(trustedCertificates); - } - -} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/ErrorCertServiceResponse.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/ErrorCertServiceResponse.java deleted file mode 100644 index 4a9efcb4..00000000 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/ErrorCertServiceResponse.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.httpclient.model; - -public class ErrorCertServiceResponse { - - private final String errorMessage; - - public ErrorCertServiceResponse(String errorMessage) { - this.errorMessage = errorMessage; - } - - public String getMessage() { - return errorMessage; - } - -} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/AppExitHandler.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/AppExitHandler.java new file mode 100644 index 00000000..16636fa6 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/AppExitHandler.java @@ -0,0 +1,34 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +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: {}", + exitStatus.getExitCodeValue(), exitStatus.getMessage()); + System.exit(exitStatus.getExitCodeValue()); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/CertServiceClient.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/CertServiceClient.java new file mode 100644 index 00000000..d115380f --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/CertServiceClient.java @@ -0,0 +1,93 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client; + +import org.onap.oom.certservice.client.api.ExitableException; +import org.onap.oom.certservice.client.certification.ArtifactsCreatorProvider; +import org.onap.oom.certservice.client.certification.CsrFactory; +import org.onap.oom.certservice.client.certification.KeyPairFactory; +import org.onap.oom.certservice.client.certification.PrivateKeyToPemEncoder; +import org.onap.oom.certservice.client.common.Base64Encoder; +import org.onap.oom.certservice.client.configuration.EnvsForClient; +import org.onap.oom.certservice.client.configuration.EnvsForCsr; +import org.onap.oom.certservice.client.configuration.EnvsForTls; +import org.onap.oom.certservice.client.configuration.factory.ClientConfigurationFactory; +import org.onap.oom.certservice.client.configuration.factory.CsrConfigurationFactory; +import org.onap.oom.certservice.client.configuration.factory.SslContextFactory; +import org.onap.oom.certservice.client.configuration.model.ClientConfiguration; +import org.onap.oom.certservice.client.configuration.model.CsrConfiguration; +import org.onap.oom.certservice.client.httpclient.CloseableHttpsClientProvider; +import org.onap.oom.certservice.client.httpclient.HttpClient; +import org.onap.oom.certservice.client.httpclient.model.CertServiceResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLContext; +import java.security.KeyPair; + +import static org.onap.oom.certservice.client.api.ExitStatus.SUCCESS; +import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.KEY_SIZE; +import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM; + +public class CertServiceClient { + + private static final Logger LOGGER = LoggerFactory.getLogger(CertServiceClient.class); + + private AppExitHandler appExitHandler; + + public CertServiceClient(AppExitHandler appExitHandler) { + this.appExitHandler = appExitHandler; + } + + public void run() { + KeyPairFactory keyPairFactory = new KeyPairFactory(RSA_ENCRYPTION_ALGORITHM, KEY_SIZE); + PrivateKeyToPemEncoder pkEncoder = new PrivateKeyToPemEncoder(); + Base64Encoder base64Encoder = new Base64Encoder(); + try { + ClientConfiguration clientConfiguration = new ClientConfigurationFactory(new EnvsForClient()).create(); + CsrConfiguration csrConfiguration = new CsrConfigurationFactory(new EnvsForCsr()).create(); + KeyPair keyPair = keyPairFactory.create(); + CsrFactory csrFactory = new CsrFactory(csrConfiguration); + SSLContext sslContext = new SslContextFactory(new EnvsForTls()).create(); + + CloseableHttpsClientProvider provider = new CloseableHttpsClientProvider( + sslContext, clientConfiguration.getRequestTimeout()); + HttpClient httpClient = new HttpClient(provider, clientConfiguration.getUrlToCertService()); + + CertServiceResponse certServiceData = + httpClient.retrieveCertServiceData( + clientConfiguration.getCaName(), + base64Encoder.encode(csrFactory.createCsrInPem(keyPair)), + base64Encoder.encode(pkEncoder.encodePrivateKeyToPem(keyPair.getPrivate()))); + + ArtifactsCreatorProvider + .get(clientConfiguration.getOutputType(), + clientConfiguration.getCertsOutputPath()) + .create(certServiceData.getCertificateChain(), + certServiceData.getTrustedCertificates(), + keyPair.getPrivate()); + + } catch (ExitableException e) { + LOGGER.error("Cert Service Client fails in execution: ", e); + appExitHandler.exit(e.applicationExitStatus()); + } + appExitHandler.exit(SUCCESS); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/MainApp.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/MainApp.java new file mode 100644 index 00000000..e0d0fec1 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/MainApp.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client; + +public class MainApp { + public static void main(String[] args) { + CertServiceClient certServiceClient = new CertServiceClient(new AppExitHandler()); + certServiceClient.run(); + } +} \ No newline at end of file diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/api/ExitStatus.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/api/ExitStatus.java new file mode 100644 index 00000000..1b1cc066 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/api/ExitStatus.java @@ -0,0 +1,51 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.api; + +public enum ExitStatus { + + SUCCESS(0, "Success"), + CLIENT_CONFIGURATION_EXCEPTION(1, "Invalid client configuration"), + CSR_CONFIGURATION_EXCEPTION(2, "Invalid CSR configuration"), + KEY_PAIR_GENERATION_EXCEPTION(3, "Fail in key pair generation"), + CSR_GENERATION_EXCEPTION(4, "Fail in CSR generation"), + CERT_SERVICE_API_CONNECTION_EXCEPTION(5, "CertService HTTP unsuccessful response"), + HTTP_CLIENT_EXCEPTION(6, "Internal HTTP Client connection problem"), + PEM_CONVERSION_EXCEPTION(7, "Fail in PEM conversion"), + PK_TO_PEM_ENCODING_EXCEPTION(8, "Fail in Private Key to PEM Encoding"), + TLS_CONFIGURATION_EXCEPTION(9, "Invalid TLS configuration"), + FILE_CREATION_EXCEPTION(10, "File could not be created"); + + private final int value; + private final String message; + + ExitStatus(int value, String message) { + this.value = value; + this.message = message; + } + + public int getExitCodeValue() { + return value; + } + + public String getMessage() { + return message; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/api/ExitableException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/api/ExitableException.java new file mode 100644 index 00000000..ab7a308b --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/api/ExitableException.java @@ -0,0 +1,32 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.api; + +public abstract class ExitableException extends Exception { + public ExitableException(Throwable cause) { + super(cause); + } + + public ExitableException(String message) { + super(message); + } + + public abstract ExitStatus applicationExitStatus(); +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProvider.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProvider.java new file mode 100644 index 00000000..dabd808d --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProvider.java @@ -0,0 +1,66 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification; + +import org.onap.oom.certservice.client.certification.conversion.ArtifactsCreator; +import org.onap.oom.certservice.client.certification.conversion.ConvertedArtifactsCreatorFactory; +import org.onap.oom.certservice.client.certification.conversion.PemArtifactsCreator; +import org.onap.oom.certservice.client.certification.writer.CertFileWriter; + +public enum ArtifactsCreatorProvider { + P12("PKCS12") { + @Override + ArtifactsCreator create(String destPath) { + return ConvertedArtifactsCreatorFactory.createConverter(destPath, getExtension(), getKeyStoreType()); + } + }, + JKS("JKS") { + @Override + ArtifactsCreator create(String destPath) { + return ConvertedArtifactsCreatorFactory.createConverter(destPath, getExtension(), getKeyStoreType()); + } + }, + PEM("PEM") { + @Override + ArtifactsCreator create(String destPath) { + return new PemArtifactsCreator(CertFileWriter.createWithDir(destPath), new PrivateKeyToPemEncoder()); + } + }; + + private final String keyStoreType; + + ArtifactsCreatorProvider(String keyStoreType) { + this.keyStoreType = keyStoreType; + } + + public static ArtifactsCreator get(String outputType, String destPath) { + return valueOf(outputType).create(destPath); + } + + String getKeyStoreType() { + return keyStoreType; + } + + String getExtension() { + return this.toString().toLowerCase(); + } + + abstract ArtifactsCreator create(String destPath); +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/CsrFactory.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/CsrFactory.java new file mode 100644 index 00000000..ac517be4 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/CsrFactory.java @@ -0,0 +1,153 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification; + +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.Extensions; +import org.bouncycastle.asn1.x509.ExtensionsGenerator; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.openssl.jcajce.JcaPEMWriter; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.pkcs.PKCS10CertificationRequest; +import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; +import org.onap.oom.certservice.client.certification.exception.CsrGenerationException; +import org.onap.oom.certservice.client.configuration.model.CsrConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.security.auth.x500.X500Principal; +import java.io.IOException; +import java.io.StringWriter; +import java.security.KeyPair; +import java.util.Optional; + +import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.COMMON_NAME; +import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.COUNTRY; +import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.LOCATION; +import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.ORGANIZATION; +import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.ORGANIZATION_UNIT; +import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.SIGN_ALGORITHM; +import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants.STATE; + + +public class CsrFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(CsrFactory.class); + private static final String SANS_DELIMITER = ":"; + private final CsrConfiguration configuration; + + + public CsrFactory(CsrConfiguration configuration) { + this.configuration = configuration; + } + + + public String createCsrInPem(KeyPair keyPair) throws CsrGenerationException { + LOGGER.info("Creation of CSR has been started with following parameters: {}", configuration.toString()); + String csrParameters = getMandatoryParameters().append(getOptionalParameters()).toString(); + X500Principal subject = new X500Principal(csrParameters); + PKCS10CertificationRequest request = createPkcs10Csr(subject, keyPair); + + LOGGER.info("Creation of CSR has been completed successfully"); + return convertPkcs10CsrToPem(request); + } + + private StringBuilder getMandatoryParameters() { + return new StringBuilder(String.format("%s=%s, %s=%s, %s=%s, %s=%s", + COMMON_NAME, configuration.getCommonName(), + COUNTRY, configuration.getCountry(), + STATE, configuration.getState(), + ORGANIZATION, configuration.getOrganization())); + } + + private String getOptionalParameters() { + StringBuilder optionalParameters = new StringBuilder(); + Optional.ofNullable(configuration.getOrganizationUnit()) + .filter(CsrFactory::isParameterPresent) + .map(unit -> optionalParameters.append(String.format(", %s=%s", ORGANIZATION_UNIT, unit))); + Optional.ofNullable(configuration.getLocation()) + .filter(CsrFactory::isParameterPresent) + .map(location -> optionalParameters.append(String.format(", %s=%s", LOCATION, location))); + return optionalParameters.toString(); + } + + private PKCS10CertificationRequest createPkcs10Csr(X500Principal subject, KeyPair keyPair) throws CsrGenerationException { + JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic()); + + if (isParameterPresent(configuration.getSans())) { + builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, generateSansExtension()); + } + + return builder.build(getContentSigner(keyPair)); + } + + private ContentSigner getContentSigner(KeyPair keyPair) throws CsrGenerationException { + ContentSigner contentSigner; + try { + contentSigner = new JcaContentSignerBuilder(SIGN_ALGORITHM).build(keyPair.getPrivate()); + } catch (OperatorCreationException e) { + LOGGER.error("Creation of PKCS10Csr failed, exception message: {}", e.getMessage()); + throw new CsrGenerationException(e); + + } + return contentSigner; + } + + private String convertPkcs10CsrToPem(PKCS10CertificationRequest request) throws CsrGenerationException { + final StringWriter stringWriter = new StringWriter(); + try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) { + LOGGER.info("Conversion of CSR to PEM has been started"); + pemWriter.writeObject(request); + } catch (IOException e) { + LOGGER.error("Conversion to PEM failed, exception message: {}", e.getMessage()); + throw new CsrGenerationException(e); + } + return stringWriter.toString(); + } + + private Extensions generateSansExtension() throws CsrGenerationException { + ExtensionsGenerator generator = new ExtensionsGenerator(); + try { + generator.addExtension(Extension.subjectAlternativeName, false, createGeneralNames()); + } catch (IOException e) { + LOGGER.error("Generation of SANs parameter failed, exception message: {}", e.getMessage()); + throw new CsrGenerationException(e); + } + return generator.generate(); + } + + private GeneralNames createGeneralNames() { + String[] sansTable = this.configuration.getSans().split(SANS_DELIMITER); + int length = sansTable.length; + GeneralName[] generalNames = new GeneralName[length]; + for (int i = 0; i < length; i++) { + generalNames[i] = new GeneralName(GeneralName.dNSName, sansTable[i]); + } + return new GeneralNames(generalNames); + } + + private static Boolean isParameterPresent(String parameter) { + return parameter != null && !"".equals(parameter); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/EncryptionAlgorithmConstants.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/EncryptionAlgorithmConstants.java new file mode 100644 index 00000000..cbd05e51 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/EncryptionAlgorithmConstants.java @@ -0,0 +1,38 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification; + +public final class EncryptionAlgorithmConstants { + + private EncryptionAlgorithmConstants() { + } + + public static final String RSA_ENCRYPTION_ALGORITHM = "RSA"; + public static final String SIGN_ALGORITHM = "SHA1withRSA"; + public static final int KEY_SIZE = 2048; + + public static final String COMMON_NAME = "CN"; + public static final String ORGANIZATION = "O"; + public static final String ORGANIZATION_UNIT = "OU"; + public static final String LOCATION = "L"; + public static final String STATE = "ST"; + public static final String COUNTRY = "C"; + +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/KeyPairFactory.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/KeyPairFactory.java new file mode 100644 index 00000000..d0c56139 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/KeyPairFactory.java @@ -0,0 +1,56 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification; + +import org.onap.oom.certservice.client.certification.exception.KeyPairGenerationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; + +public class KeyPairFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(KeyPairFactory.class); + private final String encryptionAlgorithm; + private final int keySize; + + public KeyPairFactory(String encryptionAlgorithm, int keySize) { + this.encryptionAlgorithm = encryptionAlgorithm; + this.keySize = keySize; + } + + public KeyPair create() throws KeyPairGenerationException { + try { + LOGGER.info("KeyPair generation started with algorithm: {} and key size: {}", encryptionAlgorithm, keySize); + return createKeyPairGenerator().generateKeyPair(); + } catch (NoSuchAlgorithmException e) { + String errorMessage = String.format("Generation of KeyPair failed, exception message: %s", e.getMessage()); + throw new KeyPairGenerationException(errorMessage); + } + } + + private KeyPairGenerator createKeyPairGenerator() throws NoSuchAlgorithmException { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(encryptionAlgorithm); + keyPairGenerator.initialize(keySize); + return keyPairGenerator; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoder.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoder.java new file mode 100644 index 00000000..7d94bd23 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoder.java @@ -0,0 +1,50 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification; + + +import org.bouncycastle.openssl.jcajce.JcaPEMWriter; +import org.bouncycastle.util.io.pem.PemObject; +import org.onap.oom.certservice.client.certification.exception.PkEncodingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.StringWriter; +import java.security.PrivateKey; + +public class PrivateKeyToPemEncoder { + + private static final Logger LOGGER = LoggerFactory.getLogger(PrivateKeyToPemEncoder.class); + private static final String PEM_OBJECT_TYPE = "RSA PRIVATE KEY"; + + public String encodePrivateKeyToPem(PrivateKey pk) throws PkEncodingException { + LOGGER.info("Attempt to encode private key to PEM"); + StringWriter stringWriter = new StringWriter(); + try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) { + pemWriter.writeObject(new PemObject(PEM_OBJECT_TYPE, pk.getEncoded())); + } catch (IOException e) { + LOGGER.error("Encode of private key to PEM failed. Exception message: {}", e.getMessage()); + throw new PkEncodingException(e); + } + return stringWriter.toString(); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ArtifactsCreator.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ArtifactsCreator.java new file mode 100644 index 00000000..4098b37b --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ArtifactsCreator.java @@ -0,0 +1,30 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.onap.oom.certservice.client.api.ExitableException; + +import java.security.PrivateKey; +import java.util.List; + +public interface ArtifactsCreator { + void create(List keystoreData, List truststoreData, PrivateKey privateKey) + throws ExitableException; +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreator.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreator.java new file mode 100644 index 00000000..8c7c679b --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreator.java @@ -0,0 +1,92 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.onap.oom.certservice.client.certification.exception.CertFileWriterException; +import org.onap.oom.certservice.client.certification.exception.PemConversionException; +import org.onap.oom.certservice.client.certification.writer.CertFileWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.security.PrivateKey; +import java.util.List; + +public class ConvertedArtifactsCreator implements ArtifactsCreator { + + private static final Logger LOGGER = LoggerFactory.getLogger(ConvertedArtifactsCreator.class); + private static final String CERTIFICATE_ALIAS = "certificate"; + private static final String TRUSTED_CERTIFICATE_ALIAS = "trusted-certificate-"; + private static final int PASSWORD_LENGTH = 24; + private static final String PASS_EXT = "pass"; + private static final String KEYSTORE = "keystore"; + private static final String TRUSTSTORE = "truststore"; + + private final String fileExtension; + private final RandomPasswordGenerator passwordGenerator; + private final PemConverter converter; + private final CertFileWriter fileWriter; + + ConvertedArtifactsCreator(CertFileWriter fileWriter, RandomPasswordGenerator passwordGenerator, + PemConverter converter, String fileExtension) { + this.passwordGenerator = passwordGenerator; + this.converter = converter; + this.fileWriter = fileWriter; + this.fileExtension = fileExtension; + } + + @Override + public void create(List keystoreData, List truststoreData, PrivateKey privateKey) + throws PemConversionException, CertFileWriterException { + createKeystore(keystoreData, privateKey); + createTruststore(truststoreData); + } + + private void createKeystore(List data, PrivateKey privateKey) + throws PemConversionException, CertFileWriterException { + Password password = passwordGenerator.generate(PASSWORD_LENGTH); + String keystoreArtifactName = getFilenameWithExtension(KEYSTORE, fileExtension); + String keystorePass = getFilenameWithExtension(KEYSTORE, PASS_EXT); + + LOGGER.debug("Attempt to create keystore files and saving data. File names: {}, {}", keystoreArtifactName, keystorePass); + + fileWriter.saveData(converter.convertKeystore(data, password, CERTIFICATE_ALIAS, privateKey), keystoreArtifactName); + fileWriter.saveData(getPasswordAsBytes(password), keystorePass); + } + + private void createTruststore(List data) + throws PemConversionException, CertFileWriterException { + Password password = passwordGenerator.generate(PASSWORD_LENGTH); + String truststoreArtifactName = getFilenameWithExtension(TRUSTSTORE, fileExtension); + String truststorePass = getFilenameWithExtension(TRUSTSTORE, PASS_EXT); + + LOGGER.debug("Attempt to create truststore files and saving data. File names: {}, {}", truststoreArtifactName, truststorePass); + + fileWriter.saveData(converter.convertTruststore(data, password, TRUSTED_CERTIFICATE_ALIAS), truststoreArtifactName); + fileWriter.saveData(getPasswordAsBytes(password), truststorePass); + } + + private byte[] getPasswordAsBytes(Password password) { + return password.getCurrentPassword().getBytes(); + } + + private String getFilenameWithExtension(String filename, String extension) { + return String.format("%s.%s", filename, extension); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorFactory.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorFactory.java new file mode 100644 index 00000000..183e66bc --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorFactory.java @@ -0,0 +1,37 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.onap.oom.certservice.client.certification.writer.CertFileWriter; + +public class ConvertedArtifactsCreatorFactory { + + private ConvertedArtifactsCreatorFactory() { + } + + public static ConvertedArtifactsCreator createConverter(String destPath, String fileExtension, String keyStoreType) { + return new ConvertedArtifactsCreator( + CertFileWriter.createWithDir(destPath), + new RandomPasswordGenerator(), + new PemConverter(keyStoreType), + fileExtension); + } + +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/Password.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/Password.java new file mode 100644 index 00000000..7a8d5c3d --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/Password.java @@ -0,0 +1,44 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +class Password { + // We are excluding this line in Sonar due to fact that + // PASSWORD_PATTERN does not contain password. This solution + // is safe. + private static final String PASSWORD_PATTERN = "[\\w$#]{16,}"; // NOSONAR + private final String currentPassword; + + Password(String currentPassword) { + this.currentPassword = currentPassword; + } + + String getCurrentPassword() { + return currentPassword; + } + + char[] toCharArray() { + return currentPassword.toCharArray(); + } + + boolean isCorrectPasswordPattern() { + return currentPassword.matches(PASSWORD_PATTERN); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreator.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreator.java new file mode 100644 index 00000000..0136e796 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreator.java @@ -0,0 +1,63 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.onap.oom.certservice.client.certification.PrivateKeyToPemEncoder; +import org.onap.oom.certservice.client.certification.exception.CertFileWriterException; +import org.onap.oom.certservice.client.certification.exception.PkEncodingException; +import org.onap.oom.certservice.client.certification.writer.CertFileWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.security.PrivateKey; +import java.util.List; + +public class PemArtifactsCreator implements ArtifactsCreator { + private static final Logger LOGGER = LoggerFactory.getLogger(PemArtifactsCreator.class); + + private static final String KEY_PEM = "key.pem"; + private static final String KEYSTORE_PEM = "keystore.pem"; + private static final String TRUSTSTORE_PEM = "truststore.pem"; + + private final CertFileWriter writer; + private final PrivateKeyToPemEncoder pkEncoder; + + public PemArtifactsCreator(CertFileWriter writer, PrivateKeyToPemEncoder pkEncoder) { + this.writer = writer; + this.pkEncoder = pkEncoder; + } + + @Override + public void create(List keystoreData, List truststoreData, PrivateKey privateKey) + throws PkEncodingException, CertFileWriterException { + LOGGER.debug("Attempt to create PEM private key file and saving data. File name: {}", KEY_PEM); + writer.saveData(pkEncoder.encodePrivateKeyToPem(privateKey).getBytes(), KEY_PEM); + + LOGGER.debug("Attempt to create PEM keystore file and saving data. File name: {}", KEYSTORE_PEM); + writer.saveData(getDataAsBytes(keystoreData), KEYSTORE_PEM); + + LOGGER.debug("Attempt to create PEM truststore file and saving data. File name: {}", TRUSTSTORE_PEM); + writer.saveData(getDataAsBytes(truststoreData), TRUSTSTORE_PEM); + } + + private byte[] getDataAsBytes(List data) { + return String.join("\n", data).getBytes(); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/PemConverter.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/PemConverter.java new file mode 100644 index 00000000..b8f6719c --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/PemConverter.java @@ -0,0 +1,138 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openssl.PEMParser; +import org.onap.oom.certservice.client.certification.exception.PemConversionException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.security.KeyStore; +import java.security.KeyStore.LoadStoreParameter; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.util.List; +import java.util.Optional; + +class PemConverter { + + private static final Logger LOGGER = LoggerFactory.getLogger(PemConverter.class); + private static final String PASSWORD_ERROR_MSG = "Password should be min. 16 chars long and should contain only alphanumeric characters and special characters like Underscore (_), Dollar ($) and Pound (#)"; + private static final LoadStoreParameter EMPTY_KEYSTORE_CONFIGURATION = null; + private final String keyStoreType; + + public PemConverter(String keyStoreType) { + this.keyStoreType = keyStoreType; + } + + byte[] convertKeystore(List certificateChain, Password password, String alias, PrivateKey privateKey) + throws PemConversionException { + LOGGER.info("Conversion of PEM certificates to " + keyStoreType + " keystore"); + return convert(certificateChain, password, certs -> getKeyStore(alias, password, certs, privateKey)); + } + + byte[] convertTruststore(List trustAnchors, Password password, String alias) + throws PemConversionException { + LOGGER.info("Conversion of PEM certificates to " + keyStoreType + " truststore"); + return convert(trustAnchors, password, certs -> getTrustStore(alias, certs)); + } + + private byte[] convert(List certificates, Password password, StoreEntryOperation operation) + throws PemConversionException { + checkPassword(password); + final Certificate[] X509Certificates = convertToCertificateArray(certificates); + return getKeyStoreBytes(password, operation, X509Certificates); + } + + private void checkPassword(Password password) throws PemConversionException { + if (!password.isCorrectPasswordPattern()) { + LOGGER.error(PASSWORD_ERROR_MSG); + throw new PemConversionException(PASSWORD_ERROR_MSG); + } + } + + private byte[] getKeyStoreBytes(Password password, StoreEntryOperation op, Certificate[] x509Certificates) + throws PemConversionException { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + KeyStore ks = op.getStore(x509Certificates); + ks.store(bos, password.toCharArray()); + return bos.toByteArray(); + } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) { + LOGGER.error("Pem to " + keyStoreType + " converter failed, exception message: {}", e.getMessage()); + throw new PemConversionException(e); + } + } + + private KeyStore getKeyStore(String alias, Password password, Certificate[] certificates, PrivateKey privateKey) + throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { + KeyStore ks = getKeyStoreInstance(); + ks.setKeyEntry(alias, privateKey, password.toCharArray(), certificates); + return ks; + } + + private KeyStore getTrustStore(String alias, Certificate[] certificates) + throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { + KeyStore ks = getKeyStoreInstance(); + long index = 1L; + for (Certificate c : certificates) { + ks.setCertificateEntry(alias + index++, c); + } + return ks; + } + + private KeyStore getKeyStoreInstance() + throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { + KeyStore ks = KeyStore.getInstance(keyStoreType); + ks.load(EMPTY_KEYSTORE_CONFIGURATION); + return ks; + } + + private Certificate[] convertToCertificateArray(List certificates) + throws PemConversionException { + Certificate[] parsedCertificates = new Certificate[certificates.size()]; + for (String certificate : certificates) { + parsedCertificates[certificates.indexOf(certificate)] = parseCertificate(certificate); + } + return parsedCertificates; + } + + private Certificate parseCertificate(String certificate) throws PemConversionException { + try (PEMParser pem = new PEMParser(new StringReader(certificate))) { + X509CertificateHolder certHolder = Optional.ofNullable((X509CertificateHolder) pem.readObject()) + .orElseThrow( + () -> new PemConversionException("The certificate couldn't be parsed correctly. " + certificate)); + return new JcaX509CertificateConverter() + .setProvider(new BouncyCastleProvider()) + .getCertificate(certHolder); + } catch (IOException | CertificateException e) { + LOGGER.error("Certificates conversion failed, exception message: {}", e.getMessage()); + throw new PemConversionException(e); + } + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGenerator.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGenerator.java new file mode 100644 index 00000000..c65aa21d --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGenerator.java @@ -0,0 +1,52 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.apache.commons.lang3.RandomStringUtils; + +import java.security.SecureRandom; + +class RandomPasswordGenerator { + + private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; + private static final String NUMBERS = "0123456789"; + private static final String SPECIAL_CHARS = "_$#"; + private static final char[] SET_OF_CHARS = (ALPHA + ALPHA.toUpperCase() + NUMBERS + SPECIAL_CHARS).toCharArray(); + private static final char START_POSITION_IN_ASCII_CHARS = 0; + private static final char END_POSITION_IN_ASCII_CHARS = 0; + private static final boolean USE_LETTERS_ONLY = false; + private static final boolean USE_NUMBERS_ONLY = false; + + // We are excluding this line in Sonar due to fact that + //we are using new SecureRandom which provides + //cryptographic security + Password generate(int passwordLength) { + return new Password(RandomStringUtils.random(//NOSONAR + passwordLength, + START_POSITION_IN_ASCII_CHARS, + END_POSITION_IN_ASCII_CHARS, + USE_LETTERS_ONLY, + USE_NUMBERS_ONLY, + SET_OF_CHARS, + new SecureRandom()) + ); + } +} + diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/StoreEntryOperation.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/StoreEntryOperation.java new file mode 100644 index 00000000..aea6a7f5 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/conversion/StoreEntryOperation.java @@ -0,0 +1,34 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; + +@FunctionalInterface +public interface StoreEntryOperation { + + KeyStore getStore(Certificate[] certificates) + throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException; +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/CertFileWriterException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/CertFileWriterException.java new file mode 100644 index 00000000..2cbf330b --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/CertFileWriterException.java @@ -0,0 +1,35 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class CertFileWriterException extends ExitableException { + + public CertFileWriterException(Throwable cause) { + super(cause); + } + + @Override + public ExitStatus applicationExitStatus() { + return ExitStatus.FILE_CREATION_EXCEPTION; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/CsrGenerationException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/CsrGenerationException.java new file mode 100644 index 00000000..edf13570 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/CsrGenerationException.java @@ -0,0 +1,35 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class CsrGenerationException extends ExitableException { + private static final ExitStatus EXIT_STATUS = ExitStatus.CSR_GENERATION_EXCEPTION; + + public CsrGenerationException(Throwable cause) { + super(cause); + } + + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/KeyPairGenerationException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/KeyPairGenerationException.java new file mode 100644 index 00000000..fc344d4d --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/KeyPairGenerationException.java @@ -0,0 +1,36 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class KeyPairGenerationException extends ExitableException { + private static final ExitStatus EXIT_STATUS = ExitStatus.KEY_PAIR_GENERATION_EXCEPTION; + + public KeyPairGenerationException(String errorMessage) { + super(errorMessage); + } + + + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/PemConversionException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/PemConversionException.java new file mode 100644 index 00000000..17928350 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/PemConversionException.java @@ -0,0 +1,40 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class PemConversionException extends ExitableException { + private static final ExitStatus EXIT_STATUS = ExitStatus.PEM_CONVERSION_EXCEPTION; + + public PemConversionException(Throwable cause) { + super(cause); + } + + public PemConversionException(String message) { + super(message); + } + + @Override + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/PkEncodingException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/PkEncodingException.java new file mode 100644 index 00000000..c0b8ebdc --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/exception/PkEncodingException.java @@ -0,0 +1,35 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class PkEncodingException extends ExitableException { + private static final ExitStatus EXIT_STATUS = ExitStatus.PK_TO_PEM_ENCODING_EXCEPTION; + + public PkEncodingException(Throwable cause) { + super(cause); + } + + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/writer/CertFileWriter.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/writer/CertFileWriter.java new file mode 100644 index 00000000..0e6d0508 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/certification/writer/CertFileWriter.java @@ -0,0 +1,62 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.writer; + +import org.onap.oom.certservice.client.certification.exception.CertFileWriterException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Path; + +public class CertFileWriter { + + private static final Logger LOGGER = LoggerFactory.getLogger(CertFileWriter.class); + private final String destPath; + + private CertFileWriter(String destPath) { + this.destPath = destPath; + } + + public static CertFileWriter createWithDir(String destPath) { + createDirIfNotExists(destPath); + return new CertFileWriter(destPath); + } + + public void saveData(byte[] data, String filename) throws CertFileWriterException { + LOGGER.debug("Attempt to save file {} in path {}", filename, destPath); + try (FileOutputStream outputStream = new FileOutputStream(Path.of(destPath, filename).toString())) { + outputStream.write(data); + } catch (IOException e) { + LOGGER.error("File creation failed, exception message: {}", e.getMessage()); + throw new CertFileWriterException(e); + } + } + + private static void createDirIfNotExists(String destPath) { + File destFolderPath = new File(destPath); + if (!destFolderPath.exists()) { + LOGGER.debug("Destination path not exists, subdirectories are created"); + destFolderPath.mkdirs(); + } + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/common/Base64Encoder.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/common/Base64Encoder.java new file mode 100644 index 00000000..ddb9c7b8 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/common/Base64Encoder.java @@ -0,0 +1,28 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.common; + +import org.bouncycastle.util.encoders.Base64; + +public class Base64Encoder { + public String encode(String string) { + return new String(Base64.encode(string.getBytes())); + } +} \ No newline at end of file diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/ClientConfigurationEnvs.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/ClientConfigurationEnvs.java new file mode 100644 index 00000000..c29f5d97 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/ClientConfigurationEnvs.java @@ -0,0 +1,29 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +public enum ClientConfigurationEnvs { + REQUEST_URL, + REQUEST_TIMEOUT, + OUTPUT_PATH, + CA_NAME, + OUTPUT_TYPE +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/CsrConfigurationEnvs.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/CsrConfigurationEnvs.java new file mode 100644 index 00000000..27b4aa22 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/CsrConfigurationEnvs.java @@ -0,0 +1,31 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +public enum CsrConfigurationEnvs { + COMMON_NAME, + ORGANIZATION, + ORGANIZATION_UNIT, + LOCATION, + STATE, + COUNTRY, + SANS +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvProvider.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvProvider.java new file mode 100644 index 00000000..b86b0eca --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvProvider.java @@ -0,0 +1,38 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +import java.util.Optional; + +public class EnvProvider { + public Optional readEnvVariable(String envVariableName) { + return Optional.ofNullable(getSystemEnv(envVariableName)) + .filter(EnvProvider::isEnvPresent); + } + + String getSystemEnv(String envVariableName) { + return System.getenv(envVariableName); + } + + private static Boolean isEnvPresent(String envValue) { + return !"".equals(envValue); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForClient.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForClient.java new file mode 100644 index 00000000..26d508fe --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForClient.java @@ -0,0 +1,51 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +import java.util.Optional; + +public class EnvsForClient { + private final EnvProvider envProvider = new EnvProvider(); + + public Optional getUrlToCertService() { + return readEnv(ClientConfigurationEnvs.REQUEST_URL); + } + + public Optional getRequestTimeOut() { + return readEnv(ClientConfigurationEnvs.REQUEST_TIMEOUT); + } + + public Optional getOutputPath() { + return readEnv(ClientConfigurationEnvs.OUTPUT_PATH); + } + + public Optional getCaName() { + return readEnv(ClientConfigurationEnvs.CA_NAME); + } + + public Optional getOutputType() { + return readEnv(ClientConfigurationEnvs.OUTPUT_TYPE); + } + + private Optional readEnv(ClientConfigurationEnvs envName) { + return envProvider.readEnvVariable(envName.toString()); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForCsr.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForCsr.java new file mode 100644 index 00000000..5873bf10 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForCsr.java @@ -0,0 +1,59 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +import java.util.Optional; + +public class EnvsForCsr { + private final EnvProvider envProvider = new EnvProvider(); + + public Optional getCommonName() { + return readEnv(CsrConfigurationEnvs.COMMON_NAME); + } + + public Optional getOrganization() { + return readEnv(CsrConfigurationEnvs.ORGANIZATION); + } + + public Optional getOrganizationUnit() { + return readEnv(CsrConfigurationEnvs.ORGANIZATION_UNIT); + } + + public Optional getLocation() { + return readEnv(CsrConfigurationEnvs.LOCATION); + } + + public Optional getState() { + return readEnv(CsrConfigurationEnvs.STATE); + } + + public Optional getCountry() { + return readEnv(CsrConfigurationEnvs.COUNTRY); + } + + public Optional getSubjectAlternativesName() { + return readEnv(CsrConfigurationEnvs.SANS); + } + + Optional readEnv(CsrConfigurationEnvs envName) { + return envProvider.readEnvVariable(envName.toString()); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForTls.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForTls.java new file mode 100644 index 00000000..8e1333e6 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/EnvsForTls.java @@ -0,0 +1,47 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +import java.util.Optional; + +public class EnvsForTls { + private final EnvProvider envProvider = new EnvProvider(); + + public Optional getKeystorePath() { + return readEnv(TlsConfigurationEnvs.KEYSTORE_PATH); + } + + public Optional getKeystorePassword() { + return readEnv(TlsConfigurationEnvs.KEYSTORE_PASSWORD); + } + + public Optional getTruststorePath() { + return readEnv(TlsConfigurationEnvs.TRUSTSTORE_PATH); + } + + public Optional getTruststorePassword() { + return readEnv(TlsConfigurationEnvs.TRUSTSTORE_PASSWORD); + } + + Optional readEnv(TlsConfigurationEnvs envName) { + return envProvider.readEnvVariable(envName.toString()); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/TlsConfigurationEnvs.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/TlsConfigurationEnvs.java new file mode 100644 index 00000000..de5050b5 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/TlsConfigurationEnvs.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +public enum TlsConfigurationEnvs { + KEYSTORE_PATH, + KEYSTORE_PASSWORD, + TRUSTSTORE_PATH, + TRUSTSTORE_PASSWORD +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/ClientConfigurationException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/ClientConfigurationException.java new file mode 100644 index 00000000..b75c9e13 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/ClientConfigurationException.java @@ -0,0 +1,36 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class ClientConfigurationException extends ExitableException { + private static final ExitStatus EXIT_STATUS = ExitStatus.CLIENT_CONFIGURATION_EXCEPTION; + + public ClientConfigurationException(String message) { + super(message); + } + + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/CsrConfigurationException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/CsrConfigurationException.java new file mode 100644 index 00000000..85fda772 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/CsrConfigurationException.java @@ -0,0 +1,36 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class CsrConfigurationException extends ExitableException { + private static final ExitStatus EXIT_STATUS = ExitStatus.CSR_CONFIGURATION_EXCEPTION; + + public CsrConfigurationException(String message) { + super(message); + } + + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationException.java new file mode 100644 index 00000000..6372c0b6 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationException.java @@ -0,0 +1,36 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class TlsConfigurationException extends ExitableException { + private static final ExitStatus EXIT_STATUS = ExitStatus.TLS_CONFIGURATION_EXCEPTION; + + public TlsConfigurationException(String message) { + super(message); + } + + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactory.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactory.java new file mode 100644 index 00000000..293ac2d1 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactory.java @@ -0,0 +1,77 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.factory; + + +import org.onap.oom.certservice.client.certification.ArtifactsCreatorProvider; +import org.onap.oom.certservice.client.configuration.exception.ClientConfigurationException; +import org.onap.oom.certservice.client.configuration.exception.CsrConfigurationException; +import org.onap.oom.certservice.client.configuration.model.ConfigurationModel; + +import java.util.Arrays; +import java.util.Locale; +import java.util.regex.Pattern; + +public abstract class AbstractConfigurationFactory { + + abstract T create() throws ClientConfigurationException, CsrConfigurationException; + + public boolean isPathValid(String path) { + return path.matches("^/|(/[a-zA-Z0-9_-]+)+/?$"); + } + + public boolean isAlphaNumeric(String caName) { + return caName.matches("^[a-zA-Z0-9]*$"); + } + + public boolean isCommonNameValid(String commonName) { + return !isSpecialCharsPresent(commonName) + && !isHttpProtocolsPresent(commonName) + && !isIpAddressPresent(commonName) + && !isPortNumberPresent(commonName); + } + + public boolean isSpecialCharsPresent(String stringToCheck) { + return Pattern.compile("[~#@*$+%!()?/{}<>\\|_^]").matcher(stringToCheck).find(); + } + + public boolean isCountryValid(String country) { + return Arrays.asList(Locale.getISOCountries()).contains(country); + } + + public boolean isOutputTypeValid(String outputType) { + return Arrays.stream(ArtifactsCreatorProvider.values()) + .map(ArtifactsCreatorProvider::toString) + .anyMatch(name -> name.equals(outputType)); + } + + private boolean isPortNumberPresent(String stringToCheck) { + return Pattern.compile(":[0-9]{1,5}").matcher(stringToCheck).find(); + } + + private boolean isIpAddressPresent(String stringToCheck) { + return Pattern.compile("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}").matcher(stringToCheck).find(); + } + + private boolean isHttpProtocolsPresent(String stringToCheck) { + return Pattern.compile("[h][t][t][p][:][/][/]|[h][t][t][p][s][:][/][/]").matcher(stringToCheck).find(); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactory.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactory.java new file mode 100644 index 00000000..17cb2cc4 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactory.java @@ -0,0 +1,76 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.factory; + +import org.onap.oom.certservice.client.configuration.ClientConfigurationEnvs; +import org.onap.oom.certservice.client.configuration.EnvsForClient; +import org.onap.oom.certservice.client.configuration.exception.ClientConfigurationException; +import org.onap.oom.certservice.client.configuration.model.ClientConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; + +public class ClientConfigurationFactory extends AbstractConfigurationFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientConfigurationFactory.class); + private final EnvsForClient envsForClient; + + public ClientConfigurationFactory(EnvsForClient envsForClient) { + this.envsForClient = envsForClient; + } + + @Override + public ClientConfiguration create() throws ClientConfigurationException { + + ClientConfiguration configuration = new ClientConfiguration(); + + + envsForClient.getUrlToCertService() + .map(configuration::setUrlToCertService); + + envsForClient.getRequestTimeOut() + .map(timeout -> configuration.setRequestTimeout(Integer.valueOf(timeout))); + + envsForClient.getOutputPath() + .filter(this::isPathValid) + .map(configuration::setCertsOutputPath) + .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.OUTPUT_PATH + " is invalid.")); + + envsForClient.getCaName() + .filter(this::isAlphaNumeric) + .map(configuration::setCaName) + .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.CA_NAME + " is invalid.")); + + Optional outputType = envsForClient.getOutputType(); + + if (outputType.isPresent()) { + outputType.filter(this::isOutputTypeValid) + .map(configuration::setOutputType) + .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.OUTPUT_TYPE + " is invalid.")); + } + + LOGGER.info("Successful validation of Client configuration. Configuration data: {}", configuration.toString()); + + return configuration; + } +} + diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactory.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactory.java new file mode 100644 index 00000000..0a88252c --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactory.java @@ -0,0 +1,77 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.factory; + +import org.onap.oom.certservice.client.configuration.CsrConfigurationEnvs; +import org.onap.oom.certservice.client.configuration.EnvsForCsr; +import org.onap.oom.certservice.client.configuration.exception.CsrConfigurationException; +import org.onap.oom.certservice.client.configuration.model.CsrConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class CsrConfigurationFactory extends AbstractConfigurationFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(CsrConfigurationFactory.class); + private final EnvsForCsr envsForCsr; + + public CsrConfigurationFactory(EnvsForCsr envsForCsr) { + this.envsForCsr = envsForCsr; + } + + @Override + public CsrConfiguration create() throws CsrConfigurationException { + + CsrConfiguration configuration = new CsrConfiguration(); + + envsForCsr.getCommonName() + .filter(this::isCommonNameValid) + .map(configuration::setCommonName) + .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COMMON_NAME + " is invalid.")); + + envsForCsr.getOrganization() + .filter(org -> !isSpecialCharsPresent(org)) + .map(configuration::setOrganization) + .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.ORGANIZATION + " is invalid.")); + + envsForCsr.getState() + .map(configuration::setState) + .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.STATE + " is invalid.")); + + envsForCsr.getCountry() + .filter(this::isCountryValid) + .map(configuration::setCountry) + .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COUNTRY + " is invalid.")); + + envsForCsr.getOrganizationUnit() + .map(configuration::setOrganizationUnit); + + envsForCsr.getLocation() + .map(configuration::setLocation); + + envsForCsr.getSubjectAlternativesName() + .map(configuration::setSubjectAlternativeNames); + + LOGGER.info("Successful validation of CSR configuration. Configuration data: {}", configuration.toString()); + + return configuration; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactory.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactory.java new file mode 100644 index 00000000..9fac626e --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactory.java @@ -0,0 +1,85 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.factory; + +import org.apache.http.ssl.SSLContexts; +import org.onap.oom.certservice.client.configuration.EnvsForTls; +import org.onap.oom.certservice.client.configuration.TlsConfigurationEnvs; +import org.onap.oom.certservice.client.configuration.exception.TlsConfigurationException; + +import javax.net.ssl.SSLContext; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + +public class SslContextFactory { + + private static final String JKS = "jks"; + + private EnvsForTls envsForTls; + + public SslContextFactory(EnvsForTls envsForTls) { + this.envsForTls = envsForTls; + } + + public SSLContext create() throws TlsConfigurationException { + String keystorePath = envsForTls.getKeystorePath() + .orElseThrow(() -> new TlsConfigurationException(createEnvMissingMessage(TlsConfigurationEnvs.KEYSTORE_PATH))); + String keystorePassword = envsForTls.getKeystorePassword() + .orElseThrow(() -> new TlsConfigurationException(createEnvMissingMessage(TlsConfigurationEnvs.KEYSTORE_PASSWORD))); + String truststorePath = envsForTls.getTruststorePath() + .orElseThrow(() -> new TlsConfigurationException(createEnvMissingMessage(TlsConfigurationEnvs.TRUSTSTORE_PATH))); + String truststorePassword = envsForTls.getTruststorePassword() + .orElseThrow(() -> new TlsConfigurationException(createEnvMissingMessage(TlsConfigurationEnvs.TRUSTSTORE_PASSWORD))); + + return createSslContext(keystorePath, keystorePassword, truststorePath, truststorePassword); + } + + private String createEnvMissingMessage(TlsConfigurationEnvs keystorePath) { + return String.format("%s env is missing.", keystorePath); + } + + private KeyStore setupKeystore(String keystorePath, String certPassword) + throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { + KeyStore keyStore = KeyStore.getInstance(JKS); + FileInputStream identityKeyStoreFile = new FileInputStream(new File( + keystorePath)); + keyStore.load(identityKeyStoreFile, certPassword.toCharArray()); + return keyStore; + } + + private SSLContext createSslContext(String keystorePath, String keystorePassword, String truststorePath, String truststorePassword) throws TlsConfigurationException { + try { + KeyStore identityKeystore = setupKeystore(keystorePath, keystorePassword); + KeyStore trustKeystore = setupKeystore(truststorePath, truststorePassword); + + return SSLContexts.custom() + .loadKeyMaterial(identityKeystore, keystorePassword.toCharArray()) + .loadTrustMaterial(trustKeystore, null) + .build(); + } catch (Exception e) { + throw new TlsConfigurationException("TLS configuration exception: " + e); + } + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/ClientConfiguration.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/ClientConfiguration.java new file mode 100644 index 00000000..cd8a5c1e --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/ClientConfiguration.java @@ -0,0 +1,99 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.model; + +import org.onap.oom.certservice.client.configuration.ClientConfigurationEnvs; + +public class ClientConfiguration implements ConfigurationModel { + + private static final Integer DEFAULT_TIMEOUT_MS = 30000; + private static final String DEFAULT_REQUEST_URL = "https://oom-cert-service:8443/v1/certificate/"; + private static final String DEFAULT_OUTPUT_TYPE = "P12"; + + private String urlToCertService; + private Integer requestTimeout; + private String certsOutputPath; + private String caName; + private String outputType; + + + public ClientConfiguration() { + urlToCertService = DEFAULT_REQUEST_URL; + requestTimeout = DEFAULT_TIMEOUT_MS; + outputType = DEFAULT_OUTPUT_TYPE; + } + + + public String getUrlToCertService() { + return urlToCertService; + } + + public ClientConfiguration setUrlToCertService(String urlToCertService) { + this.urlToCertService = urlToCertService; + return this; + } + + public Integer getRequestTimeout() { + return requestTimeout; + } + + public ClientConfiguration setRequestTimeout(Integer requestTimeout) { + this.requestTimeout = requestTimeout; + return this; + } + + public String getCertsOutputPath() { + return certsOutputPath; + } + + public ClientConfiguration setCertsOutputPath(String certsOutputPath) { + this.certsOutputPath = certsOutputPath; + return this; + } + + public String getCaName() { + return caName; + } + + public ClientConfiguration setCaName(String caName) { + this.caName = caName; + return this; + } + + public String getOutputType() { + return outputType; + } + + public ClientConfiguration setOutputType(String outputType) { + this.outputType = outputType; + return this; + } + + @Override + public String toString() { + return String.format("%s: %s, %s: %s, %s: %s, %s: %s, %s: %s", + ClientConfigurationEnvs.REQUEST_URL, urlToCertService, + ClientConfigurationEnvs.REQUEST_TIMEOUT, requestTimeout, + ClientConfigurationEnvs.OUTPUT_PATH, certsOutputPath, + ClientConfigurationEnvs.CA_NAME, caName, + ClientConfigurationEnvs.OUTPUT_TYPE, outputType); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/ConfigurationModel.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/ConfigurationModel.java new file mode 100644 index 00000000..2c058d74 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/ConfigurationModel.java @@ -0,0 +1,24 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.model; + +public interface ConfigurationModel { +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/CsrConfiguration.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/CsrConfiguration.java new file mode 100644 index 00000000..c5aefd97 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/CsrConfiguration.java @@ -0,0 +1,111 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.model; + + +import org.onap.oom.certservice.client.configuration.CsrConfigurationEnvs; + +public class CsrConfiguration implements ConfigurationModel { + + private String commonName; + private String organization; + private String state; + private String country; + private String organizationUnit; + private String location; + private String sans; + + + public String getCommonName() { + return commonName; + } + + public CsrConfiguration setCommonName(String commonName) { + this.commonName = commonName; + return this; + } + + public String getOrganization() { + return organization; + } + + public CsrConfiguration setOrganization(String organization) { + this.organization = organization; + return this; + } + + public String getState() { + return state; + } + + public CsrConfiguration setState(String state) { + this.state = state; + return this; + } + + public String getCountry() { + return country; + } + + public CsrConfiguration setCountry(String country) { + this.country = country; + return this; + } + + public String getOrganizationUnit() { + return organizationUnit; + } + + public CsrConfiguration setOrganizationUnit(String organizationUnit) { + this.organizationUnit = organizationUnit; + return this; + } + + public String getLocation() { + return location; + } + + public CsrConfiguration setLocation(String location) { + this.location = location; + return this; + } + + public String getSans() { + return sans; + } + + public CsrConfiguration setSubjectAlternativeNames(String subjectAlternativeNames) { + this.sans = subjectAlternativeNames; + return this; + } + + @Override + public String toString() { + return String.format("%s: %s, %s: %s, %s: %s, %s: %s, %s: %s, %s: %s, %s: %s", + CsrConfigurationEnvs.COMMON_NAME, commonName, + CsrConfigurationEnvs.COUNTRY, country, + CsrConfigurationEnvs.STATE, state, + CsrConfigurationEnvs.ORGANIZATION, organization, + CsrConfigurationEnvs.ORGANIZATION_UNIT, organizationUnit, + CsrConfigurationEnvs.LOCATION, location, + CsrConfigurationEnvs.SANS, sans); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/CloseableHttpsClientProvider.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/CloseableHttpsClientProvider.java new file mode 100644 index 00000000..6b6690b6 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/CloseableHttpsClientProvider.java @@ -0,0 +1,51 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.httpclient; + +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; + +import javax.net.ssl.SSLContext; + +public class CloseableHttpsClientProvider { + + private final int timeout; + private final SSLContext sslContext; + + public CloseableHttpsClientProvider(SSLContext sslContext, int timeout) { + this.sslContext = sslContext; + this.timeout = timeout; + } + + public CloseableHttpClient getClient() { + RequestConfig config = + RequestConfig.custom() + .setConnectionRequestTimeout(timeout) + .setConnectTimeout(timeout) + .setSocketTimeout(timeout) + .build(); + + return HttpClientBuilder.create() + .setSSLContext(sslContext) + .setDefaultRequestConfig(config).build(); + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/HttpClient.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/HttpClient.java new file mode 100644 index 00000000..7dba6b59 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/HttpClient.java @@ -0,0 +1,111 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.httpclient; + +import com.google.gson.Gson; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.util.EntityUtils; +import org.onap.oom.certservice.client.httpclient.exception.CertServiceApiResponseException; +import org.onap.oom.certservice.client.httpclient.exception.HttpClientException; +import org.onap.oom.certservice.client.httpclient.model.CertServiceResponse; +import org.onap.oom.certservice.client.httpclient.model.ErrorCertServiceResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +public class HttpClient { + + private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class); + private static final String CSR_HEADER_NAME = "CSR"; + private static final String PK_HEADER_NAME = "PK"; + private static final String CHARSET_UTF_8 = "UTF-8"; + + private final Gson gson = new Gson(); + private final CloseableHttpsClientProvider httpClientProvider; + private final String certServiceAddress; + + public HttpClient(CloseableHttpsClientProvider httpClientProvider, String certServiceAddress) { + this.httpClientProvider = httpClientProvider; + this.certServiceAddress = certServiceAddress; + } + + public CertServiceResponse retrieveCertServiceData(String caName, String csr, String encodedPk) + throws CertServiceApiResponseException, HttpClientException { + + try (CloseableHttpClient httpClient = httpClientProvider.getClient()) { + LOGGER.info("Attempt to send request to API, on url: {}{} ", certServiceAddress, caName); + HttpResponse httpResponse = httpClient.execute(createHttpRequest(caName, csr, encodedPk)); + LOGGER.info("Received response from API"); + return extractCertServiceResponse(httpResponse); + + } catch (IOException e) { + LOGGER.error("Failed execute request to API for URL: {}{} , exception message: {}", + certServiceAddress, caName, e.getMessage()); + throw new HttpClientException(e); + } + } + + private HttpGet createHttpRequest(String caName, String csr, String pk) { + String url = certServiceAddress + caName; + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader(CSR_HEADER_NAME, csr); + httpGet.addHeader(PK_HEADER_NAME, pk); + return httpGet; + } + + private CertServiceResponse extractCertServiceResponse(HttpResponse httpResponse) + throws CertServiceApiResponseException, HttpClientException { + int httpResponseCode = getStatusCode(httpResponse); + if (HttpStatus.SC_OK != httpResponseCode) { + LOGGER.error("Error on API response. Response Code: {}", httpResponseCode); + throw generateApiResponseException(httpResponse); + } + String jsonResponse = getStringResponse(httpResponse.getEntity()); + return gson.fromJson(jsonResponse, CertServiceResponse.class); + } + + private CertServiceApiResponseException generateApiResponseException(HttpResponse httpResponse) + throws HttpClientException { + String stringResponse = getStringResponse(httpResponse.getEntity()); + ErrorCertServiceResponse errorCertServiceResponse = + gson.fromJson(stringResponse, ErrorCertServiceResponse.class); + + return new CertServiceApiResponseException(getStatusCode(httpResponse), errorCertServiceResponse.getMessage()); + } + + private int getStatusCode(HttpResponse httpResponse) { + return httpResponse.getStatusLine().getStatusCode(); + } + + private String getStringResponse(HttpEntity httpEntity) throws HttpClientException { + try { + return EntityUtils.toString(httpEntity, CHARSET_UTF_8); + } catch (IOException e) { + LOGGER.error("Cannot parse response to string, exception message: {}", e.getMessage()); + throw new HttpClientException(e); + } + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/exception/CertServiceApiResponseException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/exception/CertServiceApiResponseException.java new file mode 100644 index 00000000..30ca0db3 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/exception/CertServiceApiResponseException.java @@ -0,0 +1,41 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.httpclient.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class CertServiceApiResponseException extends ExitableException { + private static final ExitStatus EXIT_STATUS = ExitStatus.CERT_SERVICE_API_CONNECTION_EXCEPTION; + + public CertServiceApiResponseException(int responseCode, String messageFromApi) { + + super(String.format("CertService HTTP unsuccessful response. Response code: %d . Message from Service: %s", + responseCode, + messageFromApi)); + } + + @Override + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; + } + +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/exception/HttpClientException.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/exception/HttpClientException.java new file mode 100644 index 00000000..ff286619 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/exception/HttpClientException.java @@ -0,0 +1,37 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.httpclient.exception; + +import org.onap.oom.certservice.client.api.ExitStatus; +import org.onap.oom.certservice.client.api.ExitableException; + +public class HttpClientException extends ExitableException { + private static final ExitStatus EXIT_STATUS = ExitStatus.HTTP_CLIENT_EXCEPTION; + + public HttpClientException(Throwable cause) { + super(cause); + } + + @Override + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/model/CertServiceResponse.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/model/CertServiceResponse.java new file mode 100644 index 00000000..453dfd53 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/model/CertServiceResponse.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.httpclient.model; + +import java.util.Collections; +import java.util.List; + +public class CertServiceResponse { + + private final List certificateChain; + private final List trustedCertificates; + + public CertServiceResponse(List certificateChain, List trustedCertificates) { + this.certificateChain = certificateChain; + this.trustedCertificates = trustedCertificates; + } + + public List getCertificateChain() { + return Collections.unmodifiableList(certificateChain); + } + + public List getTrustedCertificates() { + return Collections.unmodifiableList(trustedCertificates); + } + +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/model/ErrorCertServiceResponse.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/model/ErrorCertServiceResponse.java new file mode 100644 index 00000000..2304ddcd --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/httpclient/model/ErrorCertServiceResponse.java @@ -0,0 +1,35 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.httpclient.model; + +public class ErrorCertServiceResponse { + + private final String errorMessage; + + public ErrorCertServiceResponse(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getMessage() { + return errorMessage; + } + +} diff --git a/certServiceClient/src/main/resources/log4j2.xml b/certServiceClient/src/main/resources/log4j2.xml index bf4b6239..a641a4e0 100644 --- a/certServiceClient/src/main/resources/log4j2.xml +++ b/certServiceClient/src/main/resources/log4j2.xml @@ -8,7 +8,7 @@ pattern="%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=green, DEBUG=green bold, TRACE=blue} %style{%pid}{magenta} [%15.15t] %style{%-40.40C{1.}}{cyan} : %m%n%throwable"/> - diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CerServiceRequestTestData.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CerServiceRequestTestData.java deleted file mode 100644 index 8f252c31..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CerServiceRequestTestData.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; - -public final class CerServiceRequestTestData { - - private static final String RESOURCE_PATH = "src/test/resources/"; - - // Request parameters - public static final String CA_NAME = "TestCA"; - public static final String CSR = getCsrValue(); - public static final String PK = getPkValue(); - - // Correct response data - public static final String CORRECT_RESPONSE = getCorrectResponse(); - public static final String EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN = - getExpectedFirstElementOfCertificateChain(); - public static final String EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES = - getExpectedFirstElementOfTrustedCertificates(); - - // Error response data - public static final String MISSING_PK_RESPONSE = getMissingPkResponse(); - - private CerServiceRequestTestData() { - } - - private static String getMissingPkResponse() { - String fileName = "missingPkResponse"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getExpectedFirstElementOfTrustedCertificates() { - - String fileName = "expectedFirstElementOfTrustedCertificates"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getExpectedFirstElementOfCertificateChain() { - String fileName = "expectedFirstElementOfCertificateChain"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getCorrectResponse() { - String fileName = "correctResponse"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getPkValue() { - String fileName = "testPk"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String getCsrValue() { - String fileName = "testCsr"; - return readFromFile(RESOURCE_PATH + fileName); - } - - private static String readFromFile(String path) { - try { - return Files.readString(Paths.get(path), StandardCharsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - return "File not found"; - } - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java deleted file mode 100644 index 9e256f98..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Spy; -import org.mockito.junit.jupiter.MockitoExtension; - -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.verify; -import static org.onap.aaf.certservice.client.api.ExitStatus.CLIENT_CONFIGURATION_EXCEPTION; -import static org.onap.aaf.certservice.client.api.ExitStatus.SUCCESS; - -@ExtendWith(MockitoExtension.class) -class CertServiceClientTest { - @Spy - AppExitHandler appExitHandler = new AppExitHandler(); - - @Test - void shouldExitWithDefinedExitCode_onRunCallWhenNoEnvsPresent() { - // given - doNothing().when(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); - doNothing().when(appExitHandler).exit(SUCCESS); - CertServiceClient certServiceClient = new CertServiceClient(appExitHandler); - // when - certServiceClient.run(); - // then - verify(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); - verify(appExitHandler).exit(SUCCESS); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProviderTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProviderTest.java deleted file mode 100644 index 46bacef8..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/ArtifactsCreatorProviderTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.ValueSource; -import org.onap.aaf.certservice.client.certification.conversion.ArtifactsCreator; -import org.onap.aaf.certservice.client.certification.conversion.ConvertedArtifactsCreator; -import org.onap.aaf.certservice.client.certification.conversion.PemArtifactsCreator; - -import static org.assertj.core.api.Assertions.assertThat; - - -class ArtifactsCreatorProviderTest { - - private static final String P12 = "P12"; - private static final String JKS = "JKS"; - private static final String PEM = "PEM"; - private static final String TEST_PATH = "testPath"; - - @ParameterizedTest - @ValueSource(strings = {JKS, P12}) - void artifactsProviderShouldReturnConvertedCreator(String outputType) { - - // when - ArtifactsCreator artifactsCreator = - ArtifactsCreatorProvider.get(outputType, TEST_PATH); - // then - assertThat(artifactsCreator).isInstanceOf(ConvertedArtifactsCreator.class); - } - - @Test - void artifactsProviderShouldReturnPemCreator() { - - // when - ArtifactsCreator artifactsCreator = - ArtifactsCreatorProvider.get(PEM, TEST_PATH); - // then - assertThat(artifactsCreator).isInstanceOf(PemArtifactsCreator.class); - } - - @ParameterizedTest - @CsvSource({ - "JKS, jks", - "P12, p12"}) - void getExtensionShouldProvideExtensionBasedOnArtifactType(String artifactType, String expectedExtension) { - - //when - String actualExtension = ArtifactsCreatorProvider.valueOf(artifactType).getExtension(); - //then - assertThat(actualExtension).isEqualTo(expectedExtension); - } - -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/CsrFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/CsrFactoryTest.java deleted file mode 100644 index ae18e6fb..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/CsrFactoryTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification; - - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.certification.exception.CsrGenerationException; -import org.onap.aaf.certservice.client.certification.exception.KeyPairGenerationException; -import org.onap.aaf.certservice.client.configuration.model.CsrConfiguration; - -import java.security.KeyPair; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class CsrFactoryTest { - - CsrConfiguration config = mock(CsrConfiguration.class); - - - @Test - void createEncodedCsr_shouldSucceedWhenAllFieldsAreSetCorrectly() throws KeyPairGenerationException, CsrGenerationException { - - KeyPair keyPair = - new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, EncryptionAlgorithmConstants.KEY_SIZE).create(); - - when(config.getCommonName()).thenReturn("onap.org"); - when(config.getSans()).thenReturn("onapexample.com:onapexample.com.pl:onapexample.pl"); - when(config.getCountry()).thenReturn("US"); - when(config.getLocation()).thenReturn("San-Francisco"); - when(config.getOrganization()).thenReturn("Linux-Foundation"); - when(config.getOrganizationUnit()).thenReturn("ONAP"); - when(config.getState()).thenReturn("California"); - - assertThat(new CsrFactory(config).createCsrInPem(keyPair)).isNotEmpty(); - } -} - diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/KeyPairFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/KeyPairFactoryTest.java deleted file mode 100644 index 3d3d3c17..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/KeyPairFactoryTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification; - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.certification.exception.KeyPairGenerationException; - -import java.security.KeyPair; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -class KeyPairFactoryTest { - private static final String NOT_EXISTING_ENCRYPTION_ALGORITHM = "FAKE_ALGORITHM"; - - @Test - public void shouldProvideKeyPair_whenCreateKeyPairCalledWithCorrectArguments() throws KeyPairGenerationException { - // given - KeyPairFactory keyPairFactory = new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, - EncryptionAlgorithmConstants.KEY_SIZE); - // when - KeyPair keyPair = keyPairFactory.create(); - // then - assertThat(keyPair).isInstanceOf(KeyPair.class); - } - - @Test - public void shouldThrowKeyPairGenerationException_whenCreateTryCalledOnNotExistingAlgorithm() { - // given - KeyPairFactory keyPairFactory = new KeyPairFactory(NOT_EXISTING_ENCRYPTION_ALGORITHM, - EncryptionAlgorithmConstants.KEY_SIZE); - // when, then - assertThatThrownBy(keyPairFactory::create).isInstanceOf(KeyPairGenerationException.class); - } - -} \ No newline at end of file diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoderTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoderTest.java deleted file mode 100644 index 41f15bb7..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoderTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification; - - -import org.bouncycastle.util.io.pem.PemObject; -import org.bouncycastle.util.io.pem.PemReader; -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.certification.exception.PkEncodingException; - -import java.io.IOException; -import java.io.StringReader; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; - -import static org.assertj.core.api.Assertions.assertThat; - -class PrivateKeyToPemEncoderTest { - - private static final String ENCRYPTION_ALGORITHM = "RSA"; - private static final String RESOURCES_DIR = "src/test/resources/"; - private static final String PRIVATE_KEY_PEM_PATH = RESOURCES_DIR + "rsaPrivateKeyPem"; - - @Test - void shouldReturnProperlyEncodedPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException, PkEncodingException, IOException { - //given - String expectedPem = Files.readString(Paths.get(PRIVATE_KEY_PEM_PATH)); - PrivateKeyToPemEncoder testedPkEncoder = new PrivateKeyToPemEncoder(); - //when - PrivateKey privateKey = extractPrivateKeyFromPem(expectedPem); - String resultPkInPem = testedPkEncoder.encodePrivateKeyToPem(privateKey); - //then - assertThat(resultPkInPem).isEqualTo(expectedPem); - } - - private PrivateKey extractPrivateKeyFromPem(String pem) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { - PemReader pemReader = new PemReader(new StringReader(pem)); - PemObject pemObject = pemReader.readPemObject(); - pemReader.close(); - PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pemObject.getContent()); - KeyFactory kf = KeyFactory.getInstance(ENCRYPTION_ALGORITHM); - return kf.generatePrivate(spec); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java deleted file mode 100644 index e13f8be8..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.certification.exception.CertFileWriterException; -import org.onap.aaf.certservice.client.certification.exception.PemConversionException; -import org.onap.aaf.certservice.client.certification.writer.CertFileWriter; - -import java.security.PrivateKey; -import java.util.List; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -class ConvertedArtifactsCreatorTest { - - private static final int PASSWORD_LENGTH = 24; - private static final String CERTIFICATE_ALIAS = "certificate"; - private static final String TRUSTED_CERTIFICATE_ALIAS = "trusted-certificate-"; - - private static final Password SAMPLE_PASSWORD = new Password("d9D_u8LooYaXH4G48DtN#vw0"); - private static final List SAMPLE_KEYSTORE_CERTIFICATE_CHAIN = List.of("a", "b"); - private static final List SAMPLE_TRUSTED_CERTIFICATE_CHAIN = List.of("c", "d"); - private static final byte[] SAMPLE_KEYSTORE_BYTES = "this is a keystore test".getBytes(); - private static final byte[] SAMPLE_TRUSTSTORE_BYTES = "this is a truststore test".getBytes(); - private static final String P12_EXTENSION = "p12"; - - private CertFileWriter certFileWriter; - private RandomPasswordGenerator passwordGenerator; - private PemConverter converter; - private PrivateKey privateKey; - private ConvertedArtifactsCreator artifactsCreator; - - - @BeforeEach - void setUp() { - certFileWriter = mock(CertFileWriter.class); - passwordGenerator = mock(RandomPasswordGenerator.class); - converter = mock(PemConverter.class); - privateKey = mock(PrivateKey.class); - artifactsCreator = new ConvertedArtifactsCreator(certFileWriter, passwordGenerator, converter, P12_EXTENSION); - } - - @Test - void convertedArtifactCreatorShouldTryCreateFileWithGivenExtension() - throws CertFileWriterException, PemConversionException { - //given - mockPasswordGeneratorAndPemConverter(); - final String keystore = "keystore"; - final String testExtension = "testExt"; - final String keystoreFileName = String.format("%s.%s", keystore, testExtension); - artifactsCreator = new ConvertedArtifactsCreator(certFileWriter, passwordGenerator, converter, testExtension); - - //when - artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); - - //then - verify(certFileWriter, times(1)) - .saveData(SAMPLE_KEYSTORE_BYTES, keystoreFileName); - } - - @Test - void convertedArtifactsCreatorShouldCallConverterAndFilesCreatorMethods() - throws PemConversionException, CertFileWriterException { - // given - mockPasswordGeneratorAndPemConverter(); - final String keystoreP12 = "keystore.p12"; - final String keystorePass = "keystore.pass"; - - //when - artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); - - // then - verify(converter, times(1)) - .convertKeystore(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, CERTIFICATE_ALIAS, privateKey); - verify(certFileWriter, times(1)) - .saveData(SAMPLE_KEYSTORE_BYTES, keystoreP12); - verify(certFileWriter, times(1)) - .saveData(SAMPLE_PASSWORD.getCurrentPassword().getBytes(), keystorePass); - verify(converter, times(1)) - .convertTruststore(SAMPLE_TRUSTED_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, TRUSTED_CERTIFICATE_ALIAS); - } - - @Test - void convertedArtifactsCreatorShouldCallPasswordGeneratorTwice() - throws PemConversionException, CertFileWriterException { - // given - mockPasswordGeneratorAndPemConverter(); - - //when - artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); - - // then - verify(passwordGenerator, times(2)).generate(PASSWORD_LENGTH); - } - - private void mockPasswordGeneratorAndPemConverter() throws PemConversionException { - when(passwordGenerator.generate(PASSWORD_LENGTH)).thenReturn(SAMPLE_PASSWORD); - when(converter.convertKeystore(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, CERTIFICATE_ALIAS, privateKey)) - .thenReturn(SAMPLE_KEYSTORE_BYTES); - when(converter.convertTruststore(SAMPLE_TRUSTED_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, TRUSTED_CERTIFICATE_ALIAS)) - .thenReturn(SAMPLE_TRUSTSTORE_BYTES); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreatorTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreatorTest.java deleted file mode 100644 index 5e79b96f..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemArtifactsCreatorTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.api.ExitableException; -import org.onap.aaf.certservice.client.certification.PrivateKeyToPemEncoder; -import org.onap.aaf.certservice.client.certification.writer.CertFileWriter; - -import java.security.PrivateKey; -import java.util.List; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -class PemArtifactsCreatorTest { - private static final String KEYSTORE_PEM = "keystore.pem"; - private static final String TRUSTSTORE_PEM = "truststore.pem"; - private static final String KEY_PEM = "key.pem"; - private static final String KEY = "my private key"; - private CertFileWriter certFileWriter = mock(CertFileWriter.class); - private PrivateKey privateKey = mock(PrivateKey.class); - private PrivateKeyToPemEncoder pkEncoder = mock(PrivateKeyToPemEncoder.class); - - @Test - void pemArtifactsCreatorShouldCallRequiredMethods() throws ExitableException { - // given - final PemArtifactsCreator creator = new PemArtifactsCreator(certFileWriter, pkEncoder); - - // when - when(pkEncoder.encodePrivateKeyToPem(privateKey)).thenReturn(KEY); - creator.create(List.of("one", "two"), List.of("three", "four"), privateKey); - - // then - verify(certFileWriter, times(1)).saveData("one\ntwo".getBytes(), KEYSTORE_PEM); - verify(certFileWriter, times(1)).saveData("three\nfour".getBytes(), TRUSTSTORE_PEM); - verify(certFileWriter, times(1)).saveData(KEY.getBytes(), KEY_PEM); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemConverterTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemConverterTest.java deleted file mode 100644 index e3a58c3f..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/PemConverterTest.java +++ /dev/null @@ -1,206 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants; -import org.onap.aaf.certservice.client.certification.exception.PemConversionException; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class PemConverterTest { - - private static final String RESOURCES_PATH = "src/test/resources"; - private static final String CERT1_PATH = RESOURCES_PATH + "/cert1.pem"; - private static final String CERT2_PATH = RESOURCES_PATH + "/cert2.pem"; - private static final String KEY_PATH = RESOURCES_PATH + "/privateKey"; - private static final String EXPECTED_KEYSTORE_PATH = RESOURCES_PATH + "/expectedKeystore.jks"; - private static final String EXPECTED_TRUSTSTORE_PATH = RESOURCES_PATH + "/expectedTruststore.jks"; - private static final String PKCS12 = "PKCS12"; - private static final String PKCS8 = "PKCS#8"; - private static final String JKS = "JKS"; - private static final String KEY_ERROR_MSG = "java.security.KeyStoreException: Key protection algorithm not found: java.lang.NullPointerException"; - private static final String CERTIFICATES_ERROR_MSG = "The certificate couldn't be parsed correctly. certificate1"; - private static final String PASSWORD_ERROR_MSG = "Password should be min. 16 chars long and should contain only alphanumeric characters and special characters like Underscore (_), Dollar ($) and Pound (#)"; - private static byte[] key; - private PrivateKey privateKey = mock(PrivateKey.class); - - @BeforeAll - static void setUpForAll() throws IOException { - key = Files.readAllBytes(Path.of(KEY_PATH)); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertKeystoreShouldReturnKeystoreWithGivenPrivateKeyAndCertificateChain(String conversionTarget) - throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, PemConversionException { - // given - final String alias = "keystore-entry"; - final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); - final List certificateChain = getCertificates(); - final PemConverter converter = new PemConverter(conversionTarget); - final KeyStore expectedKeyStore = KeyStore.getInstance(conversionTarget); - expectedKeyStore.load(new ByteArrayInputStream(Files.readAllBytes(Path.of(EXPECTED_KEYSTORE_PATH))), - password.toCharArray()); - final Certificate[] expectedChain = expectedKeyStore.getCertificateChain(alias); - privateKeyMockSetup(); - - // when - final byte[] result = converter.convertKeystore(certificateChain, password, alias, privateKey); - - // then - final KeyStore actualKeyStore = KeyStore.getInstance(conversionTarget); - actualKeyStore.load(new ByteArrayInputStream(result), password.toCharArray()); - final Certificate[] actualChain = actualKeyStore.getCertificateChain(alias); - - assertArrayEquals(key, actualKeyStore.getKey(alias, password.toCharArray()).getEncoded()); - assertEquals(2, expectedChain.length); - assertArrayEquals(expectedChain, actualChain); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongPassword(String conversionTarget) throws IOException { - // given - final String alias = "keystore-entry"; - final Password password = new Password("apple"); - final List certificateChain = getCertificates(); - final PemConverter converter = new PemConverter(conversionTarget); - privateKeyMockSetup(); - - // when - Exception exception = assertThrows(PemConversionException.class, () -> - converter.convertKeystore(certificateChain, password, alias, privateKey) - ); - - // then - assertEquals(PASSWORD_ERROR_MSG, exception.getMessage()); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertTruststoreShouldReturnTruststoreWithGivenCertificatesArray(String conversionTarget) - throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, PemConversionException { - - // given - final PemConverter converter = new PemConverter(conversionTarget); - final String alias = "trusted-certificate-"; - final String alias1 = alias + 1; - final String alias2 = alias + 2; - final Password password = new Password("9z6oFx1epRSCuBWU4Er8i_0y"); - final List trustedCertificates = getCertificates(); - final KeyStore expectedTrustStore = KeyStore.getInstance(conversionTarget); - expectedTrustStore.load(new ByteArrayInputStream(Files.readAllBytes(Path.of(EXPECTED_TRUSTSTORE_PATH))), - password.toCharArray()); - - // when - final byte[] result = converter.convertTruststore(trustedCertificates, password, alias); - - // then - final KeyStore actualKeyStore = KeyStore.getInstance(conversionTarget); - actualKeyStore.load(new ByteArrayInputStream(result), password.toCharArray()); - - assertTrue(actualKeyStore.containsAlias(alias1)); - assertTrue(actualKeyStore.containsAlias(alias2)); - assertEquals(expectedTrustStore.getCertificate(alias1), actualKeyStore.getCertificate(alias1)); - assertEquals(expectedTrustStore.getCertificate(alias2), actualKeyStore.getCertificate(alias2)); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertTruststoreShouldThrowPemConverterExceptionBecauseOfWrongPassword(String conversionTarget) throws IOException { - // given - final String alias = "trusted-certificate-"; - final Password password = new Password("nokia"); - final List trustedCertificates = getCertificates(); - final PemConverter converter = new PemConverter(conversionTarget); - - // when then - assertThatThrownBy(() -> - converter.convertTruststore(trustedCertificates, password, alias)) - .isInstanceOf(PemConversionException.class).hasMessage(PASSWORD_ERROR_MSG); - } - - @Test - void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongPrivateKey() throws IOException { - // given - final String alias = "keystore-entry"; - final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); - final List certificateChain = getCertificates(); - final PemConverter converter = new PemConverter(PKCS12); - - // when then - assertThatThrownBy(() -> converter.convertKeystore(certificateChain, password, alias, privateKey)) - .isInstanceOf(PemConversionException.class).hasMessage(KEY_ERROR_MSG); - } - - @ParameterizedTest - @ValueSource(strings = {PKCS12, JKS}) - void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongCertificates(String conversionTarget) { - // given - final String alias = "keystore-entry"; - final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); - final List certificateChain = List.of("certificate1", "certificate2"); - final PemConverter converter = new PemConverter(conversionTarget); - privateKeyMockSetup(); - - // when then - assertThatThrownBy(() -> converter.convertKeystore(certificateChain, password, alias, privateKey)) - .isInstanceOf(PemConversionException.class).hasMessage(CERTIFICATES_ERROR_MSG); - } - - private void privateKeyMockSetup() { - when(privateKey.getEncoded()).thenReturn(key); - when(privateKey.getAlgorithm()).thenReturn(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM); - when(privateKey.getFormat()).thenReturn(PKCS8); - } - - private List getCertificates() throws IOException { - return List.of( - Files.readString( - Path.of(CERT1_PATH), StandardCharsets.UTF_8), - Files.readString( - Path.of(CERT2_PATH), StandardCharsets.UTF_8) - ); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java deleted file mode 100644 index 483e35e0..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.conversion; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -class RandomPasswordGeneratorTest { - - @Test - void shouldGenerateRandomPasswordOfGivenLengthMatchingThePattern() { - Password password = new RandomPasswordGenerator().generate(24); - assertTrue(password.isCorrectPasswordPattern()); - } -} \ No newline at end of file diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriterTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriterTest.java deleted file mode 100644 index c45876ec..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/certification/writer/CertFileWriterTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.certification.writer; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.onap.aaf.certservice.client.certification.exception.CertFileWriterException; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -class CertFileWriterTest { - - private static final String RESOURCES_PATH = "src/test/resources/"; - private static final String OUTPUT_PATH = RESOURCES_PATH + "generatedFiles/"; - private static final String NOT_EXISTING_OUTPUT_PATH = OUTPUT_PATH + "directoryDoesNotExist/"; - private static final String TRUSTSTORE_P12 = "truststore.p12"; - private File outputDirectory = new File(OUTPUT_PATH); - - @AfterEach - void cleanUpFiles() { - deleteDirectoryRecursive(outputDirectory); - } - - @ParameterizedTest - @ValueSource(strings = {OUTPUT_PATH, NOT_EXISTING_OUTPUT_PATH}) - void certFileWriterShouldCreateFilesWithDataInGivenLocation(String outputPath) - throws IOException, CertFileWriterException { - // given - File truststore = new File(outputPath + TRUSTSTORE_P12); - CertFileWriter certFileWriter = CertFileWriter.createWithDir(outputPath); - final byte[] data = new byte[]{-128, 1, 2, 3, 127}; - - // when - certFileWriter.saveData(data, TRUSTSTORE_P12); - - // then - assertThat(truststore.exists()).isTrue(); - assertThat(Files.readAllBytes(Path.of(outputPath + TRUSTSTORE_P12))).isEqualTo(data); - } - - private void deleteDirectoryRecursive(File dirForDeletion) { - List.of(dirForDeletion.listFiles()).forEach(file -> { - if (file.isDirectory()) { - deleteDirectoryRecursive(file); - } - file.delete(); - }); - dirForDeletion.delete(); - } - -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvProviderTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvProviderTest.java deleted file mode 100644 index 74c8c2a1..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvProviderTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -class EnvProviderTest { - private static final String TEST_ENV = "testEnv"; - private static final String TEST_ENV_VALUE = "prod"; - - private EnvProvider envProvider; - - @BeforeEach - void setUp() { - envProvider = Mockito.spy(EnvProvider.class); - } - - @Test - void shouldReturnSystemEnvVariableWhenItWasDefined() { - // given - when(envProvider.getSystemEnv(TEST_ENV)).thenReturn(TEST_ENV_VALUE); - - // when - final Optional testEnv = envProvider.readEnvVariable(TEST_ENV); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV_VALUE); - } - - @Test - void shouldReportThatSystemEnvVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envProvider.readEnvVariable(TEST_ENV); - - // then - assertThat(testEnv).isNotPresent(); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForCsrTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForCsrTest.java deleted file mode 100644 index d6af20c6..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForCsrTest.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -class EnvsForCsrTest { - private static final String TEST_ENV = "testEnv"; - private EnvsForCsr envsForCsr; - - @BeforeEach - public void setUp() { - envsForCsr = Mockito.spy(EnvsForCsr.class); - } - - @Test - void shouldReturnSystemEnvCommonNameVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.COMMON_NAME)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getCommonName(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvCommonNameVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getCommonName(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvOrganizationVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.ORGANIZATION)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getOrganization(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvOrganizationVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getOrganization(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvOuVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.ORGANIZATION_UNIT)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getOrganizationUnit(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - public void shouldReportThatSystemEnvOuVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getOrganizationUnit(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvLocationVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.LOCATION)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getLocation(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvLocationVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getLocation(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvStateVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.STATE)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getState(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvStateVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getState(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvCountryVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.COUNTRY)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getCountry(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvCountryVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getCountry(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvSansVariableWhenItWasDefined() { - // given - when(envsForCsr.readEnv(CsrConfigurationEnvs.SANS)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForCsr.getSubjectAlternativesName(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - public void shouldReportThatSystemEnvSansVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForCsr.getSubjectAlternativesName(); - - // then - assertThat(testEnv).isNotPresent(); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForTlsTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForTlsTest.java deleted file mode 100644 index 7f599aa5..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/EnvsForTlsTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -class EnvsForTlsTest { - - private static final String TEST_ENV = "testEnv"; - private EnvsForTls envsForTls; - - @BeforeEach - public void setUp() { - envsForTls = Mockito.spy(EnvsForTls.class); - } - - @Test - void shouldReturnSystemEnvKeyStorePathVariableWhenItWasDefined() { - // given - when(envsForTls.readEnv(TlsConfigurationEnvs.KEYSTORE_PATH)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForTls.getKeystorePath(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvKeyStorePathVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForTls.getKeystorePath(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvKeyStorePasswordVariableWhenItWasDefined() { - // given - when(envsForTls.readEnv(TlsConfigurationEnvs.KEYSTORE_PASSWORD)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForTls.getKeystorePassword(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvKeyStorePasswordVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForTls.getKeystorePassword(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvTrustStorePathVariableWhenItWasDefined() { - // given - when(envsForTls.readEnv(TlsConfigurationEnvs.TRUSTSTORE_PATH)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForTls.getTruststorePath(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvTrustStorePathVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForTls.getTruststorePath(); - - // then - assertThat(testEnv).isNotPresent(); - } - - @Test - void shouldReturnSystemEnvTrustStorePasswordVariableWhenItWasDefined() { - // given - when(envsForTls.readEnv(TlsConfigurationEnvs.TRUSTSTORE_PASSWORD)).thenReturn(Optional.of(TEST_ENV)); - - // when - final Optional testEnv = envsForTls.getTruststorePassword(); - - // then - assertThat(testEnv) - .isPresent() - .contains(TEST_ENV); - } - - @Test - void shouldReportThatSystemEnvTrustStorePasswordVariableIsNotPresentWhenItWasNotDefined() { - // when - final Optional testEnv = envsForTls.getTruststorePassword(); - - // then - assertThat(testEnv).isNotPresent(); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java deleted file mode 100644 index e9e5c3bf..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.exception; - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.api.ExitStatus; - -import static org.assertj.core.api.Assertions.assertThat; - - -class TlsConfigurationExceptionTest { - - @Test - void containsProperExitStatus() { - // Given - ExitStatus exitStatus = null; - - // When - try { - throw new TlsConfigurationException("Test message"); - } catch (TlsConfigurationException e) { - exitStatus = e.applicationExitStatus(); - } - - // Then - assertThat(exitStatus) - .isNotNull() - .isEqualTo(ExitStatus.TLS_CONFIGURATION_EXCEPTION); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java deleted file mode 100644 index e4d71b31..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.factory; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.mockito.Mockito; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -class AbstractConfigurationFactoryTest { - - private final AbstractConfigurationFactory cut = mock(AbstractConfigurationFactory.class, Mockito.CALLS_REAL_METHODS); - - @ParameterizedTest - @ValueSource(strings = {"/var/log", "/", "/var/log/", "/second_var", "/second-var"}) - void shouldAcceptValidPath(String path) { - assertThat(cut.isPathValid(path)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"/var/log?", "", "var_", "var", "//", "/var//log"}) - void shouldRejectInvalidPath(String path) { - assertThat(cut.isPathValid(path)).isFalse(); - } - - @ParameterizedTest - @ValueSource(strings = {"PL", "DE", "PN", "US", "IO", "CA", "KH", "CO", "DK", "EC", "CZ", "CN", "BR", "BD", "BE"}) - void shouldAcceptValidCountryCode(String countryCode) { - assertThat(cut.isCountryValid(countryCode)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"", "QQ", "AFG", "D", "&*", "!", "ONAP", "p", "pl", "us", "afg"}) - void shouldRejectInvalidCountryCode(String countryCode) { - assertThat(cut.isCountryValid(countryCode)).isFalse(); - } - - @ParameterizedTest - @ValueSource(strings = {"caname", "caname1", "123caName", "ca1name"}) - void shouldAcceptValidAlphanumeric(String caName) { - assertThat(cut.isAlphaNumeric(caName)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"44caname$", "#caname1", "1c_aname", "ca1-name"}) - void shouldRejectInvalidAlphanumeric(String caName) { - assertThat(cut.isAlphaNumeric(caName)).isFalse(); - } - - @ParameterizedTest - @ValueSource(strings = {"example.com", "www.example.com"}) - void shouldAcceptValidCommonName(String commonName) { - assertThat(cut.isCommonNameValid(commonName)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"https://example.com", "http://example.com", "example.com:8080", "0.0.0.0", "@#$%.com"}) - void shouldRejectInvalidCommonName(String commonName) { - assertThat(cut.isCommonNameValid(commonName)).isFalse(); - } - - @ParameterizedTest - @ValueSource(strings = {"JKS", "P12", "PEM"}) - void shouldAcceptValidOutputType(String outputType) { - assertThat(cut.isOutputTypeValid(outputType)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"jks", "p12", "pem", "", "pass", "!@$#pp"}) - void shouldRejectInvalidOutputType(String outputType) { - assertThat(cut.isOutputTypeValid(outputType)).isFalse(); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java deleted file mode 100644 index 20a6c7ef..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.factory; - -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.configuration.ClientConfigurationEnvs; -import org.onap.aaf.certservice.client.configuration.EnvsForClient; -import org.onap.aaf.certservice.client.configuration.exception.ClientConfigurationException; -import org.onap.aaf.certservice.client.configuration.model.ClientConfiguration; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class ClientConfigurationFactoryTest { - - private static final String CA_NAME_VALID = "caaaftest2"; - private static final String TIME_OUT_VALID = "30000"; - private static final String OUTPUT_PATH_VALID = "/opt/app/osaaf"; - private static final String URL_TO_CERT_SERVICE_VALID = "https://cert-service:8443/v1/certificate/"; - private static final String URL_TO_CERT_SERVICE_DEFAULT = "https://aaf-cert-service:8443/v1/certificate/"; - private static final String CA_NAME_INVALID = "caaaftest2#$"; - private static final String OUTPUT_PATH_INVALID = "/opt//app/osaaf"; - private static final String OUTPUT_TYPE_VALID = "JKS"; - private static final String OUTPUT_TYPE_INVALID = "JKSS"; - private static final String OUTPUT_TYPE_DEFAULT = "P12"; - - private EnvsForClient envsForClient = mock(EnvsForClient.class); - - - @Test - void create_shouldReturnSuccessWhenAllVariablesAreSetAndValid() throws ClientConfigurationException { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); - when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); - when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_VALID)); - - // when - ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); - System.out.println(configuration.toString()); - - // then - assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); - assertThat(configuration.getRequestTimeout()).isEqualTo(Integer.valueOf(TIME_OUT_VALID)); - assertThat(configuration.getCertsOutputPath()).isEqualTo(OUTPUT_PATH_VALID); - assertThat(configuration.getUrlToCertService()).isEqualTo(URL_TO_CERT_SERVICE_VALID); - assertThat(configuration.getOutputType()).isEqualTo(OUTPUT_TYPE_VALID); - } - - @Test - void create_shouldReturnSuccessWhenDefaultVariablesAreNotSet() throws ClientConfigurationException { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - - // when - ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); - - // then - assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); - assertThat(configuration.getRequestTimeout()).isEqualTo(Integer.valueOf(TIME_OUT_VALID)); - assertThat(configuration.getCertsOutputPath()).isEqualTo(OUTPUT_PATH_VALID); - assertThat(configuration.getUrlToCertService()).isEqualTo(URL_TO_CERT_SERVICE_DEFAULT); - assertThat(configuration.getOutputType()).isEqualTo(OUTPUT_TYPE_DEFAULT); - } - - @Test - void create_shouldReturnClientExceptionWhenRequiredVariableIsNotSet() { - // given - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - - // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); - - // then - assertThatExceptionOfType(ClientConfigurationException.class) - .isThrownBy(configurationFactory::create) - .withMessageContaining(ClientConfigurationEnvs.CA_NAME + " is invalid."); - } - - @Test - void create_shouldReturnClientExceptionWhenCaNameContainsSpecialCharacters() { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_INVALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); - when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); - - // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); - - // when/then - assertThatExceptionOfType(ClientConfigurationException.class) - .isThrownBy(configurationFactory::create) - .withMessageContaining(ClientConfigurationEnvs.CA_NAME + " is invalid."); - } - - @Test - void create_shouldReturnClientExceptionWhenOutputPathContainsSpecialCharacters() { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_INVALID)); - when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); - when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); - - // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); - - //then - assertThatExceptionOfType(ClientConfigurationException.class) - .isThrownBy(configurationFactory::create) - .withMessageContaining(ClientConfigurationEnvs.OUTPUT_PATH + " is invalid."); - } - - @Test - void create_shouldReturnClientExceptionWhenOutputTypeIsInvalid() { - // given - when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); - when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); - when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); - when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); - when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_INVALID)); - - // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); - - //then - assertThatExceptionOfType(ClientConfigurationException.class) - .isThrownBy(configurationFactory::create) - .withMessageContaining(ClientConfigurationEnvs.OUTPUT_TYPE + " is invalid."); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java deleted file mode 100644 index b9b9b078..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.factory; - -import org.assertj.core.api.Condition; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.configuration.CsrConfigurationEnvs; -import org.onap.aaf.certservice.client.configuration.EnvsForCsr; -import org.onap.aaf.certservice.client.configuration.exception.CsrConfigurationException; -import org.onap.aaf.certservice.client.configuration.model.CsrConfiguration; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.onap.aaf.certservice.client.api.ExitStatus.CSR_CONFIGURATION_EXCEPTION; - -public class CsrConfigurationFactoryTest { - - private static final String COMMON_NAME_VALID = "onap.org"; - private static final String SANS_VALID = "test-name"; - private static final String COUNTRY_VALID = "US"; - private static final String LOCATION_VALID = "San-Francisco"; - private static final String ORGANIZATION_VALID = "Linux-Foundation"; - private static final String ORGANIZATION_UNIT_VALID = "ONAP"; - private static final String STATE_VALID = "California"; - private static final String COMMON_NAME_INVALID = "onap.org*&"; - private static final String COUNTRY_INVALID = "PLA"; - private static final String ORGANIZATION_INVALID = "Linux?Foundation"; - - private EnvsForCsr envsForCsr = mock(EnvsForCsr.class); - private CsrConfigurationFactory testedFactory; - private Condition expectedExitCodeCondition = new Condition<>("Correct exit code") { - @Override - public boolean matches(CsrConfigurationException exception) { - return exception.applicationExitStatus() == CSR_CONFIGURATION_EXCEPTION; - } - }; - - @BeforeEach - void setUp() { - testedFactory = new CsrConfigurationFactory(envsForCsr); - } - - @Test - void shouldReturnCorrectConfiguration_WhenAllVariablesAreSetAndValid() throws CsrConfigurationException { - // given - mockEnvsWithAllValidParameters(); - - // when - CsrConfiguration configuration = testedFactory.create(); - - // then - assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); - assertThat(configuration.getSans()).isEqualTo(SANS_VALID); - assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); - assertThat(configuration.getLocation()).isEqualTo(LOCATION_VALID); - assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); - assertThat(configuration.getOrganizationUnit()).isEqualTo(ORGANIZATION_UNIT_VALID); - assertThat(configuration.getState()).isEqualTo(STATE_VALID); - } - - @Test - void shouldReturnCorrectConfiguration_WhenNotRequiredVariablesAreNotSet() throws CsrConfigurationException { - // given - mockEnvsWithValidRequiredParameters(); - - // when - CsrConfiguration configuration = testedFactory.create(); - - // then - assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); - assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); - assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); - assertThat(configuration.getState()).isEqualTo(STATE_VALID); - } - - - @Test - void shouldThrowCsrConfigurationException_WhenCommonNameInvalid() { - // given - mockEnvsWithInvalidCommonName(); - - // when/then - assertThatExceptionOfType(CsrConfigurationException.class) - .isThrownBy(testedFactory::create) - .withMessageContaining(CsrConfigurationEnvs.COMMON_NAME + " is invalid.") - .has(expectedExitCodeCondition); - } - - @Test - void shouldThrowCsrConfigurationException_WhenOrganizationInvalid() { - // given - mockEnvsWithInvalidOrganization(); - - // when/then - assertThatExceptionOfType(CsrConfigurationException.class) - .isThrownBy(testedFactory::create) - .withMessageContaining(CsrConfigurationEnvs.ORGANIZATION + " is invalid.") - .has(expectedExitCodeCondition); - - } - - @Test - void shouldThrowCsrConfigurationException_WhenCountryInvalid() { - // given - mockEnvsWithInvalidCountry(); - - // when/then - assertThatExceptionOfType(CsrConfigurationException.class) - .isThrownBy(testedFactory::create) - .withMessageContaining(CsrConfigurationEnvs.COUNTRY + " is invalid.") - .has(expectedExitCodeCondition); - - } - - @Test - void shouldThrowCsrConfigurationExceptionWhenStateInvalid() { - // given - mockEnvsWithInvalidState(); - // when/then - assertThatExceptionOfType(CsrConfigurationException.class) - .isThrownBy(testedFactory::create) - .withMessageContaining(CsrConfigurationEnvs.STATE + " is invalid.") - .has(expectedExitCodeCondition); - } - - private void mockEnvsWithAllValidParameters() { - mockEnvsWithValidRequiredParameters(); - mockEnvsWithValidOptionalParameters(); - } - - private void mockEnvsWithValidOptionalParameters() { - when(envsForCsr.getOrganizationUnit()).thenReturn(Optional.of(ORGANIZATION_UNIT_VALID)); - when(envsForCsr.getLocation()).thenReturn(Optional.of(LOCATION_VALID)); - when(envsForCsr.getSubjectAlternativesName()).thenReturn(Optional.of(SANS_VALID)); - } - - private void mockEnvsWithValidRequiredParameters() { - when(envsForCsr.getCommonName()).thenReturn(Optional.of(COMMON_NAME_VALID)); - when(envsForCsr.getCountry()).thenReturn(Optional.of(COUNTRY_VALID)); - when(envsForCsr.getOrganization()).thenReturn(Optional.of(ORGANIZATION_VALID)); - when(envsForCsr.getState()).thenReturn(Optional.of(STATE_VALID)); - } - - private void mockEnvsWithInvalidCommonName() { - mockEnvsWithAllValidParameters(); - when(envsForCsr.getCommonName()).thenReturn(Optional.of(COMMON_NAME_INVALID)); - } - - private void mockEnvsWithInvalidCountry() { - mockEnvsWithAllValidParameters(); - when(envsForCsr.getCountry()).thenReturn(Optional.of(COUNTRY_INVALID)); - } - - private void mockEnvsWithInvalidOrganization() { - mockEnvsWithAllValidParameters(); - when(envsForCsr.getOrganization()).thenReturn(Optional.of(ORGANIZATION_INVALID)); - } - - private void mockEnvsWithInvalidState() { - mockEnvsWithAllValidParameters(); - when(envsForCsr.getState()).thenReturn(Optional.empty()); - } -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactoryTest.java deleted file mode 100644 index 8e6e8369..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/factory/SslContextFactoryTest.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.configuration.factory; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.onap.aaf.certservice.client.configuration.EnvsForTls; -import org.onap.aaf.certservice.client.configuration.exception.TlsConfigurationException; - -import javax.net.ssl.SSLContext; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.when; - - -@ExtendWith(MockitoExtension.class) -public class SslContextFactoryTest { - - public static final String INVALID_KEYSTORE_PATH = "nonexistent/keystore"; - public static final String VALID_KEYSTORE_NAME = "keystore.jks"; - public static final String VALID_KEYSTORE_PASSWORD = "secret"; - public static final String INVALID_KEYSTORE_PASSWORD = "wrong_secret"; - public static final String INVALID_TRUSTSTORE_PATH = "nonexistent/truststore"; - public static final String VALID_TRUSTSTORE_PASSWORD = "secret"; - public static final String INVALID_TRUSTSTORE_PASSWORD = "wrong_secret"; - public static final String VALID_TRUSTSTORE_NAME = "truststore.jks"; - @Mock - private EnvsForTls envsForTls; - - @Test - public void shouldThrowExceptionWhenKeystorePathEnvIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.empty()); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - Exception exception = assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - assertThat(exception.getMessage()).contains("KEYSTORE_PATH"); - } - - @Test - public void shouldThrowExceptionWhenKeystorePasswordEnvIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.empty()); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - Exception exception = assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - assertThat(exception.getMessage()).contains("KEYSTORE_PASSWORD"); - } - - @Test - public void shouldThrowExceptionWhenTruststorePathEnvIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); - when(envsForTls.getTruststorePath()).thenReturn(Optional.empty()); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - Exception exception = assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - assertThat(exception.getMessage()).contains("TRUSTSTORE_PATH"); - } - - @Test - public void shouldThrowExceptionWhenTruststorePasswordEnvIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore")); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.empty()); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - Exception exception = assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - assertThat(exception.getMessage()).contains("TRUSTSTORE_PASSWORD"); - } - - @Test - public void shouldThrowExceptionWhenKeystoreIsMissing() { - // Given - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(INVALID_KEYSTORE_PATH)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("secret")); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore.jks")); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of("secret")); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - } - - @Test - public void shouldThrowExceptionWhenKeystorePasswordIsWrong() { - // Given - String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(INVALID_KEYSTORE_PASSWORD)); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of(VALID_TRUSTSTORE_NAME)); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - } - - @Test - public void shouldThrowExceptionWhenTruststoreIsMissing() { - // Given - String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PATH)); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - } - - @Test - public void shouldThrowExceptionWhenTruststorePasswordIsWrong() { - // Given - String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); - String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PASSWORD)); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When, Then - assertThrows( - TlsConfigurationException.class, sslContextFactory::create - ); - } - - @Test - public void shouldReturnSslContext() throws TlsConfigurationException { - // Given - String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); - String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); - when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); - when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); - when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); - when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); - SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); - - // When - SSLContext sslContext = sslContextFactory.create(); - - // Then - assertNotNull(sslContext); - } - - private String getResourcePath(String resource) { - return getClass().getClassLoader().getResource(resource).getFile(); - } -} - diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java deleted file mode 100644 index a109749b..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.client.httpclient; - -import org.apache.http.HttpEntity; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.httpclient.exception.CertServiceApiResponseException; -import org.onap.aaf.certservice.client.httpclient.exception.HttpClientException; -import org.onap.aaf.certservice.client.httpclient.model.CertServiceResponse; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.List; - -import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; -import static java.net.HttpURLConnection.HTTP_OK; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.CA_NAME; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.CORRECT_RESPONSE; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.CSR; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.MISSING_PK_RESPONSE; -import static org.onap.aaf.certservice.client.CerServiceRequestTestData.PK; - -class HttpClientTest { - - private HttpClient httpClient; - private CloseableHttpClient closeableHttpClient; - private HttpEntity httpEntity; - private StatusLine statusLine; - private CloseableHttpResponse httpResponse; - - @BeforeEach - void setUp() { - - closeableHttpClient = mock(CloseableHttpClient.class); - httpEntity = mock(HttpEntity.class); - statusLine = mock(StatusLine.class); - httpResponse = mock(CloseableHttpResponse.class); - - CloseableHttpsClientProvider httpClientProvider = mock(CloseableHttpsClientProvider.class); - - when(httpClientProvider.getClient()).thenReturn(closeableHttpClient); - String testCertServiceAddress = ""; - httpClient = new HttpClient(httpClientProvider, testCertServiceAddress); - } - - @Test - void shouldReturnCorrectListsOfCertificatedChainsAndTrustedCertificates_WhenRequestDataIsCorrect() - throws Exception { - - // given - mockServerResponse(HTTP_OK, CORRECT_RESPONSE); - - // when - CertServiceResponse certServiceResponse = - httpClient.retrieveCertServiceData(CA_NAME, CSR, PK); - List certificateChain = certServiceResponse.getCertificateChain(); - List trustedCertificate = certServiceResponse.getTrustedCertificates(); - - // then - assertThat(certServiceResponse).isNotNull(); - - final int expectedTwoElements = 2; - - assertThat(certificateChain).hasSize(expectedTwoElements); - assertThat(trustedCertificate).hasSize(expectedTwoElements); - - assertThat(certificateChain.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN); - assertThat(trustedCertificate.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES); - } - - @Test - void shouldThrowCertServiceApiResponseException_WhenPkHeaderIsMissing() throws Exception { - - //given - mockServerResponse(HTTP_BAD_REQUEST, MISSING_PK_RESPONSE); - - //when //then - assertThatExceptionOfType(CertServiceApiResponseException.class) - .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); - } - - @Test - void shouldThrowHttpClientException_WhenCannotExecuteRequestToApi() throws Exception { - - //given - when(closeableHttpClient.execute(any(HttpGet.class))).thenThrow(IOException.class); - - //when //then - assertThatExceptionOfType(HttpClientException.class) - .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); - } - - @Test - void shouldThrowHttpClientException_WhenCannotParseResponseToString() throws Exception { - - //given - mockServerResponse(HTTP_OK, CORRECT_RESPONSE); - when(httpEntity.getContent()).thenThrow(IOException.class); - - //when //then - assertThatExceptionOfType(HttpClientException.class) - .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); - } - - private void mockServerResponse(int serverCodeResponse, String stringResponse) - throws IOException { - when(statusLine.getStatusCode()).thenReturn(serverCodeResponse); - when(httpResponse.getStatusLine()).thenReturn(statusLine); - when(httpResponse.getEntity()).thenReturn(httpEntity); - when(closeableHttpClient.execute(any(HttpGet.class))).thenReturn(httpResponse); - - when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream(stringResponse.getBytes())); - } -} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/CerServiceRequestTestData.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/CerServiceRequestTestData.java new file mode 100644 index 00000000..0e5ec191 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/CerServiceRequestTestData.java @@ -0,0 +1,89 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; + +public final class CerServiceRequestTestData { + + private static final String RESOURCE_PATH = "src/test/resources/"; + + // Request parameters + public static final String CA_NAME = "TestCA"; + public static final String CSR = getCsrValue(); + public static final String PK = getPkValue(); + + // Correct response data + public static final String CORRECT_RESPONSE = getCorrectResponse(); + public static final String EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN = + getExpectedFirstElementOfCertificateChain(); + public static final String EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES = + getExpectedFirstElementOfTrustedCertificates(); + + // Error response data + public static final String MISSING_PK_RESPONSE = getMissingPkResponse(); + + private CerServiceRequestTestData() { + } + + private static String getMissingPkResponse() { + String fileName = "missingPkResponse"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getExpectedFirstElementOfTrustedCertificates() { + + String fileName = "expectedFirstElementOfTrustedCertificates"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getExpectedFirstElementOfCertificateChain() { + String fileName = "expectedFirstElementOfCertificateChain"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getCorrectResponse() { + String fileName = "correctResponse"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getPkValue() { + String fileName = "testPk"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String getCsrValue() { + String fileName = "testCsr"; + return readFromFile(RESOURCE_PATH + fileName); + } + + private static String readFromFile(String path) { + try { + return Files.readString(Paths.get(path), StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + return "File not found"; + } + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/CertServiceClientTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/CertServiceClientTest.java new file mode 100644 index 00000000..0a5806fd --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/CertServiceClientTest.java @@ -0,0 +1,49 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.verify; +import static org.onap.oom.certservice.client.api.ExitStatus.CLIENT_CONFIGURATION_EXCEPTION; +import static org.onap.oom.certservice.client.api.ExitStatus.SUCCESS; + +@ExtendWith(MockitoExtension.class) +class CertServiceClientTest { + @Spy + AppExitHandler appExitHandler = new AppExitHandler(); + + @Test + void shouldExitWithDefinedExitCode_onRunCallWhenNoEnvsPresent() { + // given + doNothing().when(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); + doNothing().when(appExitHandler).exit(SUCCESS); + CertServiceClient certServiceClient = new CertServiceClient(appExitHandler); + // when + certServiceClient.run(); + // then + verify(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); + verify(appExitHandler).exit(SUCCESS); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProviderTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProviderTest.java new file mode 100644 index 00000000..503ed70f --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/ArtifactsCreatorProviderTest.java @@ -0,0 +1,73 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.onap.oom.certservice.client.certification.conversion.ArtifactsCreator; +import org.onap.oom.certservice.client.certification.conversion.ConvertedArtifactsCreator; +import org.onap.oom.certservice.client.certification.conversion.PemArtifactsCreator; + +import static org.assertj.core.api.Assertions.assertThat; + + +class ArtifactsCreatorProviderTest { + + private static final String P12 = "P12"; + private static final String JKS = "JKS"; + private static final String PEM = "PEM"; + private static final String TEST_PATH = "testPath"; + + @ParameterizedTest + @ValueSource(strings = {JKS, P12}) + void artifactsProviderShouldReturnConvertedCreator(String outputType) { + + // when + ArtifactsCreator artifactsCreator = + ArtifactsCreatorProvider.get(outputType, TEST_PATH); + // then + assertThat(artifactsCreator).isInstanceOf(ConvertedArtifactsCreator.class); + } + + @Test + void artifactsProviderShouldReturnPemCreator() { + + // when + ArtifactsCreator artifactsCreator = + ArtifactsCreatorProvider.get(PEM, TEST_PATH); + // then + assertThat(artifactsCreator).isInstanceOf(PemArtifactsCreator.class); + } + + @ParameterizedTest + @CsvSource({ + "JKS, jks", + "P12, p12"}) + void getExtensionShouldProvideExtensionBasedOnArtifactType(String artifactType, String expectedExtension) { + + //when + String actualExtension = ArtifactsCreatorProvider.valueOf(artifactType).getExtension(); + //then + assertThat(actualExtension).isEqualTo(expectedExtension); + } + +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/CsrFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/CsrFactoryTest.java new file mode 100644 index 00000000..e2bfa976 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/CsrFactoryTest.java @@ -0,0 +1,56 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification; + + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.certification.exception.CsrGenerationException; +import org.onap.oom.certservice.client.certification.exception.KeyPairGenerationException; +import org.onap.oom.certservice.client.configuration.model.CsrConfiguration; + +import java.security.KeyPair; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class CsrFactoryTest { + + CsrConfiguration config = mock(CsrConfiguration.class); + + + @Test + void createEncodedCsr_shouldSucceedWhenAllFieldsAreSetCorrectly() throws KeyPairGenerationException, CsrGenerationException { + + KeyPair keyPair = + new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, EncryptionAlgorithmConstants.KEY_SIZE).create(); + + when(config.getCommonName()).thenReturn("onap.org"); + when(config.getSans()).thenReturn("onapexample.com:onapexample.com.pl:onapexample.pl"); + when(config.getCountry()).thenReturn("US"); + when(config.getLocation()).thenReturn("San-Francisco"); + when(config.getOrganization()).thenReturn("Linux-Foundation"); + when(config.getOrganizationUnit()).thenReturn("ONAP"); + when(config.getState()).thenReturn("California"); + + assertThat(new CsrFactory(config).createCsrInPem(keyPair)).isNotEmpty(); + } +} + diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/KeyPairFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/KeyPairFactoryTest.java new file mode 100644 index 00000000..765a58ca --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/KeyPairFactoryTest.java @@ -0,0 +1,53 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification; + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.certification.exception.KeyPairGenerationException; + +import java.security.KeyPair; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class KeyPairFactoryTest { + private static final String NOT_EXISTING_ENCRYPTION_ALGORITHM = "FAKE_ALGORITHM"; + + @Test + public void shouldProvideKeyPair_whenCreateKeyPairCalledWithCorrectArguments() throws KeyPairGenerationException { + // given + KeyPairFactory keyPairFactory = new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, + EncryptionAlgorithmConstants.KEY_SIZE); + // when + KeyPair keyPair = keyPairFactory.create(); + // then + assertThat(keyPair).isInstanceOf(KeyPair.class); + } + + @Test + public void shouldThrowKeyPairGenerationException_whenCreateTryCalledOnNotExistingAlgorithm() { + // given + KeyPairFactory keyPairFactory = new KeyPairFactory(NOT_EXISTING_ENCRYPTION_ALGORITHM, + EncryptionAlgorithmConstants.KEY_SIZE); + // when, then + assertThatThrownBy(keyPairFactory::create).isInstanceOf(KeyPairGenerationException.class); + } + +} \ No newline at end of file diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoderTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoderTest.java new file mode 100644 index 00000000..6424611e --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/PrivateKeyToPemEncoderTest.java @@ -0,0 +1,66 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification; + + +import org.bouncycastle.util.io.pem.PemObject; +import org.bouncycastle.util.io.pem.PemReader; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.certification.exception.PkEncodingException; + +import java.io.IOException; +import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; + +import static org.assertj.core.api.Assertions.assertThat; + +class PrivateKeyToPemEncoderTest { + + private static final String ENCRYPTION_ALGORITHM = "RSA"; + private static final String RESOURCES_DIR = "src/test/resources/"; + private static final String PRIVATE_KEY_PEM_PATH = RESOURCES_DIR + "rsaPrivateKeyPem"; + + @Test + void shouldReturnProperlyEncodedPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException, PkEncodingException, IOException { + //given + String expectedPem = Files.readString(Paths.get(PRIVATE_KEY_PEM_PATH)); + PrivateKeyToPemEncoder testedPkEncoder = new PrivateKeyToPemEncoder(); + //when + PrivateKey privateKey = extractPrivateKeyFromPem(expectedPem); + String resultPkInPem = testedPkEncoder.encodePrivateKeyToPem(privateKey); + //then + assertThat(resultPkInPem).isEqualTo(expectedPem); + } + + private PrivateKey extractPrivateKeyFromPem(String pem) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { + PemReader pemReader = new PemReader(new StringReader(pem)); + PemObject pemObject = pemReader.readPemObject(); + pemReader.close(); + PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pemObject.getContent()); + KeyFactory kf = KeyFactory.getInstance(ENCRYPTION_ALGORITHM); + return kf.generatePrivate(spec); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java new file mode 100644 index 00000000..3a4d3419 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/ConvertedArtifactsCreatorTest.java @@ -0,0 +1,125 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.certification.exception.CertFileWriterException; +import org.onap.oom.certservice.client.certification.exception.PemConversionException; +import org.onap.oom.certservice.client.certification.writer.CertFileWriter; + +import java.security.PrivateKey; +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ConvertedArtifactsCreatorTest { + + private static final int PASSWORD_LENGTH = 24; + private static final String CERTIFICATE_ALIAS = "certificate"; + private static final String TRUSTED_CERTIFICATE_ALIAS = "trusted-certificate-"; + + private static final Password SAMPLE_PASSWORD = new Password("d9D_u8LooYaXH4G48DtN#vw0"); + private static final List SAMPLE_KEYSTORE_CERTIFICATE_CHAIN = List.of("a", "b"); + private static final List SAMPLE_TRUSTED_CERTIFICATE_CHAIN = List.of("c", "d"); + private static final byte[] SAMPLE_KEYSTORE_BYTES = "this is a keystore test".getBytes(); + private static final byte[] SAMPLE_TRUSTSTORE_BYTES = "this is a truststore test".getBytes(); + private static final String P12_EXTENSION = "p12"; + + private CertFileWriter certFileWriter; + private RandomPasswordGenerator passwordGenerator; + private PemConverter converter; + private PrivateKey privateKey; + private ConvertedArtifactsCreator artifactsCreator; + + + @BeforeEach + void setUp() { + certFileWriter = mock(CertFileWriter.class); + passwordGenerator = mock(RandomPasswordGenerator.class); + converter = mock(PemConverter.class); + privateKey = mock(PrivateKey.class); + artifactsCreator = new ConvertedArtifactsCreator(certFileWriter, passwordGenerator, converter, P12_EXTENSION); + } + + @Test + void convertedArtifactCreatorShouldTryCreateFileWithGivenExtension() + throws CertFileWriterException, PemConversionException { + //given + mockPasswordGeneratorAndPemConverter(); + final String keystore = "keystore"; + final String testExtension = "testExt"; + final String keystoreFileName = String.format("%s.%s", keystore, testExtension); + artifactsCreator = new ConvertedArtifactsCreator(certFileWriter, passwordGenerator, converter, testExtension); + + //when + artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); + + //then + verify(certFileWriter, times(1)) + .saveData(SAMPLE_KEYSTORE_BYTES, keystoreFileName); + } + + @Test + void convertedArtifactsCreatorShouldCallConverterAndFilesCreatorMethods() + throws PemConversionException, CertFileWriterException { + // given + mockPasswordGeneratorAndPemConverter(); + final String keystoreP12 = "keystore.p12"; + final String keystorePass = "keystore.pass"; + + //when + artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); + + // then + verify(converter, times(1)) + .convertKeystore(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, CERTIFICATE_ALIAS, privateKey); + verify(certFileWriter, times(1)) + .saveData(SAMPLE_KEYSTORE_BYTES, keystoreP12); + verify(certFileWriter, times(1)) + .saveData(SAMPLE_PASSWORD.getCurrentPassword().getBytes(), keystorePass); + verify(converter, times(1)) + .convertTruststore(SAMPLE_TRUSTED_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, TRUSTED_CERTIFICATE_ALIAS); + } + + @Test + void convertedArtifactsCreatorShouldCallPasswordGeneratorTwice() + throws PemConversionException, CertFileWriterException { + // given + mockPasswordGeneratorAndPemConverter(); + + //when + artifactsCreator.create(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_TRUSTED_CERTIFICATE_CHAIN, privateKey); + + // then + verify(passwordGenerator, times(2)).generate(PASSWORD_LENGTH); + } + + private void mockPasswordGeneratorAndPemConverter() throws PemConversionException { + when(passwordGenerator.generate(PASSWORD_LENGTH)).thenReturn(SAMPLE_PASSWORD); + when(converter.convertKeystore(SAMPLE_KEYSTORE_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, CERTIFICATE_ALIAS, privateKey)) + .thenReturn(SAMPLE_KEYSTORE_BYTES); + when(converter.convertTruststore(SAMPLE_TRUSTED_CERTIFICATE_CHAIN, SAMPLE_PASSWORD, TRUSTED_CERTIFICATE_ALIAS)) + .thenReturn(SAMPLE_TRUSTSTORE_BYTES); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreatorTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreatorTest.java new file mode 100644 index 00000000..fd6d95c5 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemArtifactsCreatorTest.java @@ -0,0 +1,58 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.api.ExitableException; +import org.onap.oom.certservice.client.certification.PrivateKeyToPemEncoder; +import org.onap.oom.certservice.client.certification.writer.CertFileWriter; + +import java.security.PrivateKey; +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class PemArtifactsCreatorTest { + private static final String KEYSTORE_PEM = "keystore.pem"; + private static final String TRUSTSTORE_PEM = "truststore.pem"; + private static final String KEY_PEM = "key.pem"; + private static final String KEY = "my private key"; + private CertFileWriter certFileWriter = mock(CertFileWriter.class); + private PrivateKey privateKey = mock(PrivateKey.class); + private PrivateKeyToPemEncoder pkEncoder = mock(PrivateKeyToPemEncoder.class); + + @Test + void pemArtifactsCreatorShouldCallRequiredMethods() throws ExitableException { + // given + final PemArtifactsCreator creator = new PemArtifactsCreator(certFileWriter, pkEncoder); + + // when + when(pkEncoder.encodePrivateKeyToPem(privateKey)).thenReturn(KEY); + creator.create(List.of("one", "two"), List.of("three", "four"), privateKey); + + // then + verify(certFileWriter, times(1)).saveData("one\ntwo".getBytes(), KEYSTORE_PEM); + verify(certFileWriter, times(1)).saveData("three\nfour".getBytes(), TRUSTSTORE_PEM); + verify(certFileWriter, times(1)).saveData(KEY.getBytes(), KEY_PEM); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemConverterTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemConverterTest.java new file mode 100644 index 00000000..c5adec08 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/PemConverterTest.java @@ -0,0 +1,206 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.onap.oom.certservice.client.certification.EncryptionAlgorithmConstants; +import org.onap.oom.certservice.client.certification.exception.PemConversionException; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class PemConverterTest { + + private static final String RESOURCES_PATH = "src/test/resources"; + private static final String CERT1_PATH = RESOURCES_PATH + "/cert1.pem"; + private static final String CERT2_PATH = RESOURCES_PATH + "/cert2.pem"; + private static final String KEY_PATH = RESOURCES_PATH + "/privateKey"; + private static final String EXPECTED_KEYSTORE_PATH = RESOURCES_PATH + "/expectedKeystore.jks"; + private static final String EXPECTED_TRUSTSTORE_PATH = RESOURCES_PATH + "/expectedTruststore.jks"; + private static final String PKCS12 = "PKCS12"; + private static final String PKCS8 = "PKCS#8"; + private static final String JKS = "JKS"; + private static final String KEY_ERROR_MSG = "java.security.KeyStoreException: Key protection algorithm not found: java.lang.NullPointerException"; + private static final String CERTIFICATES_ERROR_MSG = "The certificate couldn't be parsed correctly. certificate1"; + private static final String PASSWORD_ERROR_MSG = "Password should be min. 16 chars long and should contain only alphanumeric characters and special characters like Underscore (_), Dollar ($) and Pound (#)"; + private static byte[] key; + private PrivateKey privateKey = mock(PrivateKey.class); + + @BeforeAll + static void setUpForAll() throws IOException { + key = Files.readAllBytes(Path.of(KEY_PATH)); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertKeystoreShouldReturnKeystoreWithGivenPrivateKeyAndCertificateChain(String conversionTarget) + throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, PemConversionException { + // given + final String alias = "keystore-entry"; + final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); + final List certificateChain = getCertificates(); + final PemConverter converter = new PemConverter(conversionTarget); + final KeyStore expectedKeyStore = KeyStore.getInstance(conversionTarget); + expectedKeyStore.load(new ByteArrayInputStream(Files.readAllBytes(Path.of(EXPECTED_KEYSTORE_PATH))), + password.toCharArray()); + final Certificate[] expectedChain = expectedKeyStore.getCertificateChain(alias); + privateKeyMockSetup(); + + // when + final byte[] result = converter.convertKeystore(certificateChain, password, alias, privateKey); + + // then + final KeyStore actualKeyStore = KeyStore.getInstance(conversionTarget); + actualKeyStore.load(new ByteArrayInputStream(result), password.toCharArray()); + final Certificate[] actualChain = actualKeyStore.getCertificateChain(alias); + + assertArrayEquals(key, actualKeyStore.getKey(alias, password.toCharArray()).getEncoded()); + assertEquals(2, expectedChain.length); + assertArrayEquals(expectedChain, actualChain); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongPassword(String conversionTarget) throws IOException { + // given + final String alias = "keystore-entry"; + final Password password = new Password("apple"); + final List certificateChain = getCertificates(); + final PemConverter converter = new PemConverter(conversionTarget); + privateKeyMockSetup(); + + // when + Exception exception = assertThrows(PemConversionException.class, () -> + converter.convertKeystore(certificateChain, password, alias, privateKey) + ); + + // then + assertEquals(PASSWORD_ERROR_MSG, exception.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertTruststoreShouldReturnTruststoreWithGivenCertificatesArray(String conversionTarget) + throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, PemConversionException { + + // given + final PemConverter converter = new PemConverter(conversionTarget); + final String alias = "trusted-certificate-"; + final String alias1 = alias + 1; + final String alias2 = alias + 2; + final Password password = new Password("9z6oFx1epRSCuBWU4Er8i_0y"); + final List trustedCertificates = getCertificates(); + final KeyStore expectedTrustStore = KeyStore.getInstance(conversionTarget); + expectedTrustStore.load(new ByteArrayInputStream(Files.readAllBytes(Path.of(EXPECTED_TRUSTSTORE_PATH))), + password.toCharArray()); + + // when + final byte[] result = converter.convertTruststore(trustedCertificates, password, alias); + + // then + final KeyStore actualKeyStore = KeyStore.getInstance(conversionTarget); + actualKeyStore.load(new ByteArrayInputStream(result), password.toCharArray()); + + assertTrue(actualKeyStore.containsAlias(alias1)); + assertTrue(actualKeyStore.containsAlias(alias2)); + assertEquals(expectedTrustStore.getCertificate(alias1), actualKeyStore.getCertificate(alias1)); + assertEquals(expectedTrustStore.getCertificate(alias2), actualKeyStore.getCertificate(alias2)); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertTruststoreShouldThrowPemConverterExceptionBecauseOfWrongPassword(String conversionTarget) throws IOException { + // given + final String alias = "trusted-certificate-"; + final Password password = new Password("nokia"); + final List trustedCertificates = getCertificates(); + final PemConverter converter = new PemConverter(conversionTarget); + + // when then + assertThatThrownBy(() -> + converter.convertTruststore(trustedCertificates, password, alias)) + .isInstanceOf(PemConversionException.class).hasMessage(PASSWORD_ERROR_MSG); + } + + @Test + void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongPrivateKey() throws IOException { + // given + final String alias = "keystore-entry"; + final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); + final List certificateChain = getCertificates(); + final PemConverter converter = new PemConverter(PKCS12); + + // when then + assertThatThrownBy(() -> converter.convertKeystore(certificateChain, password, alias, privateKey)) + .isInstanceOf(PemConversionException.class).hasMessage(KEY_ERROR_MSG); + } + + @ParameterizedTest + @ValueSource(strings = {PKCS12, JKS}) + void convertKeystoreShouldThrowPemConverterExceptionBecauseOfWrongCertificates(String conversionTarget) { + // given + final String alias = "keystore-entry"; + final Password password = new Password("d9D_u8LooYaXH4G48DtN#vw0"); + final List certificateChain = List.of("certificate1", "certificate2"); + final PemConverter converter = new PemConverter(conversionTarget); + privateKeyMockSetup(); + + // when then + assertThatThrownBy(() -> converter.convertKeystore(certificateChain, password, alias, privateKey)) + .isInstanceOf(PemConversionException.class).hasMessage(CERTIFICATES_ERROR_MSG); + } + + private void privateKeyMockSetup() { + when(privateKey.getEncoded()).thenReturn(key); + when(privateKey.getAlgorithm()).thenReturn(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM); + when(privateKey.getFormat()).thenReturn(PKCS8); + } + + private List getCertificates() throws IOException { + return List.of( + Files.readString( + Path.of(CERT1_PATH), StandardCharsets.UTF_8), + Files.readString( + Path.of(CERT2_PATH), StandardCharsets.UTF_8) + ); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java new file mode 100644 index 00000000..3457f32a --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/conversion/RandomPasswordGeneratorTest.java @@ -0,0 +1,33 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.conversion; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RandomPasswordGeneratorTest { + + @Test + void shouldGenerateRandomPasswordOfGivenLengthMatchingThePattern() { + Password password = new RandomPasswordGenerator().generate(24); + assertTrue(password.isCorrectPasswordPattern()); + } +} \ No newline at end of file diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/writer/CertFileWriterTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/writer/CertFileWriterTest.java new file mode 100644 index 00000000..11259368 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/certification/writer/CertFileWriterTest.java @@ -0,0 +1,76 @@ +/*============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.certification.writer; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.onap.oom.certservice.client.certification.exception.CertFileWriterException; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CertFileWriterTest { + + private static final String RESOURCES_PATH = "src/test/resources/"; + private static final String OUTPUT_PATH = RESOURCES_PATH + "generatedFiles/"; + private static final String NOT_EXISTING_OUTPUT_PATH = OUTPUT_PATH + "directoryDoesNotExist/"; + private static final String TRUSTSTORE_P12 = "truststore.p12"; + private File outputDirectory = new File(OUTPUT_PATH); + + @AfterEach + void cleanUpFiles() { + deleteDirectoryRecursive(outputDirectory); + } + + @ParameterizedTest + @ValueSource(strings = {OUTPUT_PATH, NOT_EXISTING_OUTPUT_PATH}) + void certFileWriterShouldCreateFilesWithDataInGivenLocation(String outputPath) + throws IOException, CertFileWriterException { + // given + File truststore = new File(outputPath + TRUSTSTORE_P12); + CertFileWriter certFileWriter = CertFileWriter.createWithDir(outputPath); + final byte[] data = new byte[]{-128, 1, 2, 3, 127}; + + // when + certFileWriter.saveData(data, TRUSTSTORE_P12); + + // then + assertThat(truststore.exists()).isTrue(); + assertThat(Files.readAllBytes(Path.of(outputPath + TRUSTSTORE_P12))).isEqualTo(data); + } + + private void deleteDirectoryRecursive(File dirForDeletion) { + List.of(dirForDeletion.listFiles()).forEach(file -> { + if (file.isDirectory()) { + deleteDirectoryRecursive(file); + } + file.delete(); + }); + dirForDeletion.delete(); + } + +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvProviderTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvProviderTest.java new file mode 100644 index 00000000..3181ec9f --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvProviderTest.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +class EnvProviderTest { + private static final String TEST_ENV = "testEnv"; + private static final String TEST_ENV_VALUE = "prod"; + + private EnvProvider envProvider; + + @BeforeEach + void setUp() { + envProvider = Mockito.spy(EnvProvider.class); + } + + @Test + void shouldReturnSystemEnvVariableWhenItWasDefined() { + // given + when(envProvider.getSystemEnv(TEST_ENV)).thenReturn(TEST_ENV_VALUE); + + // when + final Optional testEnv = envProvider.readEnvVariable(TEST_ENV); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV_VALUE); + } + + @Test + void shouldReportThatSystemEnvVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envProvider.readEnvVariable(TEST_ENV); + + // then + assertThat(testEnv).isNotPresent(); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForCsrTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForCsrTest.java new file mode 100644 index 00000000..ade13f75 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForCsrTest.java @@ -0,0 +1,201 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +class EnvsForCsrTest { + private static final String TEST_ENV = "testEnv"; + private EnvsForCsr envsForCsr; + + @BeforeEach + public void setUp() { + envsForCsr = Mockito.spy(EnvsForCsr.class); + } + + @Test + void shouldReturnSystemEnvCommonNameVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.COMMON_NAME)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getCommonName(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvCommonNameVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getCommonName(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvOrganizationVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.ORGANIZATION)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getOrganization(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvOrganizationVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getOrganization(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvOuVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.ORGANIZATION_UNIT)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getOrganizationUnit(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + public void shouldReportThatSystemEnvOuVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getOrganizationUnit(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvLocationVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.LOCATION)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getLocation(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvLocationVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getLocation(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvStateVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.STATE)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getState(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvStateVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getState(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvCountryVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.COUNTRY)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getCountry(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvCountryVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getCountry(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvSansVariableWhenItWasDefined() { + // given + when(envsForCsr.readEnv(CsrConfigurationEnvs.SANS)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForCsr.getSubjectAlternativesName(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + public void shouldReportThatSystemEnvSansVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForCsr.getSubjectAlternativesName(); + + // then + assertThat(testEnv).isNotPresent(); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForTlsTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForTlsTest.java new file mode 100644 index 00000000..54ed56b7 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/EnvsForTlsTest.java @@ -0,0 +1,133 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +class EnvsForTlsTest { + + private static final String TEST_ENV = "testEnv"; + private EnvsForTls envsForTls; + + @BeforeEach + public void setUp() { + envsForTls = Mockito.spy(EnvsForTls.class); + } + + @Test + void shouldReturnSystemEnvKeyStorePathVariableWhenItWasDefined() { + // given + when(envsForTls.readEnv(TlsConfigurationEnvs.KEYSTORE_PATH)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForTls.getKeystorePath(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvKeyStorePathVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForTls.getKeystorePath(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvKeyStorePasswordVariableWhenItWasDefined() { + // given + when(envsForTls.readEnv(TlsConfigurationEnvs.KEYSTORE_PASSWORD)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForTls.getKeystorePassword(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvKeyStorePasswordVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForTls.getKeystorePassword(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvTrustStorePathVariableWhenItWasDefined() { + // given + when(envsForTls.readEnv(TlsConfigurationEnvs.TRUSTSTORE_PATH)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForTls.getTruststorePath(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvTrustStorePathVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForTls.getTruststorePath(); + + // then + assertThat(testEnv).isNotPresent(); + } + + @Test + void shouldReturnSystemEnvTrustStorePasswordVariableWhenItWasDefined() { + // given + when(envsForTls.readEnv(TlsConfigurationEnvs.TRUSTSTORE_PASSWORD)).thenReturn(Optional.of(TEST_ENV)); + + // when + final Optional testEnv = envsForTls.getTruststorePassword(); + + // then + assertThat(testEnv) + .isPresent() + .contains(TEST_ENV); + } + + @Test + void shouldReportThatSystemEnvTrustStorePasswordVariableIsNotPresentWhenItWasNotDefined() { + // when + final Optional testEnv = envsForTls.getTruststorePassword(); + + // then + assertThat(testEnv).isNotPresent(); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java new file mode 100644 index 00000000..6ebc3f2a --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/exception/TlsConfigurationExceptionTest.java @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.exception; + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.api.ExitStatus; + +import static org.assertj.core.api.Assertions.assertThat; + + +class TlsConfigurationExceptionTest { + + @Test + void containsProperExitStatus() { + // Given + ExitStatus exitStatus = null; + + // When + try { + throw new TlsConfigurationException("Test message"); + } catch (TlsConfigurationException e) { + exitStatus = e.applicationExitStatus(); + } + + // Then + assertThat(exitStatus) + .isNotNull() + .isEqualTo(ExitStatus.TLS_CONFIGURATION_EXCEPTION); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java new file mode 100644 index 00000000..e55e55b6 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/AbstractConfigurationFactoryTest.java @@ -0,0 +1,93 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.factory; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +class AbstractConfigurationFactoryTest { + + private final AbstractConfigurationFactory cut = mock(AbstractConfigurationFactory.class, Mockito.CALLS_REAL_METHODS); + + @ParameterizedTest + @ValueSource(strings = {"/var/log", "/", "/var/log/", "/second_var", "/second-var"}) + void shouldAcceptValidPath(String path) { + assertThat(cut.isPathValid(path)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"/var/log?", "", "var_", "var", "//", "/var//log"}) + void shouldRejectInvalidPath(String path) { + assertThat(cut.isPathValid(path)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"PL", "DE", "PN", "US", "IO", "CA", "KH", "CO", "DK", "EC", "CZ", "CN", "BR", "BD", "BE"}) + void shouldAcceptValidCountryCode(String countryCode) { + assertThat(cut.isCountryValid(countryCode)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"", "QQ", "AFG", "D", "&*", "!", "ONAP", "p", "pl", "us", "afg"}) + void shouldRejectInvalidCountryCode(String countryCode) { + assertThat(cut.isCountryValid(countryCode)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"caname", "caname1", "123caName", "ca1name"}) + void shouldAcceptValidAlphanumeric(String caName) { + assertThat(cut.isAlphaNumeric(caName)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"44caname$", "#caname1", "1c_aname", "ca1-name"}) + void shouldRejectInvalidAlphanumeric(String caName) { + assertThat(cut.isAlphaNumeric(caName)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"example.com", "www.example.com"}) + void shouldAcceptValidCommonName(String commonName) { + assertThat(cut.isCommonNameValid(commonName)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"https://example.com", "http://example.com", "example.com:8080", "0.0.0.0", "@#$%.com"}) + void shouldRejectInvalidCommonName(String commonName) { + assertThat(cut.isCommonNameValid(commonName)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"JKS", "P12", "PEM"}) + void shouldAcceptValidOutputType(String outputType) { + assertThat(cut.isOutputTypeValid(outputType)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"jks", "p12", "pem", "", "pass", "!@$#pp"}) + void shouldRejectInvalidOutputType(String outputType) { + assertThat(cut.isOutputTypeValid(outputType)).isFalse(); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java new file mode 100644 index 00000000..44827494 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/ClientConfigurationFactoryTest.java @@ -0,0 +1,155 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.factory; + +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.configuration.ClientConfigurationEnvs; +import org.onap.oom.certservice.client.configuration.EnvsForClient; +import org.onap.oom.certservice.client.configuration.exception.ClientConfigurationException; +import org.onap.oom.certservice.client.configuration.model.ClientConfiguration; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ClientConfigurationFactoryTest { + + private static final String CA_NAME_VALID = "catest2"; + private static final String TIME_OUT_VALID = "30000"; + private static final String OUTPUT_PATH_VALID = "/opt/app/oom"; + private static final String URL_TO_CERT_SERVICE_VALID = "https://cert-service:8443/v1/certificate/"; + private static final String URL_TO_CERT_SERVICE_DEFAULT = "https://oom-cert-service:8443/v1/certificate/"; + private static final String CA_NAME_INVALID = "catest2#$"; + private static final String OUTPUT_PATH_INVALID = "/opt//app/oom"; + private static final String OUTPUT_TYPE_VALID = "JKS"; + private static final String OUTPUT_TYPE_INVALID = "JKSS"; + private static final String OUTPUT_TYPE_DEFAULT = "P12"; + + private EnvsForClient envsForClient = mock(EnvsForClient.class); + + + @Test + void create_shouldReturnSuccessWhenAllVariablesAreSetAndValid() throws ClientConfigurationException { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); + when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); + when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_VALID)); + + // when + ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); + System.out.println(configuration.toString()); + + // then + assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); + assertThat(configuration.getRequestTimeout()).isEqualTo(Integer.valueOf(TIME_OUT_VALID)); + assertThat(configuration.getCertsOutputPath()).isEqualTo(OUTPUT_PATH_VALID); + assertThat(configuration.getUrlToCertService()).isEqualTo(URL_TO_CERT_SERVICE_VALID); + assertThat(configuration.getOutputType()).isEqualTo(OUTPUT_TYPE_VALID); + } + + @Test + void create_shouldReturnSuccessWhenDefaultVariablesAreNotSet() throws ClientConfigurationException { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + + // when + ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); + + // then + assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); + assertThat(configuration.getRequestTimeout()).isEqualTo(Integer.valueOf(TIME_OUT_VALID)); + assertThat(configuration.getCertsOutputPath()).isEqualTo(OUTPUT_PATH_VALID); + assertThat(configuration.getUrlToCertService()).isEqualTo(URL_TO_CERT_SERVICE_DEFAULT); + assertThat(configuration.getOutputType()).isEqualTo(OUTPUT_TYPE_DEFAULT); + } + + @Test + void create_shouldReturnClientExceptionWhenRequiredVariableIsNotSet() { + // given + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + + // when + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + + // then + assertThatExceptionOfType(ClientConfigurationException.class) + .isThrownBy(configurationFactory::create) + .withMessageContaining(ClientConfigurationEnvs.CA_NAME + " is invalid."); + } + + @Test + void create_shouldReturnClientExceptionWhenCaNameContainsSpecialCharacters() { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_INVALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); + when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); + + // when + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + + // when/then + assertThatExceptionOfType(ClientConfigurationException.class) + .isThrownBy(configurationFactory::create) + .withMessageContaining(ClientConfigurationEnvs.CA_NAME + " is invalid."); + } + + @Test + void create_shouldReturnClientExceptionWhenOutputPathContainsSpecialCharacters() { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_INVALID)); + when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); + when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); + + // when + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + + //then + assertThatExceptionOfType(ClientConfigurationException.class) + .isThrownBy(configurationFactory::create) + .withMessageContaining(ClientConfigurationEnvs.OUTPUT_PATH + " is invalid."); + } + + @Test + void create_shouldReturnClientExceptionWhenOutputTypeIsInvalid() { + // given + when(envsForClient.getCaName()).thenReturn(Optional.of(CA_NAME_VALID)); + when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); + when(envsForClient.getRequestTimeOut()).thenReturn(Optional.of(TIME_OUT_VALID)); + when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); + when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_INVALID)); + + // when + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + + //then + assertThatExceptionOfType(ClientConfigurationException.class) + .isThrownBy(configurationFactory::create) + .withMessageContaining(ClientConfigurationEnvs.OUTPUT_TYPE + " is invalid."); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java new file mode 100644 index 00000000..e27cb57a --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/CsrConfigurationFactoryTest.java @@ -0,0 +1,186 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.factory; + +import org.assertj.core.api.Condition; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.configuration.CsrConfigurationEnvs; +import org.onap.oom.certservice.client.configuration.EnvsForCsr; +import org.onap.oom.certservice.client.configuration.exception.CsrConfigurationException; +import org.onap.oom.certservice.client.configuration.model.CsrConfiguration; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.oom.certservice.client.api.ExitStatus.CSR_CONFIGURATION_EXCEPTION; + +public class CsrConfigurationFactoryTest { + + private static final String COMMON_NAME_VALID = "onap.org"; + private static final String SANS_VALID = "test-name"; + private static final String COUNTRY_VALID = "US"; + private static final String LOCATION_VALID = "San-Francisco"; + private static final String ORGANIZATION_VALID = "Linux-Foundation"; + private static final String ORGANIZATION_UNIT_VALID = "ONAP"; + private static final String STATE_VALID = "California"; + private static final String COMMON_NAME_INVALID = "onap.org*&"; + private static final String COUNTRY_INVALID = "PLA"; + private static final String ORGANIZATION_INVALID = "Linux?Foundation"; + + private EnvsForCsr envsForCsr = mock(EnvsForCsr.class); + private CsrConfigurationFactory testedFactory; + private Condition expectedExitCodeCondition = new Condition<>("Correct exit code") { + @Override + public boolean matches(CsrConfigurationException exception) { + return exception.applicationExitStatus() == CSR_CONFIGURATION_EXCEPTION; + } + }; + + @BeforeEach + void setUp() { + testedFactory = new CsrConfigurationFactory(envsForCsr); + } + + @Test + void shouldReturnCorrectConfiguration_WhenAllVariablesAreSetAndValid() throws CsrConfigurationException { + // given + mockEnvsWithAllValidParameters(); + + // when + CsrConfiguration configuration = testedFactory.create(); + + // then + assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); + assertThat(configuration.getSans()).isEqualTo(SANS_VALID); + assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); + assertThat(configuration.getLocation()).isEqualTo(LOCATION_VALID); + assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); + assertThat(configuration.getOrganizationUnit()).isEqualTo(ORGANIZATION_UNIT_VALID); + assertThat(configuration.getState()).isEqualTo(STATE_VALID); + } + + @Test + void shouldReturnCorrectConfiguration_WhenNotRequiredVariablesAreNotSet() throws CsrConfigurationException { + // given + mockEnvsWithValidRequiredParameters(); + + // when + CsrConfiguration configuration = testedFactory.create(); + + // then + assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); + assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); + assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); + assertThat(configuration.getState()).isEqualTo(STATE_VALID); + } + + + @Test + void shouldThrowCsrConfigurationException_WhenCommonNameInvalid() { + // given + mockEnvsWithInvalidCommonName(); + + // when/then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(testedFactory::create) + .withMessageContaining(CsrConfigurationEnvs.COMMON_NAME + " is invalid.") + .has(expectedExitCodeCondition); + } + + @Test + void shouldThrowCsrConfigurationException_WhenOrganizationInvalid() { + // given + mockEnvsWithInvalidOrganization(); + + // when/then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(testedFactory::create) + .withMessageContaining(CsrConfigurationEnvs.ORGANIZATION + " is invalid.") + .has(expectedExitCodeCondition); + + } + + @Test + void shouldThrowCsrConfigurationException_WhenCountryInvalid() { + // given + mockEnvsWithInvalidCountry(); + + // when/then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(testedFactory::create) + .withMessageContaining(CsrConfigurationEnvs.COUNTRY + " is invalid.") + .has(expectedExitCodeCondition); + + } + + @Test + void shouldThrowCsrConfigurationExceptionWhenStateInvalid() { + // given + mockEnvsWithInvalidState(); + // when/then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(testedFactory::create) + .withMessageContaining(CsrConfigurationEnvs.STATE + " is invalid.") + .has(expectedExitCodeCondition); + } + + private void mockEnvsWithAllValidParameters() { + mockEnvsWithValidRequiredParameters(); + mockEnvsWithValidOptionalParameters(); + } + + private void mockEnvsWithValidOptionalParameters() { + when(envsForCsr.getOrganizationUnit()).thenReturn(Optional.of(ORGANIZATION_UNIT_VALID)); + when(envsForCsr.getLocation()).thenReturn(Optional.of(LOCATION_VALID)); + when(envsForCsr.getSubjectAlternativesName()).thenReturn(Optional.of(SANS_VALID)); + } + + private void mockEnvsWithValidRequiredParameters() { + when(envsForCsr.getCommonName()).thenReturn(Optional.of(COMMON_NAME_VALID)); + when(envsForCsr.getCountry()).thenReturn(Optional.of(COUNTRY_VALID)); + when(envsForCsr.getOrganization()).thenReturn(Optional.of(ORGANIZATION_VALID)); + when(envsForCsr.getState()).thenReturn(Optional.of(STATE_VALID)); + } + + private void mockEnvsWithInvalidCommonName() { + mockEnvsWithAllValidParameters(); + when(envsForCsr.getCommonName()).thenReturn(Optional.of(COMMON_NAME_INVALID)); + } + + private void mockEnvsWithInvalidCountry() { + mockEnvsWithAllValidParameters(); + when(envsForCsr.getCountry()).thenReturn(Optional.of(COUNTRY_INVALID)); + } + + private void mockEnvsWithInvalidOrganization() { + mockEnvsWithAllValidParameters(); + when(envsForCsr.getOrganization()).thenReturn(Optional.of(ORGANIZATION_INVALID)); + } + + private void mockEnvsWithInvalidState() { + mockEnvsWithAllValidParameters(); + when(envsForCsr.getState()).thenReturn(Optional.empty()); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java new file mode 100644 index 00000000..923bc18d --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java @@ -0,0 +1,197 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.configuration.factory; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.oom.certservice.client.configuration.EnvsForTls; +import org.onap.oom.certservice.client.configuration.exception.TlsConfigurationException; + +import javax.net.ssl.SSLContext; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + + +@ExtendWith(MockitoExtension.class) +public class SslContextFactoryTest { + + public static final String INVALID_KEYSTORE_PATH = "nonexistent/keystore"; + public static final String VALID_KEYSTORE_NAME = "keystore.jks"; + public static final String VALID_KEYSTORE_PASSWORD = "secret"; + public static final String INVALID_KEYSTORE_PASSWORD = "wrong_secret"; + public static final String INVALID_TRUSTSTORE_PATH = "nonexistent/truststore"; + public static final String VALID_TRUSTSTORE_PASSWORD = "secret"; + public static final String INVALID_TRUSTSTORE_PASSWORD = "wrong_secret"; + public static final String VALID_TRUSTSTORE_NAME = "truststore.jks"; + @Mock + private EnvsForTls envsForTls; + + @Test + public void shouldThrowExceptionWhenKeystorePathEnvIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.empty()); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + Exception exception = assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + assertThat(exception.getMessage()).contains("KEYSTORE_PATH"); + } + + @Test + public void shouldThrowExceptionWhenKeystorePasswordEnvIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.empty()); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + Exception exception = assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + assertThat(exception.getMessage()).contains("KEYSTORE_PASSWORD"); + } + + @Test + public void shouldThrowExceptionWhenTruststorePathEnvIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); + when(envsForTls.getTruststorePath()).thenReturn(Optional.empty()); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + Exception exception = assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + assertThat(exception.getMessage()).contains("TRUSTSTORE_PATH"); + } + + @Test + public void shouldThrowExceptionWhenTruststorePasswordEnvIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore")); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.empty()); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + Exception exception = assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + assertThat(exception.getMessage()).contains("TRUSTSTORE_PASSWORD"); + } + + @Test + public void shouldThrowExceptionWhenKeystoreIsMissing() { + // Given + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(INVALID_KEYSTORE_PATH)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("secret")); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore.jks")); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of("secret")); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + } + + @Test + public void shouldThrowExceptionWhenKeystorePasswordIsWrong() { + // Given + String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(INVALID_KEYSTORE_PASSWORD)); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of(VALID_TRUSTSTORE_NAME)); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + } + + @Test + public void shouldThrowExceptionWhenTruststoreIsMissing() { + // Given + String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PATH)); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + } + + @Test + public void shouldThrowExceptionWhenTruststorePasswordIsWrong() { + // Given + String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); + String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PASSWORD)); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When, Then + assertThrows( + TlsConfigurationException.class, sslContextFactory::create + ); + } + + @Test + public void shouldReturnSslContext() throws TlsConfigurationException { + // Given + String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); + String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); + when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); + when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); + when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); + when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); + SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); + + // When + SSLContext sslContext = sslContextFactory.create(); + + // Then + assertNotNull(sslContext); + } + + private String getResourcePath(String resource) { + return getClass().getClassLoader().getResource(resource).getFile(); + } +} + diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/httpclient/HttpClientTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/httpclient/HttpClientTest.java new file mode 100644 index 00000000..553de25c --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/httpclient/HttpClientTest.java @@ -0,0 +1,144 @@ +/* + * ============LICENSE_START======================================================= + * oom-certservice-client + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.oom.certservice.client.httpclient; + +import org.apache.http.HttpEntity; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.oom.certservice.client.httpclient.exception.CertServiceApiResponseException; +import org.onap.oom.certservice.client.httpclient.exception.HttpClientException; +import org.onap.oom.certservice.client.httpclient.model.CertServiceResponse; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.List; + +import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; +import static java.net.HttpURLConnection.HTTP_OK; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.CA_NAME; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.CORRECT_RESPONSE; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.CSR; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.MISSING_PK_RESPONSE; +import static org.onap.oom.certservice.client.CerServiceRequestTestData.PK; + +class HttpClientTest { + + private HttpClient httpClient; + private CloseableHttpClient closeableHttpClient; + private HttpEntity httpEntity; + private StatusLine statusLine; + private CloseableHttpResponse httpResponse; + + @BeforeEach + void setUp() { + + closeableHttpClient = mock(CloseableHttpClient.class); + httpEntity = mock(HttpEntity.class); + statusLine = mock(StatusLine.class); + httpResponse = mock(CloseableHttpResponse.class); + + CloseableHttpsClientProvider httpClientProvider = mock(CloseableHttpsClientProvider.class); + + when(httpClientProvider.getClient()).thenReturn(closeableHttpClient); + String testCertServiceAddress = ""; + httpClient = new HttpClient(httpClientProvider, testCertServiceAddress); + } + + @Test + void shouldReturnCorrectListsOfCertificatedChainsAndTrustedCertificates_WhenRequestDataIsCorrect() + throws Exception { + + // given + mockServerResponse(HTTP_OK, CORRECT_RESPONSE); + + // when + CertServiceResponse certServiceResponse = + httpClient.retrieveCertServiceData(CA_NAME, CSR, PK); + List certificateChain = certServiceResponse.getCertificateChain(); + List trustedCertificate = certServiceResponse.getTrustedCertificates(); + + // then + assertThat(certServiceResponse).isNotNull(); + + final int expectedTwoElements = 2; + + assertThat(certificateChain).hasSize(expectedTwoElements); + assertThat(trustedCertificate).hasSize(expectedTwoElements); + + assertThat(certificateChain.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN); + assertThat(trustedCertificate.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES); + } + + @Test + void shouldThrowCertServiceApiResponseException_WhenPkHeaderIsMissing() throws Exception { + + //given + mockServerResponse(HTTP_BAD_REQUEST, MISSING_PK_RESPONSE); + + //when //then + assertThatExceptionOfType(CertServiceApiResponseException.class) + .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); + } + + @Test + void shouldThrowHttpClientException_WhenCannotExecuteRequestToApi() throws Exception { + + //given + when(closeableHttpClient.execute(any(HttpGet.class))).thenThrow(IOException.class); + + //when //then + assertThatExceptionOfType(HttpClientException.class) + .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); + } + + @Test + void shouldThrowHttpClientException_WhenCannotParseResponseToString() throws Exception { + + //given + mockServerResponse(HTTP_OK, CORRECT_RESPONSE); + when(httpEntity.getContent()).thenThrow(IOException.class); + + //when //then + assertThatExceptionOfType(HttpClientException.class) + .isThrownBy(() -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); + } + + private void mockServerResponse(int serverCodeResponse, String stringResponse) + throws IOException { + when(statusLine.getStatusCode()).thenReturn(serverCodeResponse); + when(httpResponse.getStatusLine()).thenReturn(statusLine); + when(httpResponse.getEntity()).thenReturn(httpEntity); + when(closeableHttpClient.execute(any(HttpGet.class))).thenReturn(httpResponse); + + when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream(stringResponse.getBytes())); + } +} -- cgit 1.2.3-korg