diff options
author | 2020-11-12 07:54:33 +0100 | |
---|---|---|
committer | 2020-11-13 07:56:47 +0100 | |
commit | 0ec765505c71f024db65eadb2a21069fb9297028 (patch) | |
tree | d84021fd796c02c54d0f3804ce0c5d7b2c425d5f /certServiceClient/src | |
parent | af2527b17fb5f5242360cd908e4cae852b1f2512 (diff) |
[OOM ext-cert-provider] Refacor in validation (intermediate solution)
Atomic validation function moved to BasicValidationFunctions
More complex validation is served by ValidatorsFactory
Sans property class object changed to List<String>
Signed-off-by: kjaniak <kornel.janiak@nokia.com>
Issue-ID: OOM-2559
Change-Id: I4719499dde969db95e2caa172f767674690c40e1
Diffstat (limited to 'certServiceClient/src')
14 files changed, 283 insertions, 164 deletions
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 index d115380f..d26be8d3 100644 --- a/certServiceClient/src/main/java/org/onap/oom/certservice/client/CertServiceClient.java +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/CertServiceClient.java @@ -19,6 +19,12 @@ package org.onap.oom.certservice.client; +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; + +import java.security.KeyPair; +import javax.net.ssl.SSLContext; import org.onap.oom.certservice.client.api.ExitableException; import org.onap.oom.certservice.client.certification.ArtifactsCreatorProvider; import org.onap.oom.certservice.client.certification.CsrFactory; @@ -33,19 +39,13 @@ import org.onap.oom.certservice.client.configuration.factory.CsrConfigurationFac 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.configuration.validation.ValidatorsFactory; 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); @@ -60,29 +60,32 @@ public class CertServiceClient { KeyPairFactory keyPairFactory = new KeyPairFactory(RSA_ENCRYPTION_ALGORITHM, KEY_SIZE); PrivateKeyToPemEncoder pkEncoder = new PrivateKeyToPemEncoder(); Base64Encoder base64Encoder = new Base64Encoder(); + ValidatorsFactory validatorsFactory = new ValidatorsFactory(); try { - ClientConfiguration clientConfiguration = new ClientConfigurationFactory(new EnvsForClient()).create(); - CsrConfiguration csrConfiguration = new CsrConfigurationFactory(new EnvsForCsr()).create(); + ClientConfiguration clientConfiguration = new ClientConfigurationFactory(new EnvsForClient(), + validatorsFactory).create(); + CsrConfiguration csrConfiguration = new CsrConfigurationFactory(new EnvsForCsr(), validatorsFactory) + .create(); KeyPair keyPair = keyPairFactory.create(); CsrFactory csrFactory = new CsrFactory(csrConfiguration); SSLContext sslContext = new SslContextFactory(new EnvsForTls()).create(); CloseableHttpsClientProvider provider = new CloseableHttpsClientProvider( - sslContext, clientConfiguration.getRequestTimeout()); + sslContext, clientConfiguration.getRequestTimeoutInMs()); HttpClient httpClient = new HttpClient(provider, clientConfiguration.getUrlToCertService()); CertServiceResponse certServiceData = - httpClient.retrieveCertServiceData( - clientConfiguration.getCaName(), - base64Encoder.encode(csrFactory.createCsrInPem(keyPair)), - base64Encoder.encode(pkEncoder.encodePrivateKeyToPem(keyPair.getPrivate()))); + 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()); + .get(clientConfiguration.getOutputType(), + clientConfiguration.getCertsOutputPath()) + .create(certServiceData.getCertificateChain(), + certServiceData.getTrustedCertificates(), + keyPair.getPrivate()); } catch (ExitableException e) { LOGGER.error("Cert Service Client fails in execution: ", e); 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 index ac517be4..04216ff4 100644 --- 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 @@ -19,6 +19,21 @@ package org.onap.oom.certservice.client.certification; +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; + +import java.io.IOException; +import java.io.StringWriter; +import java.security.KeyPair; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.Extensions; @@ -36,25 +51,10 @@ 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; @@ -75,27 +75,29 @@ public class CsrFactory { 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())); + 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))); + .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))); + .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()); + private PKCS10CertificationRequest createPkcs10Csr(X500Principal subject, KeyPair keyPair) + throws CsrGenerationException { + JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject, + keyPair.getPublic()); - if (isParameterPresent(configuration.getSans())) { + if (!configuration.getSans().isEmpty()) { builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, generateSansExtension()); } @@ -138,12 +140,11 @@ public class CsrFactory { } 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]); - } + List<String> sans = this.configuration.getSans(); + GeneralName[] generalNames = sans.stream() + .map(san -> new GeneralName(GeneralName.dNSName, san)) + .collect(Collectors.toList()) + .toArray(GeneralName[]::new); return new GeneralNames(generalNames); } 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 index 17cb2cc4..9f3ae9cc 100644 --- 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 @@ -20,22 +20,26 @@ package org.onap.oom.certservice.client.configuration.factory; +import java.util.Optional; 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.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions; +import org.onap.oom.certservice.client.configuration.validation.ValidatorsFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Optional; - -public class ClientConfigurationFactory extends AbstractConfigurationFactory<ClientConfiguration> { +public class ClientConfigurationFactory implements ConfigurationFactory<ClientConfiguration> { private static final Logger LOGGER = LoggerFactory.getLogger(ClientConfigurationFactory.class); private final EnvsForClient envsForClient; + private final ValidatorsFactory validatorsFactory; - public ClientConfigurationFactory(EnvsForClient envsForClient) { + + public ClientConfigurationFactory(EnvsForClient envsForClient, ValidatorsFactory validatorsFactory) { this.envsForClient = envsForClient; + this.validatorsFactory = validatorsFactory; } @Override @@ -43,29 +47,29 @@ public class ClientConfigurationFactory extends AbstractConfigurationFactory<Cli ClientConfiguration configuration = new ClientConfiguration(); - envsForClient.getUrlToCertService() - .map(configuration::setUrlToCertService); + .map(configuration::setUrlToCertService); envsForClient.getRequestTimeOut() - .map(timeout -> configuration.setRequestTimeout(Integer.valueOf(timeout))); + .map(timeout -> configuration.setRequestTimeoutInMs(Integer.valueOf(timeout))); envsForClient.getOutputPath() - .filter(this::isPathValid) - .map(configuration::setCertsOutputPath) - .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.OUTPUT_PATH + " is invalid.")); + .filter(BasicValidationFunctions::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.")); + .filter(BasicValidationFunctions::isAlphaNumeric) + .map(configuration::setCaName) + .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.CA_NAME + " is invalid.")); Optional<String> outputType = envsForClient.getOutputType(); if (outputType.isPresent()) { - outputType.filter(this::isOutputTypeValid) - .map(configuration::setOutputType) - .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.OUTPUT_TYPE + " is invalid.")); + outputType.filter(validatorsFactory.outputTypeValidator()) + .map(configuration::setOutputType) + .orElseThrow( + () -> new ClientConfigurationException(ClientConfigurationEnvs.OUTPUT_TYPE + " is invalid.")); } LOGGER.info("Successful validation of Client configuration. Configuration data: {}", configuration.toString()); diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/ConfigurationFactory.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/ConfigurationFactory.java new file mode 100644 index 00000000..43caf55c --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/ConfigurationFactory.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.configuration.factory; + + +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; + +interface ConfigurationFactory<T extends ConfigurationModel> { + + T create() throws ClientConfigurationException, CsrConfigurationException; + +} 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 index 0a88252c..3f87be52 100644 --- 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 @@ -20,21 +20,30 @@ package org.onap.oom.certservice.client.configuration.factory; +import static org.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions.isSpecialCharPresent; + +import java.util.Arrays; 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.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions; +import org.onap.oom.certservice.client.configuration.validation.ValidatorsFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class CsrConfigurationFactory extends AbstractConfigurationFactory<CsrConfiguration> { +public class CsrConfigurationFactory implements ConfigurationFactory<CsrConfiguration> { private static final Logger LOGGER = LoggerFactory.getLogger(CsrConfigurationFactory.class); + private static final String SANS_DELIMITER = ":"; + private final EnvsForCsr envsForCsr; + private final ValidatorsFactory validatorsFactory; - public CsrConfigurationFactory(EnvsForCsr envsForCsr) { + public CsrConfigurationFactory(EnvsForCsr envsForCsr, ValidatorsFactory validatorsFactory) { this.envsForCsr = envsForCsr; + this.validatorsFactory = validatorsFactory; } @Override @@ -43,12 +52,12 @@ public class CsrConfigurationFactory extends AbstractConfigurationFactory<CsrCon CsrConfiguration configuration = new CsrConfiguration(); envsForCsr.getCommonName() - .filter(this::isCommonNameValid) + .filter(validatorsFactory.commonNameValidator()) .map(configuration::setCommonName) .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COMMON_NAME + " is invalid.")); envsForCsr.getOrganization() - .filter(org -> !isSpecialCharsPresent(org)) + .filter(org -> !isSpecialCharPresent(org)) .map(configuration::setOrganization) .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.ORGANIZATION + " is invalid.")); @@ -57,7 +66,7 @@ public class CsrConfigurationFactory extends AbstractConfigurationFactory<CsrCon .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.STATE + " is invalid.")); envsForCsr.getCountry() - .filter(this::isCountryValid) + .filter(BasicValidationFunctions::isCountryValid) .map(configuration::setCountry) .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COUNTRY + " is invalid.")); @@ -68,10 +77,12 @@ public class CsrConfigurationFactory extends AbstractConfigurationFactory<CsrCon .map(configuration::setLocation); envsForCsr.getSubjectAlternativesName() + .map(sans -> Arrays.asList(sans.split(SANS_DELIMITER))) .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/model/ClientConfiguration.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/ClientConfiguration.java index cd8a5c1e..f87b525d 100644 --- 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 @@ -29,7 +29,7 @@ public class ClientConfiguration implements ConfigurationModel { private static final String DEFAULT_OUTPUT_TYPE = "P12"; private String urlToCertService; - private Integer requestTimeout; + private Integer requestTimeoutInMs; private String certsOutputPath; private String caName; private String outputType; @@ -37,7 +37,7 @@ public class ClientConfiguration implements ConfigurationModel { public ClientConfiguration() { urlToCertService = DEFAULT_REQUEST_URL; - requestTimeout = DEFAULT_TIMEOUT_MS; + requestTimeoutInMs = DEFAULT_TIMEOUT_MS; outputType = DEFAULT_OUTPUT_TYPE; } @@ -51,12 +51,12 @@ public class ClientConfiguration implements ConfigurationModel { return this; } - public Integer getRequestTimeout() { - return requestTimeout; + public Integer getRequestTimeoutInMs() { + return requestTimeoutInMs; } - public ClientConfiguration setRequestTimeout(Integer requestTimeout) { - this.requestTimeout = requestTimeout; + public ClientConfiguration setRequestTimeoutInMs(Integer requestTimeoutInMs) { + this.requestTimeoutInMs = requestTimeoutInMs; return this; } @@ -91,7 +91,7 @@ public class ClientConfiguration implements ConfigurationModel { 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.REQUEST_TIMEOUT, requestTimeoutInMs, 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/CsrConfiguration.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/CsrConfiguration.java index c5aefd97..382d1ffc 100644 --- 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 @@ -21,6 +21,7 @@ package org.onap.oom.certservice.client.configuration.model; +import java.util.List; import org.onap.oom.certservice.client.configuration.CsrConfigurationEnvs; public class CsrConfiguration implements ConfigurationModel { @@ -31,7 +32,7 @@ public class CsrConfiguration implements ConfigurationModel { private String country; private String organizationUnit; private String location; - private String sans; + private List<String> sans; public String getCommonName() { @@ -88,12 +89,12 @@ public class CsrConfiguration implements ConfigurationModel { return this; } - public String getSans() { + public List<String> getSans() { return sans; } - public CsrConfiguration setSubjectAlternativeNames(String subjectAlternativeNames) { - this.sans = subjectAlternativeNames; + public CsrConfiguration setSubjectAlternativeNames(List<String> subjectAlternativeNames) { + this.sans = List.copyOf(subjectAlternativeNames); return this; } 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/validation/BasicValidationFunctions.java index 293ac2d1..e5044c26 100644 --- 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/validation/BasicValidationFunctions.java @@ -18,60 +18,40 @@ * ============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; +package org.onap.oom.certservice.client.configuration.validation; import java.util.Arrays; import java.util.Locale; import java.util.regex.Pattern; -public abstract class AbstractConfigurationFactory<T extends ConfigurationModel> { +public class BasicValidationFunctions { - abstract T create() throws ClientConfigurationException, CsrConfigurationException; - - public boolean isPathValid(String path) { + public static boolean isPathValid(String path) { return path.matches("^/|(/[a-zA-Z0-9_-]+)+/?$"); } - public boolean isAlphaNumeric(String caName) { + public static 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) { + public static boolean isSpecialCharPresent(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) { + public static boolean isPortNumberPresent(String stringToCheck) { return Pattern.compile(":[0-9]{1,5}").matcher(stringToCheck).find(); } - private boolean isIpAddressPresent(String stringToCheck) { + public static 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) { + public static boolean isHttpProtocolsPresent(String stringToCheck) { return Pattern.compile("[h][t][t][p][:][/][/]|[h][t][t][p][s][:][/][/]").matcher(stringToCheck).find(); } + + public static boolean isCountryValid(String country) { + return Arrays.asList(Locale.getISOCountries()).contains(country); + } + } diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/ValidatorsFactory.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/ValidatorsFactory.java new file mode 100644 index 00000000..771ce3f2 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/ValidatorsFactory.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.validation; + +import static org.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions.isHttpProtocolsPresent; +import static org.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions.isIpAddressPresent; +import static org.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions.isPortNumberPresent; +import static org.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions.isSpecialCharPresent; + +import java.util.Arrays; +import java.util.function.Predicate; +import org.onap.oom.certservice.client.certification.ArtifactsCreatorProvider; + +public class ValidatorsFactory { + + public Predicate<String> commonNameValidator() { + return commonName -> + !isSpecialCharPresent(commonName) + && !isHttpProtocolsPresent(commonName) + && !isIpAddressPresent(commonName) + && !isPortNumberPresent(commonName); + } + + public Predicate<String> outputTypeValidator() { + return outputType -> Arrays.stream(ArtifactsCreatorProvider.values()) + .map(ArtifactsCreatorProvider::toString) + .anyMatch(name -> name.equals(outputType)); + } + +} 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 index e2bfa976..ee7d210f 100644 --- 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 @@ -20,6 +20,7 @@ package org.onap.oom.certservice.client.certification; +import java.util.List; import org.junit.jupiter.api.Test; import org.onap.oom.certservice.client.certification.exception.CsrGenerationException; import org.onap.oom.certservice.client.certification.exception.KeyPairGenerationException; @@ -43,7 +44,7 @@ class CsrFactoryTest { 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.getSans()).thenReturn(List.of("onapexample.com","onapexample.com.pl","onapexample.pl")); when(config.getCountry()).thenReturn("US"); when(config.getLocation()).thenReturn("San-Francisco"); when(config.getOrganization()).thenReturn("Linux-Foundation"); 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 index 44827494..071e7551 100644 --- 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 @@ -27,6 +27,7 @@ import org.onap.oom.certservice.client.configuration.exception.ClientConfigurati import org.onap.oom.certservice.client.configuration.model.ClientConfiguration; import java.util.Optional; +import org.onap.oom.certservice.client.configuration.validation.ValidatorsFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -47,6 +48,7 @@ public class ClientConfigurationFactoryTest { private static final String OUTPUT_TYPE_DEFAULT = "P12"; private EnvsForClient envsForClient = mock(EnvsForClient.class); + private ValidatorsFactory validatorsFactory = new ValidatorsFactory(); @Test @@ -59,12 +61,12 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_VALID)); // when - ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); + ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient, validatorsFactory).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.getRequestTimeoutInMs()).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); @@ -77,11 +79,11 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); // when - ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient).create(); + ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient, validatorsFactory).create(); // then assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); - assertThat(configuration.getRequestTimeout()).isEqualTo(Integer.valueOf(TIME_OUT_VALID)); + assertThat(configuration.getRequestTimeoutInMs()).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); @@ -93,7 +95,7 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, validatorsFactory); // then assertThatExceptionOfType(ClientConfigurationException.class) @@ -110,7 +112,7 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, validatorsFactory); // when/then assertThatExceptionOfType(ClientConfigurationException.class) @@ -127,7 +129,7 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, validatorsFactory); //then assertThatExceptionOfType(ClientConfigurationException.class) @@ -145,7 +147,7 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_INVALID)); // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient); + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, validatorsFactory); //then assertThatExceptionOfType(ClientConfigurationException.class) 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 index e27cb57a..238b979d 100644 --- 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 @@ -20,6 +20,7 @@ package org.onap.oom.certservice.client.configuration.factory; +import java.util.List; import org.assertj.core.api.Condition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,6 +30,7 @@ import org.onap.oom.certservice.client.configuration.exception.CsrConfigurationE import org.onap.oom.certservice.client.configuration.model.CsrConfiguration; import java.util.Optional; +import org.onap.oom.certservice.client.configuration.validation.ValidatorsFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -39,6 +41,7 @@ import static org.onap.oom.certservice.client.api.ExitStatus.CSR_CONFIGURATION_E public class CsrConfigurationFactoryTest { private static final String COMMON_NAME_VALID = "onap.org"; + private static final List<String> SANS_SPLITTED_VALID = List.of("test-name"); private static final String SANS_VALID = "test-name"; private static final String COUNTRY_VALID = "US"; private static final String LOCATION_VALID = "San-Francisco"; @@ -50,6 +53,7 @@ public class CsrConfigurationFactoryTest { private static final String ORGANIZATION_INVALID = "Linux?Foundation"; private EnvsForCsr envsForCsr = mock(EnvsForCsr.class); + private ValidatorsFactory validatorsFactory = new ValidatorsFactory(); private CsrConfigurationFactory testedFactory; private Condition<CsrConfigurationException> expectedExitCodeCondition = new Condition<>("Correct exit code") { @Override @@ -60,7 +64,7 @@ public class CsrConfigurationFactoryTest { @BeforeEach void setUp() { - testedFactory = new CsrConfigurationFactory(envsForCsr); + testedFactory = new CsrConfigurationFactory(envsForCsr, validatorsFactory); } @Test @@ -73,7 +77,7 @@ public class CsrConfigurationFactoryTest { // then assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); - assertThat(configuration.getSans()).isEqualTo(SANS_VALID); + assertThat(configuration.getSans()).isEqualTo(SANS_SPLITTED_VALID); assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); assertThat(configuration.getLocation()).isEqualTo(LOCATION_VALID); assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); 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/validation/BasicValidationFunctionsTest.java index e55e55b6..d552ba55 100644 --- 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/validation/BasicValidationFunctionsTest.java @@ -18,76 +18,52 @@ * ============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; +package org.onap.oom.certservice.client.configuration.validation; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; +import static org.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions.isAlphaNumeric; +import static org.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions.isCountryValid; +import static org.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions.isPathValid; -class AbstractConfigurationFactoryTest { +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; - private final AbstractConfigurationFactory cut = mock(AbstractConfigurationFactory.class, Mockito.CALLS_REAL_METHODS); +class BasicValidationFunctionsTest { @ParameterizedTest @ValueSource(strings = {"/var/log", "/", "/var/log/", "/second_var", "/second-var"}) void shouldAcceptValidPath(String path) { - assertThat(cut.isPathValid(path)).isTrue(); + assertThat(isPathValid(path)).isTrue(); } @ParameterizedTest @ValueSource(strings = {"/var/log?", "", "var_", "var", "//", "/var//log"}) void shouldRejectInvalidPath(String path) { - assertThat(cut.isPathValid(path)).isFalse(); + assertThat(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(); + assertThat(isCountryValid(countryCode)).isTrue(); } @ParameterizedTest @ValueSource(strings = {"", "QQ", "AFG", "D", "&*", "!", "ONAP", "p", "pl", "us", "afg"}) void shouldRejectInvalidCountryCode(String countryCode) { - assertThat(cut.isCountryValid(countryCode)).isFalse(); + assertThat(isCountryValid(countryCode)).isFalse(); } @ParameterizedTest @ValueSource(strings = {"caname", "caname1", "123caName", "ca1name"}) void shouldAcceptValidAlphanumeric(String caName) { - assertThat(cut.isAlphaNumeric(caName)).isTrue(); + assertThat(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(); + assertThat(isAlphaNumeric(caName)).isFalse(); } - @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/validation/ValidatorsFactoryTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/ValidatorsFactoryTest.java new file mode 100644 index 00000000..3c14d30f --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/ValidatorsFactoryTest.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.configuration.validation; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class ValidatorsFactoryTest { + + ValidatorsFactory cut = new ValidatorsFactory(); + + @ParameterizedTest + @ValueSource(strings = {"JKS", "P12", "PEM"}) + void shouldAcceptValidOutputType(String outputType) { + assertThat(cut.outputTypeValidator().test(outputType)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"jks", "p12", "pem", "", "pass", "!@$#pp"}) + void shouldRejectInvalidOutputType(String outputType) { + assertThat(cut.outputTypeValidator().test(outputType)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"example.com", "www.example.com"}) + void shouldAcceptValidCommonName(String commonName) { + assertThat(cut.commonNameValidator().test(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.commonNameValidator().test(commonName)).isFalse(); + } + +} |