diff options
author | kjaniak <kornel.janiak@nokia.com> | 2020-11-13 15:03:17 +0100 |
---|---|---|
committer | kjaniak <kornel.janiak@nokia.com> | 2020-11-25 12:30:39 +0100 |
commit | 5a9b5d9d6911a82e50c7d3e15c2cc8b9ca14098a (patch) | |
tree | 1f78ba5e0862c970a91370e272d3740289942c66 /certServiceClient | |
parent | 6043d57de1232277456200a7e218cfa53e444c05 (diff) |
[OOM cert-service-client] Add validation of email, ip and domain name
Added SanMapper to distinguish types of SANS.
ExitableException changed to RuntimeException.
Introcudced intermediate object San.
Issue-ID: OOM-2559
Signed-off-by: kjaniak <kornel.janiak@nokia.com>
Change-Id: I060de9869ab9fd737a474f683a251abd8431d224
Diffstat (limited to 'certServiceClient')
24 files changed, 632 insertions, 169 deletions
diff --git a/certServiceClient/pom.xml b/certServiceClient/pom.xml index a99732eb..d0cb5bd1 100644 --- a/certServiceClient/pom.xml +++ b/certServiceClient/pom.xml @@ -162,6 +162,10 @@ <artifactId>commons-lang3</artifactId> </dependency> <dependency> + <groupId>commons-validator</groupId> + <artifactId>commons-validator</artifactId> + </dependency> + <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> </dependency> 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 d26be8d3..afa38b99 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 @@ -25,6 +25,7 @@ import static org.onap.oom.certservice.client.certification.EncryptionAlgorithmC import java.security.KeyPair; import javax.net.ssl.SSLContext; +import org.onap.oom.certservice.client.api.ExitStatus; import org.onap.oom.certservice.client.api.ExitableException; import org.onap.oom.certservice.client.certification.ArtifactsCreatorProvider; import org.onap.oom.certservice.client.certification.CsrFactory; @@ -36,10 +37,12 @@ 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.SanMapper; 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.configuration.validation.client.OutputTypeValidator; +import org.onap.oom.certservice.client.configuration.validation.csr.CommonNameValidator; 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; @@ -60,12 +63,11 @@ 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(), - validatorsFactory).create(); - CsrConfiguration csrConfiguration = new CsrConfigurationFactory(new EnvsForCsr(), validatorsFactory) - .create(); + new OutputTypeValidator()).create(); + CsrConfiguration csrConfiguration = new CsrConfigurationFactory(new EnvsForCsr(), new CommonNameValidator(), + new SanMapper()).create(); KeyPair keyPair = keyPairFactory.create(); CsrFactory csrFactory = new CsrFactory(csrConfiguration); SSLContext sslContext = new SslContextFactory(new EnvsForTls()).create(); @@ -90,6 +92,9 @@ public class CertServiceClient { } catch (ExitableException e) { LOGGER.error("Cert Service Client fails in execution: ", e); appExitHandler.exit(e.applicationExitStatus()); + } catch (Exception e) { + LOGGER.error("Application failed (unexpected error): ", e); + appExitHandler.exit(ExitStatus.UNEXPECTED_EXCEPTION); } appExitHandler.exit(SUCCESS); } 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 index 1b1cc066..8ef79167 100644 --- 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 @@ -31,7 +31,8 @@ public enum ExitStatus { 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"); + FILE_CREATION_EXCEPTION(10, "File could not be created"), + UNEXPECTED_EXCEPTION(99, "Application exited abnormally"); private final int value; private final String 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 index ab7a308b..d488843f 100644 --- 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 @@ -19,7 +19,7 @@ package org.onap.oom.certservice.client.api; -public abstract class ExitableException extends Exception { +public abstract class ExitableException extends RuntimeException { public ExitableException(Throwable cause) { super(cause); } 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 04216ff4..1215e699 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 @@ -48,6 +48,7 @@ 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.onap.oom.certservice.client.configuration.model.San; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -140,9 +141,9 @@ public class CsrFactory { } private GeneralNames createGeneralNames() { - List<String> sans = this.configuration.getSans(); + List<San> sans = this.configuration.getSans(); GeneralName[] generalNames = sans.stream() - .map(san -> new GeneralName(GeneralName.dNSName, san)) + .map(san -> new GeneralName(san.getType(), san.getValue())) .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 9f3ae9cc..f1541b04 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 @@ -25,8 +25,8 @@ 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.onap.oom.certservice.client.configuration.validation.client.ClientEnvsValueValidators; +import org.onap.oom.certservice.client.configuration.validation.client.OutputTypeValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,12 +34,12 @@ public class ClientConfigurationFactory implements ConfigurationFactory<ClientCo private static final Logger LOGGER = LoggerFactory.getLogger(ClientConfigurationFactory.class); private final EnvsForClient envsForClient; - private final ValidatorsFactory validatorsFactory; + private final OutputTypeValidator outputTypeValidator; - public ClientConfigurationFactory(EnvsForClient envsForClient, ValidatorsFactory validatorsFactory) { + public ClientConfigurationFactory(EnvsForClient envsForClient, OutputTypeValidator outputTypeValidator) { this.envsForClient = envsForClient; - this.validatorsFactory = validatorsFactory; + this.outputTypeValidator = outputTypeValidator; } @Override @@ -54,19 +54,19 @@ public class ClientConfigurationFactory implements ConfigurationFactory<ClientCo .map(timeout -> configuration.setRequestTimeoutInMs(Integer.valueOf(timeout))); envsForClient.getOutputPath() - .filter(BasicValidationFunctions::isPathValid) + .filter(ClientEnvsValueValidators::isPathValid) .map(configuration::setCertsOutputPath) .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.OUTPUT_PATH + " is invalid.")); envsForClient.getCaName() - .filter(BasicValidationFunctions::isAlphaNumeric) + .filter(ClientEnvsValueValidators::isAlphaNumeric) .map(configuration::setCaName) .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.CA_NAME + " is invalid.")); Optional<String> outputType = envsForClient.getOutputType(); if (outputType.isPresent()) { - outputType.filter(validatorsFactory.outputTypeValidator()) + outputType.filter(outputTypeValidator) .map(configuration::setOutputType) .orElseThrow( () -> new ClientConfigurationException(ClientConfigurationEnvs.OUTPUT_TYPE + " is invalid.")); 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 d050a2a3..48ead884 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,15 +20,16 @@ package org.onap.oom.certservice.client.configuration.factory; -import static org.onap.oom.certservice.client.configuration.validation.BasicValidationFunctions.isSpecialCharPresent; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isSpecialCharPresent; import java.util.Arrays; +import java.util.stream.Collectors; 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.onap.oom.certservice.client.configuration.validation.csr.CommonNameValidator; +import org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,11 +40,14 @@ public class CsrConfigurationFactory implements ConfigurationFactory<CsrConfigur private static final String SANS_DELIMITER = ","; private final EnvsForCsr envsForCsr; - private final ValidatorsFactory validatorsFactory; + private final CommonNameValidator commonNameValidator; + private final SanMapper sanMapper; - public CsrConfigurationFactory(EnvsForCsr envsForCsr, ValidatorsFactory validatorsFactory) { + public CsrConfigurationFactory(EnvsForCsr envsForCsr, CommonNameValidator commonNameValidator, + SanMapper sanMapper) { this.envsForCsr = envsForCsr; - this.validatorsFactory = validatorsFactory; + this.commonNameValidator = commonNameValidator; + this.sanMapper = sanMapper; } @Override @@ -52,33 +56,34 @@ public class CsrConfigurationFactory implements ConfigurationFactory<CsrConfigur CsrConfiguration configuration = new CsrConfiguration(); envsForCsr.getCommonName() - .filter(validatorsFactory.commonNameValidator()) - .map(configuration::setCommonName) - .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COMMON_NAME + " is invalid.")); + .filter(commonNameValidator) + .map(configuration::setCommonName) + .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COMMON_NAME + " is invalid.")); envsForCsr.getOrganization() - .filter(org -> !isSpecialCharPresent(org)) - .map(configuration::setOrganization) - .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.ORGANIZATION + " is invalid.")); + .filter(org -> !isSpecialCharPresent(org)) + .map(configuration::setOrganization) + .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.ORGANIZATION + " is invalid.")); envsForCsr.getState() - .map(configuration::setState) - .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.STATE + " is invalid.")); + .map(configuration::setState) + .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.STATE + " is invalid.")); envsForCsr.getCountry() - .filter(BasicValidationFunctions::isCountryValid) - .map(configuration::setCountry) - .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COUNTRY + " is invalid.")); + .filter(CsrEnvsValueValidators::isCountryValid) + .map(configuration::setCountry) + .orElseThrow(() -> new CsrConfigurationException(CsrConfigurationEnvs.COUNTRY + " is invalid.")); envsForCsr.getOrganizationUnit() - .map(configuration::setOrganizationUnit); + .map(configuration::setOrganizationUnit); envsForCsr.getLocation() - .map(configuration::setLocation); + .map(configuration::setLocation); envsForCsr.getSubjectAlternativesName() .map(sans -> Arrays.asList(sans.split(SANS_DELIMITER))) - .map(configuration::setSubjectAlternativeNames); + .map(list -> list.stream().map(sanMapper).collect(Collectors.toList())) + .map(configuration::setSans); LOGGER.info("Successful validation of CSR configuration. Configuration data: {}", configuration.toString()); diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/SanMapper.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/SanMapper.java new file mode 100644 index 00000000..f76bd572 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/factory/SanMapper.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.factory; + +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isDomainNameValid; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isEmailAddressValid; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isIpAddressValid; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isUriValid; + +import java.util.function.Function; +import org.bouncycastle.asn1.x509.GeneralName; +import org.onap.oom.certservice.client.configuration.exception.CsrConfigurationException; +import org.onap.oom.certservice.client.configuration.model.San; + +public class SanMapper implements Function<String, San> { + + public San apply(String san) { + if (isEmailAddressValid(san)) { + return new San(san, GeneralName.rfc822Name); + } else if (isIpAddressValid(san)) { + return new San(san, GeneralName.iPAddress); + } else if (isDomainNameValid(san)) { + return new San(san, GeneralName.dNSName); + } else if (isUriValid(san)) { + return new San(san, GeneralName.uniformResourceIdentifier); + } else { + throw new CsrConfigurationException("SAN :" + san + " does not match any requirements"); + } + } +} 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 382d1ffc..3f77d259 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 @@ -32,7 +32,7 @@ public class CsrConfiguration implements ConfigurationModel { private String country; private String organizationUnit; private String location; - private List<String> sans; + private List<San> sans; public String getCommonName() { @@ -89,11 +89,11 @@ public class CsrConfiguration implements ConfigurationModel { return this; } - public List<String> getSans() { + public List<San> getSans() { return sans; } - public CsrConfiguration setSubjectAlternativeNames(List<String> subjectAlternativeNames) { + public CsrConfiguration setSans(List<San> subjectAlternativeNames) { this.sans = List.copyOf(subjectAlternativeNames); return this; } diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/San.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/San.java new file mode 100644 index 00000000..5ca36246 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/model/San.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.configuration.model; + +import java.util.Objects; + +public final class San { + + private final String value; + private final int type; + + public San(String value, int type) { + this.value = value; + this.type = type; + } + + public String getValue() { + return value; + } + + public int getType() { + return type; + } + + public String toString() { + return "{SAN value: " + value + ", type: " + getReadableType(type) + '}'; + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + San san1 = (San) o; + return type == san1.type && + Objects.equals(value, san1.value); + } + + public int hashCode() { + return Objects.hash(value, type); + } + + private String getReadableType(int type) { + String readableType = "undefined"; + switch (type) { + case 1: readableType = "rfc822Name"; break; + case 2: readableType = "dNSName"; break; + case 6: readableType = "uniformResourceIdentifier"; break; + case 7: readableType = "iPAddress"; break; + } + return readableType; + } +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/client/ClientEnvsValueValidators.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/client/ClientEnvsValueValidators.java new file mode 100644 index 00000000..503b7e46 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/client/ClientEnvsValueValidators.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.configuration.validation.client; + +public final class ClientEnvsValueValidators { + private static final String ALPHA_NUMERIC_REGEX = "^[a-zA-Z0-9]*$"; + private static final String VALID_PATH_REGEX = "^/|(/[a-zA-Z0-9_-]+)+/?$"; + + public static boolean isAlphaNumeric(String caName) { + return caName.matches(ALPHA_NUMERIC_REGEX); + } + + public static boolean isPathValid(String path) { + return path.matches(VALID_PATH_REGEX); + } +} 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/client/OutputTypeValidator.java index 8eeac74a..6b737e26 100644 --- 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/client/OutputTypeValidator.java @@ -18,34 +18,18 @@ * ============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; +package org.onap.oom.certservice.client.configuration.validation.client; 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 class OutputTypeValidator implements Predicate<String> { - public Predicate<String> outputTypeValidator() { - return outputType -> Arrays.stream(ArtifactsCreatorProvider.values()) + public boolean test(String outputType) { + return Arrays.stream(ArtifactsCreatorProvider.values()) .map(ArtifactsCreatorProvider::toString) .anyMatch(name -> name.equals(outputType)); } - public Predicate<String> uriValidator() { - return UriValidator::isValidUri; - } } diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/csr/CommonNameValidator.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/csr/CommonNameValidator.java new file mode 100644 index 00000000..a5244466 --- /dev/null +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/csr/CommonNameValidator.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.configuration.validation.csr; + +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isSpecialCharPresent; + +import java.util.function.Predicate; +import java.util.regex.Pattern; + +public final class CommonNameValidator implements Predicate<String> { + + private static final String PORT_POSTFIX_REGEX = ":[0-9]{1,5}"; + private static final String IPV4_ADDRESS_REGEX = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"; + private static final String HTTP_HTTPS_SCHEME_REGEX = "[h][t][t][p][:][/][/]|[h][t][t][p][s][:][/][/]"; + + public boolean test(String commonName) { + return !isSpecialCharPresent(commonName) + && !isHttpProtocolsPresent(commonName) + && !isIpAddressPresent(commonName) + && !isPortNumberPresent(commonName); + } + + private boolean isPortNumberPresent(String stringToCheck) { + return Pattern.compile(PORT_POSTFIX_REGEX).matcher(stringToCheck).find(); + } + + private boolean isIpAddressPresent(String stringToCheck) { + return Pattern.compile(IPV4_ADDRESS_REGEX).matcher(stringToCheck).find(); + } + + private boolean isHttpProtocolsPresent(String stringToCheck) { + return Pattern.compile(HTTP_HTTPS_SCHEME_REGEX).matcher(stringToCheck).find(); + } + +} diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/BasicValidationFunctions.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/csr/CsrEnvsValueValidators.java index e5044c26..31903a98 100644 --- a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/BasicValidationFunctions.java +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/csr/CsrEnvsValueValidators.java @@ -18,40 +18,45 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.certservice.client.configuration.validation; +package org.onap.oom.certservice.client.configuration.validation.csr; import java.util.Arrays; import java.util.Locale; import java.util.regex.Pattern; +import org.apache.commons.validator.routines.DomainValidator; +import org.apache.commons.validator.routines.EmailValidator; +import org.apache.commons.validator.routines.InetAddressValidator; -public class BasicValidationFunctions { +public final class CsrEnvsValueValidators { - public static boolean isPathValid(String path) { - return path.matches("^/|(/[a-zA-Z0-9_-]+)+/?$"); - } + private static final boolean ALLOW_LOCAL_DOMAINS = true; + + private static final String SPECIAL_CHAR_PRESENCE_REGEX = "[~#@*$+%!()?/{}<>\\|_^]"; - public static boolean isAlphaNumeric(String caName) { - return caName.matches("^[a-zA-Z0-9]*$"); + private CsrEnvsValueValidators() { } - public static boolean isSpecialCharPresent(String stringToCheck) { - return Pattern.compile("[~#@*$+%!()?/{}<>\\|_^]").matcher(stringToCheck).find(); + public static boolean isCountryValid(String country) { + return Arrays.asList(Locale.getISOCountries()).contains(country); } - public static boolean isPortNumberPresent(String stringToCheck) { - return Pattern.compile(":[0-9]{1,5}").matcher(stringToCheck).find(); + public static boolean isEmailAddressValid(String address) { + return EmailValidator.getInstance().isValid(address); } - 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(); + public static boolean isIpAddressValid(String address) { + return InetAddressValidator.getInstance().isValid(address); } - public static boolean isHttpProtocolsPresent(String stringToCheck) { - return Pattern.compile("[h][t][t][p][:][/][/]|[h][t][t][p][s][:][/][/]").matcher(stringToCheck).find(); + public static boolean isDomainNameValid(String domain) { + return DomainValidator.getInstance(ALLOW_LOCAL_DOMAINS).isValid(domain); } - public static boolean isCountryValid(String country) { - return Arrays.asList(Locale.getISOCountries()).contains(country); + public static boolean isUriValid(String uri) { + return UriValidator.isValid(uri); } + public static boolean isSpecialCharPresent(String stringToCheck) { + return Pattern.compile(SPECIAL_CHAR_PRESENCE_REGEX).matcher(stringToCheck).find(); + } } diff --git a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/UriValidator.java b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/csr/UriValidator.java index 7800d739..b8073f42 100644 --- a/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/UriValidator.java +++ b/certServiceClient/src/main/java/org/onap/oom/certservice/client/configuration/validation/csr/UriValidator.java @@ -17,16 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - -package org.onap.oom.certservice.client.configuration.validation; +package org.onap.oom.certservice.client.configuration.validation.csr; /** * Compliant with the RFC3986 */ -public final class UriValidator { - - private UriValidator() { - } +final class UriValidator { private static final String SCHEME = "([A-Za-z][A-Za-z0-9+\\-.]*):"; @@ -63,7 +59,11 @@ public final class UriValidator { SCHEME + "(" + AUTHORITY_WITH_PATH + OR + PATH_BEGIN_WITH_SLASH + OR + PATH_WITHOUT_SLASH + OR + "" + ")" + QUERY + FRAGMENT; - public static boolean isValidUri(String uri) { + private UriValidator() { + } + + static boolean isValid(String uri) { return uri.matches(RFC3986_URI_MATCH_PATTERN); } } + 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 ee7d210f..ab9fc921 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,31 +20,35 @@ package org.onap.oom.certservice.client.certification; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.security.KeyPair; import java.util.List; +import org.bouncycastle.asn1.x509.GeneralName; 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; +import org.onap.oom.certservice.client.configuration.model.San; class CsrFactoryTest { CsrConfiguration config = mock(CsrConfiguration.class); - @Test - void createEncodedCsr_shouldSucceedWhenAllFieldsAreSetCorrectly() throws KeyPairGenerationException, CsrGenerationException { + void createEncodedCsr_shouldSucceedWhenAllFieldsAreSetCorrectly() + throws KeyPairGenerationException, CsrGenerationException { KeyPair keyPair = - new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, EncryptionAlgorithmConstants.KEY_SIZE).create(); + new KeyPairFactory(EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM, + EncryptionAlgorithmConstants.KEY_SIZE).create(); + San san1 = new San("onapexample.com", GeneralName.dNSName); + San san2 = new San("onapexample.com.pl", GeneralName.dNSName); when(config.getCommonName()).thenReturn("onap.org"); - when(config.getSans()).thenReturn(List.of("onapexample.com","onapexample.com.pl","onapexample.pl")); + when(config.getSans()).thenReturn(List.of(san1, san2)); 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 071e7551..166b1e60 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,7 +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 org.onap.oom.certservice.client.configuration.validation.client.OutputTypeValidator; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -48,7 +48,7 @@ public class ClientConfigurationFactoryTest { private static final String OUTPUT_TYPE_DEFAULT = "P12"; private EnvsForClient envsForClient = mock(EnvsForClient.class); - private ValidatorsFactory validatorsFactory = new ValidatorsFactory(); + private OutputTypeValidator outputTypeValidator = new OutputTypeValidator(); @Test @@ -61,7 +61,7 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_VALID)); // when - ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient, validatorsFactory).create(); + ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient, outputTypeValidator).create(); System.out.println(configuration.toString()); // then @@ -79,7 +79,7 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); // when - ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient, validatorsFactory).create(); + ClientConfiguration configuration = new ClientConfigurationFactory(envsForClient, outputTypeValidator).create(); // then assertThat(configuration.getCaName()).isEqualTo(CA_NAME_VALID); @@ -95,7 +95,8 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getOutputPath()).thenReturn(Optional.of(OUTPUT_PATH_VALID)); // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, validatorsFactory); + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, + outputTypeValidator); // then assertThatExceptionOfType(ClientConfigurationException.class) @@ -112,7 +113,8 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, validatorsFactory); + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, + outputTypeValidator); // when/then assertThatExceptionOfType(ClientConfigurationException.class) @@ -129,7 +131,8 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getUrlToCertService()).thenReturn(Optional.of(URL_TO_CERT_SERVICE_VALID)); // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, validatorsFactory); + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, + outputTypeValidator); //then assertThatExceptionOfType(ClientConfigurationException.class) @@ -147,7 +150,8 @@ public class ClientConfigurationFactoryTest { when(envsForClient.getOutputType()).thenReturn(Optional.of(OUTPUT_TYPE_INVALID)); // when - ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, validatorsFactory); + ClientConfigurationFactory configurationFactory = new ClientConfigurationFactory(envsForClient, + outputTypeValidator); //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 cdcefe2e..158f0cf2 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 @@ -22,6 +22,7 @@ package org.onap.oom.certservice.client.configuration.factory; import java.util.List; import org.assertj.core.api.Condition; +import org.bouncycastle.asn1.x509.GeneralName; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.onap.oom.certservice.client.configuration.CsrConfigurationEnvs; @@ -30,7 +31,8 @@ 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 org.onap.oom.certservice.client.configuration.model.San; +import org.onap.oom.certservice.client.configuration.validation.csr.CommonNameValidator; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -41,8 +43,9 @@ 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", "test-name-1"); - private static final String SANS_VALID = "test-name,test-name-1"; + private static final String RAW_SAN1 = "ves-collector"; + private static final String RAW_SAN2 = "ves"; + private static final String RAW_SANS_VALID = String.format("%s,%s", RAW_SAN1, RAW_SAN2); private static final String COUNTRY_VALID = "US"; private static final String LOCATION_VALID = "San-Francisco"; private static final String ORGANIZATION_VALID = "Linux-Foundation"; @@ -51,9 +54,11 @@ public class CsrConfigurationFactoryTest { 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 static final String INVALID_SANS = "192.168.1."; private EnvsForCsr envsForCsr = mock(EnvsForCsr.class); - private ValidatorsFactory validatorsFactory = new ValidatorsFactory(); + private CommonNameValidator commonNameValidator = new CommonNameValidator(); + private SanMapper sanMapper = new SanMapper(); private CsrConfigurationFactory testedFactory; private Condition<CsrConfigurationException> expectedExitCodeCondition = new Condition<>("Correct exit code") { @Override @@ -64,20 +69,23 @@ public class CsrConfigurationFactoryTest { @BeforeEach void setUp() { - testedFactory = new CsrConfigurationFactory(envsForCsr, validatorsFactory); + testedFactory = new CsrConfigurationFactory(envsForCsr, commonNameValidator, sanMapper); } @Test void shouldReturnCorrectConfiguration_WhenAllVariablesAreSetAndValid() throws CsrConfigurationException { // given mockEnvsWithAllValidParameters(); + San san1 = new San(RAW_SAN1, GeneralName.dNSName); + San san2 = new San(RAW_SAN2, GeneralName.dNSName); + List<San> sans = List.of(san1, san2); // when CsrConfiguration configuration = testedFactory.create(); // then assertThat(configuration.getCommonName()).isEqualTo(COMMON_NAME_VALID); - assertThat(configuration.getSans()).isEqualTo(SANS_SPLITTED_VALID); + assertThat(configuration.getSans()).isEqualTo(sans); assertThat(configuration.getCountry()).isEqualTo(COUNTRY_VALID); assertThat(configuration.getLocation()).isEqualTo(LOCATION_VALID); assertThat(configuration.getOrganization()).isEqualTo(ORGANIZATION_VALID); @@ -150,6 +158,17 @@ public class CsrConfigurationFactoryTest { .has(expectedExitCodeCondition); } + @Test + void shouldThrowCsrConfigurationExceptionWhenSansInvalid() { + // given + mockEnvsWithInvalidSans(); + // when/then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(testedFactory::create) + .withMessageContaining("SAN :" + INVALID_SANS + " does not match any requirements") + .has(expectedExitCodeCondition); + } + private void mockEnvsWithAllValidParameters() { mockEnvsWithValidRequiredParameters(); mockEnvsWithValidOptionalParameters(); @@ -158,7 +177,7 @@ public class CsrConfigurationFactoryTest { 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)); + when(envsForCsr.getSubjectAlternativesName()).thenReturn(Optional.of(RAW_SANS_VALID)); } private void mockEnvsWithValidRequiredParameters() { @@ -187,4 +206,9 @@ public class CsrConfigurationFactoryTest { mockEnvsWithAllValidParameters(); when(envsForCsr.getState()).thenReturn(Optional.empty()); } + + private void mockEnvsWithInvalidSans() { + mockEnvsWithAllValidParameters(); + when(envsForCsr.getSubjectAlternativesName()).thenReturn(Optional.of(INVALID_SANS)); + } } diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SanMapperTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SanMapperTest.java new file mode 100644 index 00000000..9ec4c6e7 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SanMapperTest.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 static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import java.util.function.Function; +import org.bouncycastle.asn1.x509.GeneralName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.onap.oom.certservice.client.configuration.exception.CsrConfigurationException; +import org.onap.oom.certservice.client.configuration.model.San; + +class SanMapperTest { + + private Function<String, San> sanMapper = new SanMapper(); + + @ParameterizedTest + @ValueSource(strings = {"192.178.2.3", "10.183.34.201", "ff:ff:ff:ff:ff:ff:ff:ff", "ff:ff::"}) + void shouldCorrectlyMapIpAddress(String san) { + // when + San result = sanMapper.apply(san); + // then + assertThat(result.getValue()).isEqualTo(san); + assertThat(result.getType()).isEqualTo(GeneralName.iPAddress); + } + + @ParameterizedTest + @ValueSource(strings = {"foo@bar.com", "sample@example.com", "onap@domain.pl", "alex.supertramp@onap.com", + "al.super^tramp@onap.org"}) + void shouldCorrectlyMapEmailAddress(String san) { + // when + San result = sanMapper.apply(san); + // then + assertThat(result.getValue()).isEqualTo(san); + assertThat(result.getType()).isEqualTo(GeneralName.rfc822Name); + } + + @ParameterizedTest + @ValueSource(strings = {"sample.com", "Sample.com", "onap.org", "SRI-NIC.ARPA", "ves-collector", "sample"}) + void shouldCorrectlyMapDomain(String san) { + // when + San result = sanMapper.apply(san); + // then + assertThat(result.getValue()).isEqualTo(san); + assertThat(result.getType()).isEqualTo(GeneralName.dNSName); + } + + @ParameterizedTest + @ValueSource(strings = {" ", "", "192.168.0.", "10.183.34.201:8080", "incoreectdomaim@onap.ux", "<sample@example.com>", + "onap@domain"}) + void shouldThrowExceptionOnIncorrectString(String san) { + // when, then + assertThatExceptionOfType(CsrConfigurationException.class) + .isThrownBy(() -> sanMapper.apply(san)) + .withMessage("SAN :" + san + " does not match any requirements"); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/BasicValidationFunctionsTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/client/ClientEnvsValueValidatorsTest.java index d552ba55..9ed46c1a 100644 --- a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/BasicValidationFunctionsTest.java +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/client/ClientEnvsValueValidatorsTest.java @@ -18,17 +18,27 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.certservice.client.configuration.validation; +package org.onap.oom.certservice.client.configuration.validation.client; import static org.assertj.core.api.Assertions.assertThat; -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; +import static org.onap.oom.certservice.client.configuration.validation.client.ClientEnvsValueValidators.isAlphaNumeric; +import static org.onap.oom.certservice.client.configuration.validation.client.ClientEnvsValueValidators.isPathValid; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -class BasicValidationFunctionsTest { +class ClientEnvsValueValidatorsTest { + @ParameterizedTest + @ValueSource(strings = {"caname", "caname1", "123caName", "ca1name"}) + void shouldAcceptValidAlphanumeric(String caName) { + assertThat(isAlphaNumeric(caName)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"44caname$", "#caname1", "1c_aname", "ca1-name"}) + void shouldRejectInvalidAlphanumeric(String caName) { + assertThat(isAlphaNumeric(caName)).isFalse(); + } @ParameterizedTest @ValueSource(strings = {"/var/log", "/", "/var/log/", "/second_var", "/second-var"}) @@ -42,28 +52,4 @@ class BasicValidationFunctionsTest { 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(isCountryValid(countryCode)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"", "QQ", "AFG", "D", "&*", "!", "ONAP", "p", "pl", "us", "afg"}) - void shouldRejectInvalidCountryCode(String countryCode) { - assertThat(isCountryValid(countryCode)).isFalse(); - } - - @ParameterizedTest - @ValueSource(strings = {"caname", "caname1", "123caName", "ca1name"}) - void shouldAcceptValidAlphanumeric(String caName) { - assertThat(isAlphaNumeric(caName)).isTrue(); - } - - @ParameterizedTest - @ValueSource(strings = {"44caname$", "#caname1", "1c_aname", "ca1-name"}) - void shouldRejectInvalidAlphanumeric(String caName) { - assertThat(isAlphaNumeric(caName)).isFalse(); - } - } diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/client/OutputTypeValidatorTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/client/OutputTypeValidatorTest.java new file mode 100644 index 00000000..1b32c017 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/client/OutputTypeValidatorTest.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.configuration.validation.client; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class OutputTypeValidatorTest { + + OutputTypeValidator cut = new OutputTypeValidator(); + + @ParameterizedTest + @ValueSource(strings = {"JKS", "P12", "PEM"}) + void shouldAcceptValidOutputType(String outputType) { + assertThat(cut.test(outputType)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"jks", "p12", "pem", "", "pass", "!@$#pp"}) + void shouldRejectInvalidOutputType(String outputType) { + assertThat(cut.test(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/csr/CommonNameValidatorTest.java index 3c14d30f..deb02cf3 100644 --- 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/csr/CommonNameValidatorTest.java @@ -18,39 +18,27 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.certservice.client.configuration.validation; +package org.onap.oom.certservice.client.configuration.validation.csr; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -class ValidatorsFactoryTest { +class CommonNameValidatorTest { - 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(); - } + CommonNameValidator cut = new CommonNameValidator(); @ParameterizedTest @ValueSource(strings = {"example.com", "www.example.com"}) void shouldAcceptValidCommonName(String commonName) { - assertThat(cut.commonNameValidator().test(commonName)).isTrue(); + assertThat(cut.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(); + assertThat(cut.test(commonName)).isFalse(); } } diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/csr/CsrEnvsValueValidatorsTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/csr/CsrEnvsValueValidatorsTest.java new file mode 100644 index 00000000..d1d075a4 --- /dev/null +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/csr/CsrEnvsValueValidatorsTest.java @@ -0,0 +1,122 @@ +/* + * ============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.csr; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.oom.certservice.client.configuration.validation.client.ClientEnvsValueValidators.isPathValid; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isCountryValid; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isDomainNameValid; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isEmailAddressValid; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isIpAddressValid; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isSpecialCharPresent; +import static org.onap.oom.certservice.client.configuration.validation.csr.CsrEnvsValueValidators.isUriValid; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CsrEnvsValueValidatorsTest { + + @ParameterizedTest + @ValueSource(strings = {"/var/log", "/", "/var/log/", "/second_var", "/second-var"}) + void shouldAcceptValidPath(String path) { + assertThat(isPathValid(path)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"/var/log?", "", "var_", "var", "//", "/var//log"}) + void shouldRejectInvalidPath(String path) { + 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(isCountryValid(countryCode)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"", "QQ", "AFG", "D", "&*", "!", "ONAP", "p", "pl", "us", "afg"}) + void shouldRejectInvalidCountryCode(String countryCode) { + assertThat(isCountryValid(countryCode)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"sample@example.com", "onap@domain.pl", "alex.supertramp@onap.com", + "al.super^tramp@onap.org"}) + void shouldAcceptValidEmailAddr(String emailAddr) { + assertThat(isEmailAddressValid(emailAddr)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"<sample@example.com>", "onap@domain", "(mailto)user@onap.com", "mailto:axe@axe.de", + "incoreectdomaim@onap.ux"}) + void shouldRejectInvalidEmailAddr(String address) { + assertThat(isEmailAddressValid(address)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"192.168.0.1", "10.183.34.201", "ff:ff:ff:ff::", "ff:ff:ff:ff:ff:ff:ff:ff"}) + void shouldAcceptValidIpAddress(String address) { + assertThat(isIpAddressValid(address)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"192.168.0.", "ff:ff:ee:a1:", "fg:ff:ff:ff::", "http://10.183.34.201", + "10.183.34.201:8080"}) + void shouldRejectInvalidIpAddress(String address) { + assertThat(isIpAddressValid(address)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"sample.com", "Sample.com", "onap.org", "SRI-NIC.ARPA", "ves-collector", "sample"}) + void shouldAcceptValidDomainName(String domain) { + assertThat(isDomainNameValid(domain)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {" ", "", "sample@onap.org", "192.168.0.1", "http://sample.com"}) + void shouldRejectInvalidDomainNames(String domain) { + assertThat(isDomainNameValid(domain)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"http://sample.com/path", "ftp://sample.com/path/file.txt", "https://ves.pl"}) + void shouldBeTrueForValidUris(String text) { + assertThat(isUriValid(text)).isTrue(); + } + @ParameterizedTest + @ValueSource(strings = {"3http://sample.com", "192.168.0.1", "www.example.com"}) + void shouldBeFalseForInvalidUris(String text) { + assertThat(isUriValid(text)).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"/text~", "/text#", "/text@", "/text*","/text$", "/text+", "/text%", "/text!", "/text(", + "/text)", "/text?", "/text|", "/text_", "/text^"}) + void shouldBeTrueForStringsWithSpecialChars(String text) { + assertThat(isSpecialCharPresent(text)).isTrue(); + } + @ParameterizedTest + @ValueSource(strings = {"text", ""}) + void shouldBeFalseForStringsWithoutSpecialChars(String text) { + assertThat(isSpecialCharPresent(text)).isFalse(); + } +} diff --git a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/UriValidatorTest.java b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/csr/UriValidatorTest.java index d7024d4e..addc4603 100644 --- a/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/UriValidatorTest.java +++ b/certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/validation/csr/UriValidatorTest.java @@ -18,9 +18,10 @@ * ============LICENSE_END========================================================= */ -package org.onap.oom.certservice.client.configuration.validation; +package org.onap.oom.certservice.client.configuration.validation.csr; import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.oom.certservice.client.configuration.validation.csr.UriValidator.isValid; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -34,19 +35,19 @@ class UriValidatorTest { @ParameterizedTest @ValueSource(strings = {"http:/", "http:", "http://", "h4ttp://"}) void shouldTrueForValidScheme(String uri) { - assertThat(UriValidator.isValidUri(uri)).isTrue(); + assertThat(isValid(uri)).isTrue(); } @ParameterizedTest @ValueSource(strings = {"example.com", "www.example.com", "0.0.0.0", "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]"}) void shouldFalseForUriWithoutScheme(String uri) { - assertThat(UriValidator.isValidUri(uri)).isFalse(); + assertThat(isValid(uri)).isFalse(); } @ParameterizedTest @ValueSource(strings = {"*http://", "_http://", "?http://", "4http://"}) void shouldFalseForUriWithInvalidScheme(String uri) { - assertThat(UriValidator.isValidUri(uri)).isFalse(); + assertThat(isValid(uri)).isFalse(); } /** @@ -64,7 +65,7 @@ class UriValidatorTest { "http://user:password:test@example.com", "http://user-info:password@example.com"}) void shouldTrueForValidUserInAuthority(String uri) { - assertThat(UriValidator.isValidUri(uri)).isTrue(); + assertThat(isValid(uri)).isTrue(); } @ParameterizedTest @@ -72,7 +73,7 @@ class UriValidatorTest { "http://user:password", "http://user:password:test:"}) void shouldFalseForMissingHostInAuthority(String uri) { - assertThat(UriValidator.isValidUri(uri)).isFalse(); + assertThat(isValid(uri)).isFalse(); } @ParameterizedTest @@ -82,7 +83,7 @@ class UriValidatorTest { "http://8.8.8.8/", "http://8.8.8.8/test"}) void shouldTrueForUriContainsIP(String uri) { - assertThat(UriValidator.isValidUri(uri)).isTrue(); + assertThat(isValid(uri)).isTrue(); } @ParameterizedTest @@ -92,7 +93,7 @@ class UriValidatorTest { "http://8.8.8.8:8080/test", "https://8.8.8.8:443/"}) void shouldTrueForUriContainsIPAndPort(String uri) { - assertThat(UriValidator.isValidUri(uri)).isTrue(); + assertThat(isValid(uri)).isTrue(); } @ParameterizedTest @@ -101,7 +102,7 @@ class UriValidatorTest { "http:/file", "http:/ptah/to/file"}) void shouldTrueForMissingAuthority(String uri) { - assertThat(UriValidator.isValidUri(uri)).isTrue(); + assertThat(isValid(uri)).isTrue(); } /** @@ -114,7 +115,7 @@ class UriValidatorTest { "http://example.com/path", "http://example.com/",}) void shouldTrueForPathWithAuthority(String uri) { - assertThat(UriValidator.isValidUri(uri)).isTrue(); + assertThat(isValid(uri)).isTrue(); } @ParameterizedTest @@ -123,7 +124,7 @@ class UriValidatorTest { "http:/path", "http:/",}) void shouldTrueForPathWithoutAuthority(String uri) { - assertThat(UriValidator.isValidUri(uri)).isTrue(); + assertThat(isValid(uri)).isTrue(); } @@ -134,7 +135,7 @@ class UriValidatorTest { "http://example.com?test=tes1&#", "http://example.com#onap"}) void shouldTrueForUriWithQueryAndFragmentInPath(String uri) { - assertThat(UriValidator.isValidUri(uri)).isTrue(); + assertThat(isValid(uri)).isTrue(); } @ParameterizedTest @@ -143,7 +144,7 @@ class UriValidatorTest { "http://example.com?##", "http://www.example.com/file%GF.html"}) void shouldFalseForUriWithWrongQueryOrWrongFragmentInPath(String uri) { - assertThat(UriValidator.isValidUri(uri)).isFalse(); + assertThat(isValid(uri)).isFalse(); } @ParameterizedTest @@ -157,6 +158,7 @@ class UriValidatorTest { "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"}) void shouldTrueForRFC3986Examples(String uri) { - assertThat(UriValidator.isValidUri(uri)).isTrue(); + assertThat(isValid(uri)).isTrue(); } + } |