diff options
44 files changed, 327 insertions, 602 deletions
diff --git a/certService/pom.xml b/certService/pom.xml index c61501b4..87888f12 100644 --- a/certService/pom.xml +++ b/certService/pom.xml @@ -168,8 +168,6 @@ <dockerFileDir>${project.basedir}</dockerFileDir> <tags> <tag>${project.version}-${maven.build.timestamp}Z</tag> - <tag>${project.version}</tag> - <tag>${docker-image.latest}</tag> </tags> </build> </image> diff --git a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/CertificateFactoryProvider.java b/certService/src/main/java/org/onap/aaf/certservice/certification/CertificateFactoryProvider.java index 79f59363..b633f905 100644 --- a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/CertificateFactoryProvider.java +++ b/certService/src/main/java/org/onap/aaf/certservice/certification/CertificateFactoryProvider.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.aaf.certservice.certification.adapter; +package org.onap.aaf.certservice.certification; import java.io.InputStream; import java.security.NoSuchProviderException; diff --git a/certService/src/main/java/org/onap/aaf/certservice/certification/CertificationProvider.java b/certService/src/main/java/org/onap/aaf/certservice/certification/CertificationProvider.java index fa2d88ab..4435aa75 100644 --- a/certService/src/main/java/org/onap/aaf/certservice/certification/CertificationProvider.java +++ b/certService/src/main/java/org/onap/aaf/certservice/certification/CertificationProvider.java @@ -20,28 +20,58 @@ package org.onap.aaf.certservice.certification; -import org.onap.aaf.certservice.certification.adapter.Cmpv2ClientAdapter; +import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator; +import org.bouncycastle.util.io.pem.PemObjectGenerator; +import org.bouncycastle.util.io.pem.PemWriter; import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server; -import org.onap.aaf.certservice.certification.exception.Cmpv2ClientAdapterException; import org.onap.aaf.certservice.certification.model.CertificationModel; import org.onap.aaf.certservice.certification.model.CsrModel; +import org.onap.aaf.certservice.cmpv2client.api.CmpClient; import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.io.StringWriter; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.stream.Collectors; + @Service public class CertificationProvider { - private final Cmpv2ClientAdapter cmpv2ClientAdapter; + private static final Logger LOGGER = LoggerFactory.getLogger(CertificationProvider.class); + + private final CmpClient cmpClient; @Autowired - public CertificationProvider(Cmpv2ClientAdapter cmpv2ClientAdapter) { - this.cmpv2ClientAdapter = cmpv2ClientAdapter; + public CertificationProvider(CmpClient cmpClient) { + this.cmpClient = cmpClient; + } + + public CertificationModel signCsr(CsrModel csrModel, Cmpv2Server server) + throws CmpClientException { + List<List<X509Certificate>> certificates = cmpClient.createCertificate(csrModel, server); + return new CertificationModel(convertFromX509CertificateListToPemList(certificates.get(0)), + convertFromX509CertificateListToPemList(certificates.get(1))); + } + + private static List<String> convertFromX509CertificateListToPemList(List<X509Certificate> certificates) { + return certificates.stream().map(CertificationProvider::convertFromX509CertificateToPem).filter(cert -> !cert.isEmpty()) + .collect(Collectors.toList()); } - CertificationModel signCsr(CsrModel csrModel, Cmpv2Server server) - throws CmpClientException, Cmpv2ClientAdapterException { - return cmpv2ClientAdapter.callCmpClient(csrModel, server); + private static String convertFromX509CertificateToPem(X509Certificate certificate) { + StringWriter sw = new StringWriter(); + try (PemWriter pw = new PemWriter(sw)) { + PemObjectGenerator gen = new JcaMiscPEMGenerator(certificate); + pw.writeObject(gen); + } catch (IOException e) { + LOGGER.error("Exception occurred during convert of X509 certificate", e); + } + return sw.toString(); } } diff --git a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/RsaContentSignerBuilder.java b/certService/src/main/java/org/onap/aaf/certservice/certification/RsaContentSignerBuilder.java index bda89235..12f00f9c 100644 --- a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/RsaContentSignerBuilder.java +++ b/certService/src/main/java/org/onap/aaf/certservice/certification/RsaContentSignerBuilder.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.aaf.certservice.certification.adapter; +package org.onap.aaf.certservice.certification; import java.io.IOException; import java.security.PrivateKey; diff --git a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/X509CertificateBuilder.java b/certService/src/main/java/org/onap/aaf/certservice/certification/X509CertificateBuilder.java index f96cec8e..70591759 100644 --- a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/X509CertificateBuilder.java +++ b/certService/src/main/java/org/onap/aaf/certservice/certification/X509CertificateBuilder.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.aaf.certservice.certification.adapter; +package org.onap.aaf.certservice.certification; import java.io.IOException; import java.math.BigInteger; @@ -38,7 +38,7 @@ public class X509CertificateBuilder { private static final int SECURE_NEXT_BYTES = 16; private static final int VALID_PERIOD_IN_DAYS = 365; - X509v3CertificateBuilder build(PKCS10CertificationRequest csr) throws IOException { + public X509v3CertificateBuilder build(PKCS10CertificationRequest csr) throws IOException { return new X509v3CertificateBuilder(csr.getSubject(), createSerial(), Date.from(LocalDateTime.now().toInstant(ZoneOffset.UTC)), Date.from(LocalDateTime.now().plusDays(VALID_PERIOD_IN_DAYS).toInstant(ZoneOffset.UTC)), diff --git a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapter.java b/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapter.java deleted file mode 100644 index 2477c421..00000000 --- a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapter.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Cert Service - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.certification.adapter; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.StringWriter; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.List; -import java.util.stream.Collectors; - -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.X509v3CertificateBuilder; -import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.bouncycastle.util.io.pem.PemObjectGenerator; -import org.bouncycastle.util.io.pem.PemWriter; -import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server; -import org.onap.aaf.certservice.certification.exception.Cmpv2ClientAdapterException; -import org.onap.aaf.certservice.certification.model.CertificationModel; -import org.onap.aaf.certservice.certification.model.CsrModel; -import org.onap.aaf.certservice.cmpv2client.api.CmpClient; -import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class Cmpv2ClientAdapter { - - private static final Logger LOGGER = LoggerFactory.getLogger(Cmpv2ClientAdapter.class); - - private final CmpClient cmpClient; - private final RsaContentSignerBuilder rsaContentSignerBuilder; - private final X509CertificateBuilder x509CertificateBuilder; - private final CertificateFactoryProvider certificateFactoryProvider; - - @Autowired - public Cmpv2ClientAdapter(CmpClient cmpClient, RsaContentSignerBuilder rsaContentSignerBuilder, - X509CertificateBuilder x509CertificateBuilder, - CertificateFactoryProvider certificateFactoryProvider) { - this.cmpClient = cmpClient; - this.rsaContentSignerBuilder = rsaContentSignerBuilder; - this.x509CertificateBuilder = x509CertificateBuilder; - this.certificateFactoryProvider = certificateFactoryProvider; - } - - /** - * Uses CmpClient to call to Cmp Server and gather certificates data - * - * @param csrModel Certificate Signing Request from Service external API - * @param server Cmp Server configuration from cmpServers.json - * @return container for returned certificates - * @throws CmpClientException Exceptions which comes from Cmp Client - * @throws Cmpv2ClientAdapterException Exceptions which comes from Adapter itself - */ - public CertificationModel callCmpClient(CsrModel csrModel, Cmpv2Server server) - throws CmpClientException, Cmpv2ClientAdapterException { - List<List<X509Certificate>> certificates = cmpClient.createCertificate(server.getCaName(), - server.getCaMode().getProfile(), csrModel, server, - convertCsrToX509Certificate(csrModel.getCsr(), csrModel.getPrivateKey())); - return new CertificationModel(convertFromX509CertificateListToPemList(certificates.get(0)), - convertFromX509CertificateListToPemList(certificates.get(1))); - } - - private String convertFromX509CertificateToPem(X509Certificate certificate) { - StringWriter sw = new StringWriter(); - try (PemWriter pw = new PemWriter(sw)) { - PemObjectGenerator gen = new JcaMiscPEMGenerator(certificate); - pw.writeObject(gen); - } catch (IOException e) { - LOGGER.error("Exception occurred during convert of X509 certificate", e); - } - return sw.toString(); - } - - private X509Certificate convertCsrToX509Certificate(PKCS10CertificationRequest csr, PrivateKey privateKey) - throws Cmpv2ClientAdapterException { - try { - X509v3CertificateBuilder certificateGenerator = x509CertificateBuilder.build(csr); - ContentSigner signer = rsaContentSignerBuilder.build(csr, privateKey); - X509CertificateHolder holder = certificateGenerator.build(signer); - return certificateFactoryProvider - .generateCertificate(new ByteArrayInputStream(holder.toASN1Structure().getEncoded())); - } catch (IOException | CertificateException | OperatorCreationException | NoSuchProviderException e) { - throw new Cmpv2ClientAdapterException(e); - } - } - - private List<String> convertFromX509CertificateListToPemList(List<X509Certificate> certificates) { - return certificates.stream().map(this::convertFromX509CertificateToPem).filter(cert -> !cert.isEmpty()) - .collect(Collectors.toList()); - } - -} diff --git a/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/api/CmpClient.java b/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/api/CmpClient.java index 7de3b712..6ff1bf68 100644 --- a/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/api/CmpClient.java +++ b/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/api/CmpClient.java @@ -41,13 +41,8 @@ public interface CmpClient { * IAK/RV, Verification of the signature (proof-of-possession) on the request is performed and an * Exception thrown if verification fails or issue encountered in fetching certificate from CA. * - * @param caName Information about the External Root Certificate Authority (CA) performing the - * event CA Name. Could be {@code null}. - * @param profile Profile on CA server Client/RA Mode configuration on Server. Could be {@code - * null}. * @param csrModel Certificate Signing Request model. Must not be {@code null}. * @param server CMPv2 Server. Must not be {@code null}. - * @param csr Certificate Signing Request {.cer} file. Must not be {@code null}. * @param notBefore An optional validity to set in the created certificate, Certificate not valid * before this date. * @param notAfter An optional validity to set in the created certificate, Certificate not valid @@ -56,11 +51,8 @@ public interface CmpClient { * @throws CmpClientException if client error occurs. */ List<List<X509Certificate>> createCertificate( - String caName, - String profile, CsrModel csrModel, Cmpv2Server server, - X509Certificate csr, Date notBefore, Date notAfter) throws CmpClientException; @@ -71,21 +63,13 @@ public interface CmpClient { * IAK/RV, Verification of the signature (proof-of-possession) on the request is performed and an * Exception thrown if verification fails or issue encountered in fetching certificate from CA. * - * @param caName Information about the External Root Certificate Authority (CA) performing the - * event CA Name. Could be {@code null}. - * @param profile Profile on CA server Client/RA Mode configuration on Server. Could be {@code - * null}. * @param csrModel Certificate Signing Request Model. Must not be {@code null}. * @param server CMPv2 server. Must not be {@code null}. - * @param csr Certificate Signing Request {.cer} file. Must not be {@code null}. * @return {@link X509Certificate} The newly created Certificate. * @throws CmpClientException if client error occurs. */ List<List<X509Certificate>> createCertificate( - String caName, - String profile, CsrModel csrModel, - Cmpv2Server server, - X509Certificate csr) + Cmpv2Server server) throws CmpClientException; } diff --git a/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpClientImpl.java b/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpClientImpl.java index 79656e91..28731f29 100644 --- a/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpClientImpl.java +++ b/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CmpClientImpl.java @@ -48,6 +48,7 @@ import org.bouncycastle.asn1.cmp.PKIBody; import org.bouncycastle.asn1.cmp.PKIHeader; import org.bouncycastle.asn1.cmp.PKIMessage; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.onap.aaf.certservice.certification.configuration.model.CaMode; import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server; import org.onap.aaf.certservice.certification.model.CsrModel; import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException; @@ -64,8 +65,8 @@ public class CmpClientImpl implements CmpClient { private static final Logger LOG = LoggerFactory.getLogger(CmpClientImpl.class); private final CloseableHttpClient httpClient; - private static final String DEFAULT_PROFILE = "RA"; private static final String DEFAULT_CA_NAME = "Certification Authority"; + private static final String DEFAULT_PROFILE = CaMode.RA.getProfile(); public CmpClientImpl(CloseableHttpClient httpClient) { this.httpClient = httpClient; @@ -73,16 +74,13 @@ public class CmpClientImpl implements CmpClient { @Override public List<List<X509Certificate>> createCertificate( - String caName, - String profile, CsrModel csrModel, Cmpv2Server server, - X509Certificate cert, Date notBefore, Date notAfter) throws CmpClientException { - validate(csrModel, server, cert, caName, profile, httpClient, notBefore, notAfter); + validate(csrModel, server, httpClient, notBefore, notAfter); KeyPair keyPair = new KeyPair(csrModel.getPublicKey(), csrModel.getPrivateKey()); final CreateCertRequest certRequest = @@ -99,14 +97,13 @@ public class CmpClientImpl implements CmpClient { final PKIMessage pkiMessage = certRequest.generateCertReq(); Cmpv2HttpClient cmpv2HttpClient = new Cmpv2HttpClient(httpClient); - return retrieveCertificates(caName, csrModel, server, pkiMessage, cmpv2HttpClient); + return retrieveCertificates(csrModel, server, pkiMessage, cmpv2HttpClient); } @Override - public List<List<X509Certificate>> createCertificate( - String caName, String profile, CsrModel csrModel, Cmpv2Server server, X509Certificate csr) + public List<List<X509Certificate>> createCertificate(CsrModel csrModel, Cmpv2Server server) throws CmpClientException { - return createCertificate(caName, profile, csrModel, server, csr, null, null); + return createCertificate(csrModel, server, null, null); } private void checkCmpResponse( @@ -197,25 +194,19 @@ public class CmpClientImpl implements CmpClient { * * @param csrModel Certificate Signing Request model. Must not be {@code null}. * @param server CMPv2 Server. Must not be {@code null}. - * @param cert Certificate object needed to validate response from CA server. - * @param incomingCaName Date specifying certificate is not valid before this date. - * @param incomingProfile Date specifying certificate is not valid after this date. * @throws IllegalArgumentException if Before Date is set after the After Date. */ private static void validate( final CsrModel csrModel, final Cmpv2Server server, - final X509Certificate cert, - final String incomingCaName, - final String incomingProfile, final CloseableHttpClient httpClient, final Date notBefore, final Date notAfter) { - String caName = CmpUtil.isNullOrEmpty(incomingCaName) ? incomingCaName : DEFAULT_CA_NAME; - String caProfile = CmpUtil.isNullOrEmpty(incomingProfile) ? incomingProfile : DEFAULT_PROFILE; + String caName = CmpUtil.isNullOrEmpty(server.getCaName()) ? server.getCaName() : DEFAULT_CA_NAME; + String profile = server.getCaMode() != null ? server.getCaMode().getProfile() : DEFAULT_PROFILE; LOG.info( - "Validate before creating Certificate Request for CA :{} in Mode {} ", caName, caProfile); + "Validate before creating Certificate Request for CA :{} in Mode {} ", caName, profile); CmpUtil.notNull(csrModel, "CsrModel Instance"); CmpUtil.notNull(csrModel.getSubjectData(), "Subject DN"); @@ -224,7 +215,6 @@ public class CmpClientImpl implements CmpClient { CmpUtil.notNull(server.getIssuerDN(), "Issuer DN"); CmpUtil.notNull(server.getUrl(), "External CA URL"); CmpUtil.notNull(server.getAuthentication().getIak(), "IAK/RV Password"); - CmpUtil.notNull(cert, "Certificate Signing Request (CSR)"); CmpUtil.notNull(httpClient, "Closeable Http Client"); if (notBefore != null && notAfter != null && notBefore.compareTo(notAfter) > 0) { @@ -233,9 +223,9 @@ public class CmpClientImpl implements CmpClient { } private List<List<X509Certificate>> retrieveCertificates( - String caName, CsrModel csrModel, Cmpv2Server server, PKIMessage pkiMessage, Cmpv2HttpClient cmpv2HttpClient) + CsrModel csrModel, Cmpv2Server server, PKIMessage pkiMessage, Cmpv2HttpClient cmpv2HttpClient) throws CmpClientException { - final byte[] respBytes = cmpv2HttpClient.postRequest(pkiMessage, server.getUrl(), caName); + final byte[] respBytes = cmpv2HttpClient.postRequest(pkiMessage, server.getUrl(), server.getCaName()); try { final PKIMessage respPkiMessage = PKIMessage.getInstance(respBytes); LOG.info("Received response from Server"); diff --git a/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CreateCertRequest.java b/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CreateCertRequest.java index 687c47d1..74380d84 100644 --- a/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CreateCertRequest.java +++ b/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/impl/CreateCertRequest.java @@ -28,12 +28,9 @@ import java.security.KeyPair; import java.util.Date; import java.util.List; -import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.cmp.PKIBody; import org.bouncycastle.asn1.cmp.PKIHeader; import org.bouncycastle.asn1.cmp.PKIMessage; -import org.bouncycastle.asn1.crmf.AttributeTypeAndValue; -import org.bouncycastle.asn1.crmf.CRMFObjectIdentifiers; import org.bouncycastle.asn1.crmf.CertReqMessages; import org.bouncycastle.asn1.crmf.CertReqMsg; import org.bouncycastle.asn1.crmf.CertRequest; @@ -114,12 +111,7 @@ class CreateCertRequest { final ProofOfPossession proofOfPossession = CmpMessageHelper.generateProofOfPossession(certRequest, subjectKeyPair); - final AttributeTypeAndValue[] attrTypeVal = { - new AttributeTypeAndValue( - CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String(initAuthPassword)) - }; - - final CertReqMsg certReqMsg = new CertReqMsg(certRequest, proofOfPossession, attrTypeVal); + final CertReqMsg certReqMsg = new CertReqMsg(certRequest, proofOfPossession, null); final CertReqMessages certReqMessages = new CertReqMessages(certReqMsg); final PKIHeader pkiHeader = diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationProviderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationProviderTest.java index f75bd608..cf3c7233 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationProviderTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/CertificationProviderTest.java @@ -20,65 +20,89 @@ package org.onap.aaf.certservice.certification; +import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.onap.aaf.certservice.certification.adapter.Cmpv2ClientAdapter; import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server; -import org.onap.aaf.certservice.certification.exception.Cmpv2ClientAdapterException; -import org.onap.aaf.certservice.certification.exception.DecryptionException; import org.onap.aaf.certservice.certification.model.CertificationModel; import org.onap.aaf.certservice.certification.model.CsrModel; +import org.onap.aaf.certservice.cmpv2client.api.CmpClient; import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.NoSuchProviderException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class CertificationProviderTest { - private CertificationProvider certificationProvider; - @Mock - private Cmpv2ClientAdapter cmpv2ClientAdapter; + private CsrModel csrModel; + @Mock + private Cmpv2Server server; + @Mock + private CsrModel testCsrModel; + @Mock + private Cmpv2Server testServer; + @Mock + private CmpClient cmpClient; + + private CertificationProvider certificationProvider; @BeforeEach - void setUp() { - certificationProvider = new CertificationProvider(cmpv2ClientAdapter); + public void init() { + certificationProvider = new CertificationProvider(cmpClient); } @Test - void certificationProviderShouldReturnCertificationModelWhenProvidedProperCsrModelAndCmpv2Server() - throws CmpClientException, Cmpv2ClientAdapterException { - // Given - CsrModel testCsrModel = mock(CsrModel.class); - Cmpv2Server testServer = mock(Cmpv2Server.class); - CertificationModel expectedCertificationModel = mock(CertificationModel.class); + void shouldConvertToCertificationModel() + throws CertificateException, NoSuchProviderException, IOException, CmpClientException { + // When when( - cmpv2ClientAdapter.callCmpClient(eq(testCsrModel), eq(testServer)) - ).thenReturn(expectedCertificationModel); + cmpClient.createCertificate(any(CsrModel.class), any(Cmpv2Server.class)) + ).thenReturn(createCorrectClientResponse()); - // When - CertificationModel receivedCertificationModel = certificationProvider.signCsr(testCsrModel, testServer); + CertificationModel certificationModel = certificationProvider.signCsr(csrModel, server); // Then - assertThat(receivedCertificationModel).isEqualTo(expectedCertificationModel); + InputStream certificate = getClass().getClassLoader().getResourceAsStream("certificateModelChain.first"); + InputStream trustedCertificate = + getClass().getClassLoader().getResourceAsStream("trustedCertificatesModel.first"); + String certificateModel = removeLineEndings(certificationModel.getCertificateChain().get(0)); + String expectedCertificate = + removeLineEndings(IOUtils.toString(Objects.requireNonNull(certificate), StandardCharsets.UTF_8)); + String trustedCertificateModel = removeLineEndings(certificationModel.getTrustedCertificates().get(0)); + String expectedTrustedCertificate = + removeLineEndings(IOUtils.toString(Objects.requireNonNull(trustedCertificate), StandardCharsets.UTF_8)); + + assertThat(certificateModel).isEqualTo(expectedCertificate); + assertThat(trustedCertificateModel).isEqualTo(expectedTrustedCertificate); } + @Test void certificationProviderThrowCmpClientWhenCallingClientFails() - throws CmpClientException, Cmpv2ClientAdapterException { + throws CmpClientException { // Given - CsrModel testCsrModel = mock(CsrModel.class); - Cmpv2Server testServer = mock(Cmpv2Server.class); String expectedErrorMessage = "connecting to CMP client failed"; + when( - cmpv2ClientAdapter.callCmpClient(eq(testCsrModel), eq(testServer)) + cmpClient.createCertificate(any(CsrModel.class), any(Cmpv2Server.class)) ).thenThrow(new CmpClientException(expectedErrorMessage)); // When @@ -91,4 +115,18 @@ class CertificationProviderTest { assertThat(exception.getMessage()).isEqualTo(expectedErrorMessage); } + private List<List<X509Certificate>> createCorrectClientResponse() + throws CertificateException, NoSuchProviderException { + InputStream certificateChain = getClass().getClassLoader().getResourceAsStream("certificateChain.first"); + InputStream trustedCertificate = getClass().getClassLoader().getResourceAsStream("trustedCertificates.first"); + X509Certificate x509Certificate = new CertificateFactoryProvider().generateCertificate(certificateChain); + X509Certificate x509TrustedCertificate = + new CertificateFactoryProvider().generateCertificate(trustedCertificate); + return Arrays.asList(Collections.singletonList(x509Certificate), + Collections.singletonList(x509TrustedCertificate)); + } + + private String removeLineEndings(String string) { + return string.replace("\n", "").replace("\r", ""); + } } diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/RsaContentSignerBuilderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/RsaContentSignerBuilderTest.java index 44669216..0083968d 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/RsaContentSignerBuilderTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/RsaContentSignerBuilderTest.java @@ -18,13 +18,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.aaf.certservice.certification.adapter; +package org.onap.aaf.certservice.certification; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.onap.aaf.certservice.certification.RsaContentSignerBuilder; import org.onap.aaf.certservice.certification.exception.DecryptionException; import org.onap.aaf.certservice.certification.model.CsrModel; diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/X509CertificateBuilderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/X509CertificateBuilderTest.java index d53c6c72..067f2f5f 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/X509CertificateBuilderTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/certification/X509CertificateBuilderTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.aaf.certservice.certification.adapter; +package org.onap.aaf.certservice.certification; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v3CertificateBuilder; @@ -38,12 +38,12 @@ import static org.onap.aaf.certservice.certification.TestUtils.createCsrModel; public class X509CertificateBuilderTest { - private X509CertificateBuilder certificateBuilde; + private X509CertificateBuilder certificateBuilder; @BeforeEach void setUp() { - certificateBuilde = new X509CertificateBuilder(); + certificateBuilder = new X509CertificateBuilder(); } @Test @@ -57,7 +57,7 @@ public class X509CertificateBuilderTest { ContentSigner createdContentSigner = rsaContentSignerBuilder.build(testCertificationRequest, testPrivateKey); // When - X509v3CertificateBuilder certificateBuilder = certificateBuilde.build(testCertificationRequest); + X509v3CertificateBuilder certificateBuilder = this.certificateBuilder.build(testCertificationRequest); X509CertificateHolder certificateHolder = certificateBuilder.build(createdContentSigner); // Then diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapterTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapterTest.java deleted file mode 100644 index e18d1ffb..00000000 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/Cmpv2ClientAdapterTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Cert Service - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aaf.certservice.certification.adapter; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import org.apache.commons.io.IOUtils; -import org.bouncycastle.asn1.x509.Certificate; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.X509v3CertificateBuilder; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.certservice.certification.configuration.model.CaMode; -import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server; -import org.onap.aaf.certservice.certification.exception.Cmpv2ClientAdapterException; -import org.onap.aaf.certservice.certification.model.CertificationModel; -import org.onap.aaf.certservice.certification.model.CsrModel; -import org.onap.aaf.certservice.cmpv2client.api.CmpClient; -import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class Cmpv2ClientAdapterTest { - - @Mock - private CmpClient cmpClient; - @Mock - private CsrModel csrModel; - @Mock - private Cmpv2Server server; - @Mock - private RsaContentSignerBuilder rsaContentSignerBuilder; - @Mock - private X509CertificateBuilder x509CertificateBuilder; - @Mock - private PKCS10CertificationRequest csr; - @Mock - private PrivateKey privateKey; - @Mock - private X509v3CertificateBuilder x509V3CertificateBuilder; - @Mock - private ContentSigner contentSigner; - @Mock - private X509CertificateHolder holder; - @Mock - private Certificate asn1Certificate; - @Mock - private X509Certificate certificate; - @Mock - private CertificateFactoryProvider certificateFactoryProvider; - - @InjectMocks - private Cmpv2ClientAdapter adapter; - - private static final CaMode CA_MODEL = CaMode.CLIENT; - private static final String TEST_MSG = "Test"; - - @Test - void adapterShouldRethrowClientExceptionOnFailure() - throws CmpClientException, IOException, OperatorCreationException, CertificateException, - NoSuchProviderException { - // Given - stubInternalProperties(); - - // When - Mockito.when(cmpClient.createCertificate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenThrow(new CmpClientException(TEST_MSG)); - - // Then - Assertions.assertThrows(CmpClientException.class, () -> adapter.callCmpClient(csrModel, server)); - } - - @Test - void shouldConvertToCertificationModel() - throws OperatorCreationException, CertificateException, NoSuchProviderException, IOException, - CmpClientException, Cmpv2ClientAdapterException { - // Given - stubInternalProperties(); - - // When - Mockito.when(cmpClient.createCertificate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(createCorrectClientResponse()); - CertificationModel certificationModel = adapter.callCmpClient(csrModel, server); - - // Then - InputStream certificate = getClass().getClassLoader().getResourceAsStream("certificateModelChain.first"); - InputStream trustedCertificate = - getClass().getClassLoader().getResourceAsStream("trustedCertificatesModel.first"); - String certificateModel = removeLineEndings(certificationModel.getCertificateChain().get(0)); - String expectedCertificate = - removeLineEndings(IOUtils.toString(Objects.requireNonNull(certificate), StandardCharsets.UTF_8)); - String trustedCertificateModel = removeLineEndings(certificationModel.getTrustedCertificates().get(0)); - String expectedTrustedCertificate = - removeLineEndings(IOUtils.toString(Objects.requireNonNull(trustedCertificate), StandardCharsets.UTF_8)); - - Assertions.assertEquals(certificateModel, expectedCertificate); - Assertions.assertEquals(trustedCertificateModel, expectedTrustedCertificate); - } - - @Test - void adapterShouldThrowClientAdapterExceptionOnFailure() - throws OperatorCreationException, CertificateException, NoSuchProviderException, IOException, - CmpClientException { - // Given - stubInternalProperties(); - - // When - Mockito.when(cmpClient.createCertificate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(createCorrectClientResponse()); - Mockito.when(certificateFactoryProvider.generateCertificate(Mockito.any())) - .thenThrow(new CertificateException(TEST_MSG)); - - // Then - Assertions.assertThrows(Cmpv2ClientAdapterException.class, () -> adapter.callCmpClient(csrModel, server)); - } - - private List<List<X509Certificate>> createCorrectClientResponse() - throws CertificateException, NoSuchProviderException { - InputStream certificateChain = getClass().getClassLoader().getResourceAsStream("certificateChain.first"); - InputStream trustedCertificate = getClass().getClassLoader().getResourceAsStream("trustedCertificates.first"); - X509Certificate x509Certificate = new CertificateFactoryProvider().generateCertificate(certificateChain); - X509Certificate x509TrustedCertificate = - new CertificateFactoryProvider().generateCertificate(trustedCertificate); - return Arrays.asList(Collections.singletonList(x509Certificate), - Collections.singletonList(x509TrustedCertificate)); - } - - private String removeLineEndings(String string) { - return string.replace("\n", "").replace("\r", ""); - } - - private void stubInternalProperties() - throws IOException, OperatorCreationException, CertificateException, NoSuchProviderException { - Mockito.when(server.getCaMode()).thenReturn(CA_MODEL); - Mockito.when(csrModel.getCsr()).thenReturn(csr); - Mockito.when(csrModel.getPrivateKey()).thenReturn(privateKey); - Mockito.when(x509CertificateBuilder.build(csr)).thenReturn(x509V3CertificateBuilder); - Mockito.when(rsaContentSignerBuilder.build(csr, privateKey)).thenReturn(contentSigner); - Mockito.when(x509V3CertificateBuilder.build(contentSigner)).thenReturn(holder); - Mockito.when(holder.toASN1Structure()).thenReturn(asn1Certificate); - Mockito.when(certificateFactoryProvider.generateCertificate(Mockito.any())).thenReturn(certificate); - Mockito.when(holder.toASN1Structure().getEncoded()).thenReturn("".getBytes()); - } - -} diff --git a/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java b/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java index bea6b6a1..06eeecce 100644 --- a/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java +++ b/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java @@ -153,7 +153,7 @@ class Cmpv2ClientTest { CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); // when List<List<X509Certificate>> cmpClientResult = - cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter); + cmpClient.createCertificate(csrModel, server, notBefore, notAfter); // then assertNotNull(cmpClientResult); } @@ -192,7 +192,7 @@ class Cmpv2ClientTest { // then Assertions.assertThrows( CmpClientException.class, - () -> cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter)); + () -> cmpClient.createCertificate(csrModel, server, notBefore, notAfter)); } @Test @@ -229,7 +229,7 @@ class Cmpv2ClientTest { // then Assertions.assertThrows( CmpClientException.class, - () -> cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter)); + () -> cmpClient.createCertificate(csrModel, server, notBefore, notAfter)); } @Test @@ -248,7 +248,7 @@ class Cmpv2ClientTest { // then Assertions.assertThrows( IllegalArgumentException.class, - () -> cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter)); + () -> cmpClient.createCertificate(csrModel, server, notBefore, notAfter)); } @Test @@ -268,7 +268,7 @@ class Cmpv2ClientTest { // then Assertions.assertThrows( CmpClientException.class, - () -> cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter)); + () -> cmpClient.createCertificate(csrModel, server, notBefore, notAfter)); } private void setCsrModelAndServerValues(String iak, String rv, String externalCaUrl, Date notBefore, Date notAfter) { diff --git a/certServiceClient/README.md b/certServiceClient/README.md index 092eb326..12520218 100644 --- a/certServiceClient/README.md +++ b/certServiceClient/README.md @@ -69,11 +69,10 @@ docker logs aaf-certservice-client ``` 0 Success 1 Invalid client configuration -2 Invalid CSR data -3 Failed key pair generation -4 Failed CSR generation -5 API return unsuccessful response -6 Problem with Http Client connection -7 Failed PKCS12 conversion -8 Failed Private Key to PEM Encoding -```
\ No newline at end of file +2 Invalid CSR configuration +3 Fail in key pair generation +4 Fail in CSR generation +5 CertService HTTP unsuccessful response +6 Internal HTTP Client connection problem +7 Fail in PKCS12 conversion +8 Fail in Private Key to PEM Encoding diff --git a/certServiceClient/pom.xml b/certServiceClient/pom.xml index 4b7c0cf9..0b3b1478 100644 --- a/certServiceClient/pom.xml +++ b/certServiceClient/pom.xml @@ -110,8 +110,6 @@ <dockerFileDir>${project.basedir}</dockerFileDir> <tags> <tag>${project.version}-${maven.build.timestamp}Z</tag> - <tag>${project.version}</tag> - <tag>${docker-image.latest}</tag> </tags> </build> </image> @@ -183,4 +181,4 @@ </dependency> </dependencies> -</project>
\ No newline at end of file +</project> diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/AppExitHandler.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/AppExitHandler.java index e29142e8..caeca37e 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/AppExitHandler.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/AppExitHandler.java @@ -18,14 +18,16 @@ */ package org.onap.aaf.certservice.client; +import org.onap.aaf.certservice.client.api.ExitStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AppExitHandler { - public static final Logger LOGGER = LoggerFactory.getLogger(AppExitHandler.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AppExitHandler.class); - public void exit(int exitCode) { - LOGGER.debug("Application exits with following exit code: {}", exitCode); - System.exit(exitCode); + public void exit(ExitStatus exitStatus) { + LOGGER.info(String.format("Application exits with following exit code: %s and message: %s", + exitStatus.getExitCodeValue(), exitStatus.getMessage())); + System.exit(exitStatus.getExitCodeValue()); } -}
\ No newline at end of file +} diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/CertServiceClient.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/CertServiceClient.java index d3d7f26d..0916bb8a 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/CertServiceClient.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/CertServiceClient.java @@ -36,13 +36,17 @@ import org.onap.aaf.certservice.client.configuration.model.CsrConfiguration; import org.onap.aaf.certservice.client.httpclient.CloseableHttpClientProvider; import org.onap.aaf.certservice.client.httpclient.HttpClient; import org.onap.aaf.certservice.client.httpclient.model.CertServiceResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import static org.onap.aaf.certservice.client.api.ExitCode.SUCCESS_EXIT_CODE; +import static org.onap.aaf.certservice.client.api.ExitStatus.SUCCESS; import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.KEY_SIZE; import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.RSA_ENCRYPTION_ALGORITHM; public class CertServiceClient { + private static final Logger LOGGER = LoggerFactory.getLogger(CertServiceClient.class); + private AppExitHandler appExitHandler; public CertServiceClient(AppExitHandler appExitHandler) { @@ -74,8 +78,9 @@ public class CertServiceClient { filesCreator.createKeystore(certServiceData.getCertificateChain(), keyPair.getPrivate()); filesCreator.createTruststore(certServiceData.getTrustedCertificates()); } catch (ExitableException e) { - appExitHandler.exit(e.applicationExitCode()); + LOGGER.error("Cert Service Client fail in execution: ", e); + appExitHandler.exit(e.applicationExitStatus()); } - appExitHandler.exit(SUCCESS_EXIT_CODE.getValue()); + appExitHandler.exit(SUCCESS); } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitCode.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitStatus.java index 670cbe90..c474fd03 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitCode.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitStatus.java @@ -18,24 +18,31 @@ */ package org.onap.aaf.certservice.client.api; -public enum ExitCode { - SUCCESS_EXIT_CODE(0), - CLIENT_CONFIGURATION_EXCEPTION(1), - CSR_CONFIGURATION_EXCEPTION(2), - KEY_PAIR_GENERATION_EXCEPTION(3), - CSR_GENERATION_EXCEPTION(4), - CERT_SERVICE_API_CONNECTION_EXCEPTION(5), - HTTP_CLIENT_EXCEPTION(6), - PKCS12_CONVERSION_EXCEPTION(7), - PK_TO_PEM_ENCODING_EXCEPTION(8); +public enum ExitStatus { + + SUCCESS(0, "Success"), + CLIENT_CONFIGURATION_EXCEPTION(1,"Invalid client configuration"), + CSR_CONFIGURATION_EXCEPTION(2,"Invalid CSR configuration"), + KEY_PAIR_GENERATION_EXCEPTION(3,"Fail in key pair generation"), + CSR_GENERATION_EXCEPTION(4,"Fail in CSR generation"), + CERT_SERVICE_API_CONNECTION_EXCEPTION(5,"CertService HTTP unsuccessful response"), + HTTP_CLIENT_EXCEPTION(6,"Internal HTTP Client connection problem"), + PKCS12_CONVERSION_EXCEPTION(7,"Fail in PKCS12 conversion"), + PK_TO_PEM_ENCODING_EXCEPTION(8,"Fail in Private Key to PEM Encoding"); private final int value; + private final String message; - ExitCode(int value) { + ExitStatus(int value, String message) { this.value = value; + this.message = message; } - public int getValue() { + public int getExitCodeValue() { return value; } + + public String getMessage(){ + return message; + } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitableException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitableException.java index f9166c96..fc1bc760 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitableException.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/api/ExitableException.java @@ -26,5 +26,5 @@ public abstract class ExitableException extends Exception { public ExitableException(String message) { super(message); } - public abstract int applicationExitCode(); + public abstract ExitStatus applicationExitStatus(); } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/CsrFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/CsrFactory.java index 83fa6d44..a7fb3f35 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/CsrFactory.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/CsrFactory.java @@ -40,9 +40,7 @@ import org.slf4j.LoggerFactory; import javax.security.auth.x500.X500Principal; import java.io.IOException; import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.security.KeyPair; -import java.util.Base64; import java.util.Optional; import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmConstants.COMMON_NAME; @@ -56,7 +54,7 @@ import static org.onap.aaf.certservice.client.certification.EncryptionAlgorithmC public class CsrFactory { - private final Logger LOGGER = LoggerFactory.getLogger(CsrFactory.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CsrFactory.class); private static final String SANS_DELIMITER = ":"; private final CsrConfiguration configuration; @@ -67,13 +65,14 @@ public class CsrFactory { public String createCsrInPem(KeyPair keyPair) throws CsrGenerationException { - PKCS10CertificationRequest request; + LOGGER.info("Creation of CSR has been started with following parameters: {}", configuration.toString()); String csrParameters = getMandatoryParameters().append(getOptionalParameters()).toString(); X500Principal subject = new X500Principal(csrParameters); - request = createPKCS10Csr(subject, keyPair); - return convertPKC10CsrToPem(request); - } + PKCS10CertificationRequest request = createPKCS10Csr(subject, keyPair); + LOGGER.info("Creation of CSR has been completed successfully"); + return convertPKCS10CsrToPem(request); + } private StringBuilder getMandatoryParameters() { return new StringBuilder(String.format("%s=%s, %s=%s, %s=%s, %s=%s", @@ -116,9 +115,10 @@ public class CsrFactory { return contentSigner; } - private String convertPKC10CsrToPem(PKCS10CertificationRequest request) throws CsrGenerationException { + private String convertPKCS10CsrToPem(PKCS10CertificationRequest request) throws CsrGenerationException { final StringWriter stringWriter = new StringWriter(); try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) { + LOGGER.info("Conversion of CSR to PEM has been started"); pemWriter.writeObject(request); } catch (IOException e) { LOGGER.error("Conversion to PEM failed, exception message: {}", e.getMessage()); diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/KeyPairFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/KeyPairFactory.java index 64136863..988d37d8 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/KeyPairFactory.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/KeyPairFactory.java @@ -39,9 +39,10 @@ public class KeyPairFactory { public KeyPair create() throws KeyPairGenerationException { try { + LOGGER.info("KeyPair generation started with algorithm: {} and key size: {}", encryptionAlgorithm, keySize); return createKeyPairGenerator().generateKeyPair(); } catch (NoSuchAlgorithmException e) { - LOGGER.error("Generation of KeyPair failed, exception message: " + e.getMessage()); + LOGGER.error("Generation of KeyPair failed, exception message: {}" , e.getMessage()); throw new KeyPairGenerationException(e); } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoder.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoder.java index 77995958..7391b119 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoder.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/PrivateKeyToPemEncoder.java @@ -34,16 +34,16 @@ import org.slf4j.LoggerFactory; public class PrivateKeyToPemEncoder { - public static final String PEM_OBJECT_TYPE = "RSA PRIVATE KEY"; - private final Logger LOGGER = LoggerFactory.getLogger(PrivateKeyToPemEncoder.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PrivateKeyToPemEncoder.class); + private static final String PEM_OBJECT_TYPE = "RSA PRIVATE KEY"; public String encodePrivateKeyToPem(PrivateKey pk) throws PkEncodingException { - LOGGER.info("Encoding PrivateKey to PEM"); + LOGGER.info("Attempt to encode private key to PEM"); StringWriter stringWriter = new StringWriter(); try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) { pemWriter.writeObject(new PemObject(PEM_OBJECT_TYPE, pk.getEncoded())); } catch (IOException e) { - LOGGER.error("Exception occurred during encoding PrivateKey to PEM", e); + LOGGER.error("Encode of private key to PEM failed. Exception message: {}", e.getMessage()); throw new PkEncodingException(e); } return stringWriter.toString(); diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PKCS12FilesCreator.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PKCS12FilesCreator.java index d8c41bfd..9b0cfb78 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PKCS12FilesCreator.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PKCS12FilesCreator.java @@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory; class PKCS12FilesCreator { + private static final Logger LOGGER = LoggerFactory.getLogger(PKCS12FilesCreator.class); private static final String KEYSTORE_JKS = "keystore.jks"; private static final String KEYSTORE_PASS = "keystore.pass"; private static final String TRUSTSTORE_JKS = "truststore.jks"; @@ -37,7 +38,6 @@ class PKCS12FilesCreator { private final String keystorePassPath; private final String truststoreJksPath; private final String truststorePassPath; - private final Logger LOGGER = LoggerFactory.getLogger(PKCS12FilesCreator.class); PKCS12FilesCreator(String path) { @@ -48,7 +48,7 @@ class PKCS12FilesCreator { } void saveKeystoreData(byte[] keystoreData, String keystorePassword) throws PemToPKCS12ConverterException { - LOGGER.debug("Creating PKCS12 keystore files and saving data. Keystore path: {}", keystoreJksPath); + LOGGER.debug("Attempt to create PKCS12 keystore files and saving data. Keystore path: {}", keystoreJksPath); saveDataToLocation(keystoreData, keystoreJksPath); saveDataToLocation(keystorePassword.getBytes(), keystorePassPath); @@ -56,7 +56,7 @@ class PKCS12FilesCreator { void saveTruststoreData(byte[] truststoreData, String truststorePassword) throws PemToPKCS12ConverterException { - LOGGER.debug("Creating PKCS12 truststore files and saving data. Truststore path: {}", truststoreJksPath); + LOGGER.debug("Attempt to create PKCS12 truststore files and saving data. Truststore path: {}", truststoreJksPath); saveDataToLocation(truststoreData, truststoreJksPath); saveDataToLocation(truststorePassword.getBytes(), truststorePassPath); @@ -66,7 +66,7 @@ class PKCS12FilesCreator { try (FileOutputStream fos = new FileOutputStream(path)) { fos.write(data); } catch (IOException e) { - LOGGER.error("PKCS12 files creation failed", e); + LOGGER.error("PKCS12 files creation failed, exception message: {}", e.getMessage()); throw new PemToPKCS12ConverterException(e); } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemToPKCS12Converter.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemToPKCS12Converter.java index eab9bf7c..ef1666dc 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemToPKCS12Converter.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/conversion/PemToPKCS12Converter.java @@ -41,20 +41,20 @@ import org.slf4j.LoggerFactory; class PemToPKCS12Converter { - private final static String PKCS12 = "PKCS12"; - private final static String PASSWORD_ERROR_MSG = "Password should be min. 16 chars long and should contain only alphanumeric characters and special characters like Underscore (_), Dollar ($) and Pound (#)"; + private static final Logger LOGGER = LoggerFactory.getLogger(PemToPKCS12Converter.class); + private static final String PKCS12 = "PKCS12"; + private static final String PASSWORD_ERROR_MSG = "Password should be min. 16 chars long and should contain only alphanumeric characters and special characters like Underscore (_), Dollar ($) and Pound (#)"; private final LoadStoreParameter EMPTY_KEYSTORE_CONFIGURATION = null; - private final Logger LOGGER = LoggerFactory.getLogger(PemToPKCS12Converter.class); byte[] convertKeystore(List<String> certificateChain, Password password, String alias, PrivateKey privateKey) throws PemToPKCS12ConverterException { - LOGGER.debug("Converting PEM certificates to PKCS12 keystore."); + LOGGER.info("Conversion of PEM certificates to PKCS12 keystore"); return convert(certificateChain, password, certs -> getKeyStore(alias, password, certs, privateKey)); } byte[] convertTruststore(List<String> trustAnchors, Password password, String alias) throws PemToPKCS12ConverterException { - LOGGER.debug("Converting PEM certificates to PKCS12 truststore."); + LOGGER.info("Conversion of PEM certificates to PKCS12 truststore"); return convert(trustAnchors, password, certs -> getTrustStore(alias, certs)); } @@ -79,7 +79,7 @@ class PemToPKCS12Converter { ks.store(bos, password.toCharArray()); return bos.toByteArray(); } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) { - LOGGER.error("Pem to PKCS12 converter failed", e); + LOGGER.error("Pem to PKCS12 converter failed, exception message: {}", e.getMessage()); throw new PemToPKCS12ConverterException(e); } } @@ -126,7 +126,7 @@ class PemToPKCS12Converter { .setProvider(new BouncyCastleProvider()) .getCertificate(certHolder); } catch (IOException | CertificateException e) { - LOGGER.error("Certificates conversion failed", e); + LOGGER.error("Certificates conversion failed, exception message: {}", e.getMessage()); throw new PemToPKCS12ConverterException(e); } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CsrGenerationException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CsrGenerationException.java index c1d4afd2..8c93a227 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CsrGenerationException.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/CsrGenerationException.java @@ -19,17 +19,17 @@ package org.onap.aaf.certservice.client.certification.exception; -import org.onap.aaf.certservice.client.api.ExitCode; +import org.onap.aaf.certservice.client.api.ExitStatus; import org.onap.aaf.certservice.client.api.ExitableException; public class CsrGenerationException extends ExitableException { - private static final ExitCode EXIT_CODE = ExitCode.CSR_GENERATION_EXCEPTION; + private static final ExitStatus EXIT_STATUS = ExitStatus.CSR_GENERATION_EXCEPTION; public CsrGenerationException(Throwable e) { super(e); } - public int applicationExitCode() { - return EXIT_CODE.getValue(); + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/KeyPairGenerationException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/KeyPairGenerationException.java index 6af69889..d03c819d 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/KeyPairGenerationException.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/KeyPairGenerationException.java @@ -18,17 +18,17 @@ */ package org.onap.aaf.certservice.client.certification.exception; -import org.onap.aaf.certservice.client.api.ExitCode; +import org.onap.aaf.certservice.client.api.ExitStatus; import org.onap.aaf.certservice.client.api.ExitableException; public class KeyPairGenerationException extends ExitableException { - private static final ExitCode EXIT_CODE = ExitCode.KEY_PAIR_GENERATION_EXCEPTION; + private static final ExitStatus EXIT_STATUS = ExitStatus.KEY_PAIR_GENERATION_EXCEPTION; public KeyPairGenerationException(Throwable e) { super(e); } - public int applicationExitCode() { - return EXIT_CODE.getValue(); + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PemToPKCS12ConverterException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PemToPKCS12ConverterException.java index 87020d6f..b98f4ace 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PemToPKCS12ConverterException.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PemToPKCS12ConverterException.java @@ -19,11 +19,11 @@ package org.onap.aaf.certservice.client.certification.exception; -import org.onap.aaf.certservice.client.api.ExitCode; +import org.onap.aaf.certservice.client.api.ExitStatus; import org.onap.aaf.certservice.client.api.ExitableException; public class PemToPKCS12ConverterException extends ExitableException { - private static final ExitCode EXIT_CODE = ExitCode.PKCS12_CONVERSION_EXCEPTION; + private static final ExitStatus EXIT_STATUS = ExitStatus.PKCS12_CONVERSION_EXCEPTION; public PemToPKCS12ConverterException(Throwable e) { super(e); @@ -33,7 +33,7 @@ public class PemToPKCS12ConverterException extends ExitableException { } @Override - public int applicationExitCode() { - return EXIT_CODE.getValue(); + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PkEncodingException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PkEncodingException.java index 596a6a44..20d623aa 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PkEncodingException.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/certification/exception/PkEncodingException.java @@ -19,17 +19,17 @@ package org.onap.aaf.certservice.client.certification.exception; -import org.onap.aaf.certservice.client.api.ExitCode; +import org.onap.aaf.certservice.client.api.ExitStatus; import org.onap.aaf.certservice.client.api.ExitableException; public class PkEncodingException extends ExitableException { - private static final ExitCode EXIT_CODE = ExitCode.PK_TO_PEM_ENCODING_EXCEPTION; + private static final ExitStatus EXIT_STATUS = ExitStatus.PK_TO_PEM_ENCODING_EXCEPTION; public PkEncodingException(Throwable e) { super(e); } - public int applicationExitCode() { - return EXIT_CODE.getValue(); + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/ClientConfigurationException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/ClientConfigurationException.java index 5d968f43..f9360d73 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/ClientConfigurationException.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/ClientConfigurationException.java @@ -19,17 +19,17 @@ */ package org.onap.aaf.certservice.client.configuration.exception; -import org.onap.aaf.certservice.client.api.ExitCode; +import org.onap.aaf.certservice.client.api.ExitStatus; import org.onap.aaf.certservice.client.api.ExitableException; public class ClientConfigurationException extends ExitableException { - private static final ExitCode EXIT_CODE = ExitCode.CLIENT_CONFIGURATION_EXCEPTION; + private static final ExitStatus EXIT_STATUS = ExitStatus.CLIENT_CONFIGURATION_EXCEPTION; public ClientConfigurationException(String message) { super(message); } - public int applicationExitCode() { - return EXIT_CODE.getValue(); + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/CsrConfigurationException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/CsrConfigurationException.java index f9373117..a7cf4f7a 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/CsrConfigurationException.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/exception/CsrConfigurationException.java @@ -19,17 +19,17 @@ */ package org.onap.aaf.certservice.client.configuration.exception; -import org.onap.aaf.certservice.client.api.ExitCode; +import org.onap.aaf.certservice.client.api.ExitStatus; import org.onap.aaf.certservice.client.api.ExitableException; public class CsrConfigurationException extends ExitableException { - private static final ExitCode EXIT_CODE = ExitCode.CSR_CONFIGURATION_EXCEPTION; + private static final ExitStatus EXIT_STATUS = ExitStatus.CSR_CONFIGURATION_EXCEPTION; public CsrConfigurationException(String message) { super(message); } - public int applicationExitCode() { - return EXIT_CODE.getValue(); + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactory.java index 26a2b1b1..a03ded6c 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactory.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/ClientConfigurationFactory.java @@ -24,9 +24,12 @@ import org.onap.aaf.certservice.client.configuration.ClientConfigurationEnvs; import org.onap.aaf.certservice.client.configuration.EnvsForClient; import org.onap.aaf.certservice.client.configuration.exception.ClientConfigurationException; import org.onap.aaf.certservice.client.configuration.model.ClientConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ClientConfigurationFactory extends AbstractConfigurationFactory<ClientConfiguration> { + private static final Logger LOGGER = LoggerFactory.getLogger(ClientConfigurationFactory.class); private final EnvsForClient envsForClient; public ClientConfigurationFactory(EnvsForClient envsForClient) { @@ -54,6 +57,8 @@ public class ClientConfigurationFactory extends AbstractConfigurationFactory<Cli .map(configuration::setCaName) .orElseThrow(() -> new ClientConfigurationException(ClientConfigurationEnvs.CA_NAME + " is invalid.")); + LOGGER.info("Successful validation of Client configuration. Configuration data: {}", configuration.toString()); + return configuration; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactory.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactory.java index a6e86187..a94c906f 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactory.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/factory/CsrConfigurationFactory.java @@ -24,9 +24,12 @@ import org.onap.aaf.certservice.client.configuration.CsrConfigurationEnvs; import org.onap.aaf.certservice.client.configuration.EnvsForCsr; import org.onap.aaf.certservice.client.configuration.exception.CsrConfigurationException; import org.onap.aaf.certservice.client.configuration.model.CsrConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class CsrConfigurationFactory extends AbstractConfigurationFactory<CsrConfiguration> { + private static final Logger LOGGER = LoggerFactory.getLogger(CsrConfigurationFactory.class); private final EnvsForCsr envsForCsr; @@ -67,6 +70,8 @@ public class CsrConfigurationFactory extends AbstractConfigurationFactory<CsrCon envsForCsr.getSubjectAlternativesName() .map(configuration::setSubjectAlternativeNames); + LOGGER.info("Successful validation of CSR configuration. Configuration data: {}", configuration.toString()); + return configuration; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ClientConfiguration.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ClientConfiguration.java index d1c1c685..ff2db831 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ClientConfiguration.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/ClientConfiguration.java @@ -20,6 +20,8 @@ package org.onap.aaf.certservice.client.configuration.model; +import org.onap.aaf.certservice.client.configuration.ClientConfigurationEnvs; + public class ClientConfiguration implements ConfigurationModel { private static final Integer DEFAULT_TIMEOUT_MS = 30000; @@ -72,4 +74,13 @@ public class ClientConfiguration implements ConfigurationModel { this.caName = caName; return this; } + + @Override + public String toString() { + return String.format("%s: %s, %s: %s, %s: %s, %s: %s", + ClientConfigurationEnvs.REQUEST_URL, urlToCertService, + ClientConfigurationEnvs.REQUEST_TIMEOUT, requestTimeout, + ClientConfigurationEnvs.OUTPUT_PATH, certsOutputPath, + ClientConfigurationEnvs.CA_NAME, caName); + } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/CsrConfiguration.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/CsrConfiguration.java index aaaf10fa..55f33c9f 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/CsrConfiguration.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/configuration/model/CsrConfiguration.java @@ -21,6 +21,8 @@ package org.onap.aaf.certservice.client.configuration.model; +import org.onap.aaf.certservice.client.configuration.CsrConfigurationEnvs; + public class CsrConfiguration implements ConfigurationModel { private String commonName; @@ -94,4 +96,16 @@ public class CsrConfiguration implements ConfigurationModel { this.sans = subjectAlternativeNames; return this; } + + @Override + public String toString() { + return String.format("%s: %s, %s: %s, %s: %s, %s: %s, %s: %s, %s: %s, %s: %s", + CsrConfigurationEnvs.COMMON_NAME, commonName, + CsrConfigurationEnvs.COUNTRY, country, + CsrConfigurationEnvs.STATE, state, + CsrConfigurationEnvs.ORGANIZATION, organization, + CsrConfigurationEnvs.ORGANIZATION_UNIT, organizationUnit, + CsrConfigurationEnvs.LOCATION, location, + CsrConfigurationEnvs.SANS, sans); + } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/CloseableHttpClientProvider.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/CloseableHttpClientProvider.java index ff29a14d..5ad933ff 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/CloseableHttpClientProvider.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/CloseableHttpClientProvider.java @@ -34,7 +34,11 @@ public class CloseableHttpClientProvider { public CloseableHttpClient getClient() { RequestConfig config = - RequestConfig.custom().setConnectionRequestTimeout(timeout).build(); + RequestConfig.custom() + .setConnectionRequestTimeout(timeout) + .setConnectTimeout(timeout) + .setSocketTimeout(timeout) + .build(); return HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/HttpClient.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/HttpClient.java index 30f881bb..7512830d 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/HttpClient.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/HttpClient.java @@ -38,12 +38,11 @@ import java.io.IOException; public class HttpClient { + private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class); private static final String CSR_HEADER_NAME = "CSR"; private static final String PK_HEADER_NAME = "PK"; private static final String CHARSET_UTF_8 = "UTF-8"; - private final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class); - private final Gson gson = new Gson(); private final CloseableHttpClientProvider httpClientProvider; private final String certServiceAddress; @@ -57,20 +56,24 @@ public class HttpClient { throws CertServiceApiResponseException, HttpClientException { try (CloseableHttpClient httpClient = httpClientProvider.getClient()) { - LOGGER.info("Sending request to API. Url: {}{} ", certServiceAddress, caName); + LOGGER.info("Attempt to send request to API, on url: {}{} ", certServiceAddress, caName); HttpResponse httpResponse = httpClient.execute(createHttpRequest(caName, csr, encodedPk)); LOGGER.info("Received response from API"); return extractCertServiceResponse(httpResponse); } catch (IOException e) { - LOGGER.error("Failed execute request to API for URL: {}{} . Exception message: {}", + LOGGER.error("Failed execute request to API for URL: {}{} , exception message: {}", certServiceAddress, caName, e.getMessage()); throw new HttpClientException(e); } } - private int getStatusCode(HttpResponse httpResponse) { - return httpResponse.getStatusLine().getStatusCode(); + private HttpGet createHttpRequest(String caName, String csr, String pk) { + String url = certServiceAddress + caName; + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader(CSR_HEADER_NAME, csr); + httpGet.addHeader(PK_HEADER_NAME, pk); + return httpGet; } private CertServiceResponse extractCertServiceResponse(HttpResponse httpResponse) @@ -84,34 +87,25 @@ public class HttpClient { return gson.fromJson(jsonResponse, CertServiceResponse.class); } - private String getStringResponse(HttpEntity httpEntity) throws HttpClientException { - try { - return EntityUtils.toString(httpEntity, CHARSET_UTF_8); - } catch (IOException e) { - LOGGER.error("Cannot parse response to string", e); - throw new HttpClientException(e); - } - } - - private HttpGet createHttpRequest(String caName, String csr, String pk) { - String url = certServiceAddress + caName; - HttpGet httpGet = new HttpGet(url); - httpGet.addHeader(CSR_HEADER_NAME, csr); - httpGet.addHeader(PK_HEADER_NAME, pk); - return httpGet; - } - - private CertServiceApiResponseException generateApiResponseException(HttpResponse httpResponse) throws HttpClientException { String stringResponse = getStringResponse(httpResponse.getEntity()); ErrorCertServiceResponse errorCertServiceResponse = gson.fromJson(stringResponse, ErrorCertServiceResponse.class); - String messageFromApi = errorCertServiceResponse.getMessage(); - String path = errorCertServiceResponse.getPath(); - int httpResponseCode = getStatusCode(httpResponse); + return new CertServiceApiResponseException(getStatusCode(httpResponse), errorCertServiceResponse.getMessage()); + } - return new CertServiceApiResponseException(certServiceAddress + path, httpResponseCode, messageFromApi); + private int getStatusCode(HttpResponse httpResponse) { + return httpResponse.getStatusLine().getStatusCode(); + } + + private String getStringResponse(HttpEntity httpEntity) throws HttpClientException { + try { + return EntityUtils.toString(httpEntity, CHARSET_UTF_8); + } catch (IOException e) { + LOGGER.error("Cannot parse response to string, exception message: {}", e.getMessage()); + throw new HttpClientException(e); + } } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/CertServiceApiResponseException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/CertServiceApiResponseException.java index 7286318f..151c2a1c 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/CertServiceApiResponseException.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/CertServiceApiResponseException.java @@ -20,23 +20,22 @@ package org.onap.aaf.certservice.client.httpclient.exception; -import org.onap.aaf.certservice.client.api.ExitCode; +import org.onap.aaf.certservice.client.api.ExitStatus; import org.onap.aaf.certservice.client.api.ExitableException; public class CertServiceApiResponseException extends ExitableException { - private static final ExitCode EXIT_CODE = ExitCode.CERT_SERVICE_API_CONNECTION_EXCEPTION; + private static final ExitStatus EXIT_STATUS = ExitStatus.CERT_SERVICE_API_CONNECTION_EXCEPTION; - public CertServiceApiResponseException(String url, int responseCode, String messageFromAPI) { + public CertServiceApiResponseException(int responseCode, String messageFromAPI) { - super(String.format("Request failed for URL '%s'. Response code: %d . Message from API: %s", - url, + super(String.format("CertService HTTP unsuccessful response. Response code: %d . Message from Service: %s", responseCode, messageFromAPI)); } @Override - public int applicationExitCode() { - return EXIT_CODE.getValue(); + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/HttpClientException.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/HttpClientException.java index 28f83073..697d152a 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/HttpClientException.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/exception/HttpClientException.java @@ -20,18 +20,18 @@ package org.onap.aaf.certservice.client.httpclient.exception; -import org.onap.aaf.certservice.client.api.ExitCode; +import org.onap.aaf.certservice.client.api.ExitStatus; import org.onap.aaf.certservice.client.api.ExitableException; public class HttpClientException extends ExitableException { - private static final ExitCode EXIT_CODE = ExitCode.HTTP_CLIENT_EXCEPTION; + private static final ExitStatus EXIT_STATUS = ExitStatus.HTTP_CLIENT_EXCEPTION; - public HttpClientException(Throwable e) { + public HttpClientException(Throwable e){ super(e); } @Override - public int applicationExitCode() { - return EXIT_CODE.getValue(); + public ExitStatus applicationExitStatus() { + return EXIT_STATUS; } } diff --git a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/ErrorCertServiceResponse.java b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/ErrorCertServiceResponse.java index 6fe99ce5..4a9efcb4 100644 --- a/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/ErrorCertServiceResponse.java +++ b/certServiceClient/src/main/java/org/onap/aaf/certservice/client/httpclient/model/ErrorCertServiceResponse.java @@ -22,19 +22,14 @@ package org.onap.aaf.certservice.client.httpclient.model; public class ErrorCertServiceResponse { - private final String message; - private final String path; + private final String errorMessage; - public ErrorCertServiceResponse(String message, String path) { - this.message = message; - this.path = path; + public ErrorCertServiceResponse(String errorMessage) { + this.errorMessage = errorMessage; } public String getMessage() { - return message; + return errorMessage; } - public String getPath() { - return path; - } } diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java index 9e733017..7e7bf5db 100644 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java +++ b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/CertServiceClientTest.java @@ -25,8 +25,8 @@ import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.verify; -import static org.onap.aaf.certservice.client.api.ExitCode.CLIENT_CONFIGURATION_EXCEPTION; -import static org.onap.aaf.certservice.client.api.ExitCode.SUCCESS_EXIT_CODE; +import static org.onap.aaf.certservice.client.api.ExitStatus.CLIENT_CONFIGURATION_EXCEPTION; +import static org.onap.aaf.certservice.client.api.ExitStatus.SUCCESS; @ExtendWith(MockitoExtension.class) class CertServiceClientTest { @@ -35,13 +35,13 @@ class CertServiceClientTest { @Test public void shouldExitWithDefinedExitCode_onRunCallWhenNoEnvsPresent() { // given - doNothing().when(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION.getValue()); - doNothing().when(appExitHandler).exit(SUCCESS_EXIT_CODE.getValue()); + doNothing().when(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); + doNothing().when(appExitHandler).exit(SUCCESS); CertServiceClient certServiceClient = new CertServiceClient(appExitHandler); // when certServiceClient.run(); // then - verify(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION.getValue()); - verify(appExitHandler).exit(SUCCESS_EXIT_CODE.getValue()); + verify(appExitHandler).exit(CLIENT_CONFIGURATION_EXCEPTION); + verify(appExitHandler).exit(SUCCESS); } -}
\ No newline at end of file +} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/DummyExitableException.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/DummyExitableException.java deleted file mode 100644 index 80a2f723..00000000 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/DummyExitableException.java +++ /dev/null @@ -1,35 +0,0 @@ -/*============LICENSE_START======================================================= - * aaf-certservice-client - * ================================================================================ - * Copyright (C) 2020 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aaf.certservice.client; - -import org.onap.aaf.certservice.client.api.ExitableException; - -class DummyExitableException extends ExitableException { - private static final int EXIT_CODE = 888; - - DummyExitableException() { - super("This is Test Exitable Exception"); - } - - @Override - public int applicationExitCode() { - return EXIT_CODE; - } - -} diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/model/CsrConfigurationFactoryTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/model/CsrConfigurationFactoryTest.java index bb566e81..6ab1bffc 100644 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/model/CsrConfigurationFactoryTest.java +++ b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/configuration/model/CsrConfigurationFactoryTest.java @@ -23,19 +23,18 @@ package org.onap.aaf.certservice.client.configuration.model; import org.assertj.core.api.Condition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.api.ExitCode; import org.onap.aaf.certservice.client.configuration.CsrConfigurationEnvs; import org.onap.aaf.certservice.client.configuration.EnvsForCsr; import org.onap.aaf.certservice.client.configuration.exception.CsrConfigurationException; import org.onap.aaf.certservice.client.configuration.factory.CsrConfigurationFactory; import java.util.Optional; -import java.util.function.Predicate; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.onap.aaf.certservice.client.api.ExitStatus.CSR_CONFIGURATION_EXCEPTION; public class CsrConfigurationFactoryTest { @@ -55,7 +54,7 @@ public class CsrConfigurationFactoryTest { private Condition<CsrConfigurationException> expectedExitCodeCondition = new Condition<>("Correct exit code"){ @Override public boolean matches(CsrConfigurationException e) { - return e.applicationExitCode() == ExitCode.CSR_CONFIGURATION_EXCEPTION.getValue(); + return e.applicationExitStatus() == CSR_CONFIGURATION_EXCEPTION; } }; diff --git a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java index 461b7a34..2a539414 100644 --- a/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java +++ b/certServiceClient/src/test/java/org/onap/aaf/certservice/client/httpclient/HttpClientTest.java @@ -27,7 +27,6 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.client.api.ExitCode; import org.onap.aaf.certservice.client.httpclient.exception.CertServiceApiResponseException; import org.onap.aaf.certservice.client.httpclient.exception.HttpClientException; import org.onap.aaf.certservice.client.httpclient.model.CertServiceResponse; @@ -38,9 +37,8 @@ import java.util.List; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static java.net.HttpURLConnection.HTTP_OK; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -89,60 +87,49 @@ class HttpClientTest { List<String> trustedCertificate = certServiceResponse.getTrustedCertificates(); // then - assertNotNull(certServiceResponse); + assertThat(certServiceResponse).isNotNull(); final int expectedTwoElements = 2; - assertEquals(expectedTwoElements, certificateChain.size()); - assertEquals(expectedTwoElements, trustedCertificate.size()); - assertEquals(EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN, certificateChain.get(0)); - assertEquals(EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES, trustedCertificate.get(0)); + assertThat(certificateChain).hasSize(expectedTwoElements); + assertThat(trustedCertificate).hasSize(expectedTwoElements); + + assertThat(certificateChain.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_CERTIFICATE_CHAIN); + assertThat(trustedCertificate.get(0)).isEqualTo(EXPECTED_FIRST_ELEMENT_OF_TRUSTED_CERTIFICATES); } @Test void shouldThrowCertServiceApiResponseException_WhenPkHeaderIsMissing() throws Exception { - // given + //given mockServerResponse(HTTP_BAD_REQUEST, MISSING_PK_RESPONSE); - // when - CertServiceApiResponseException exception = - assertThrows(CertServiceApiResponseException.class, - () -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); - - // then - assertEquals(ExitCode.CERT_SERVICE_API_CONNECTION_EXCEPTION.getValue(), exception.applicationExitCode()); + //when //then + assertThatExceptionOfType(CertServiceApiResponseException.class) + .isThrownBy(()->httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); } @Test - void shouldThrowHttpClientException_WhenCannotExecuteRequestToAPI() throws Exception{ + void shouldThrowHttpClientException_WhenCannotExecuteRequestToAPI() throws Exception { //given when(closeableHttpClient.execute(any(HttpGet.class))).thenThrow(IOException.class); - //when - HttpClientException exception = - assertThrows(HttpClientException.class, - () -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); - - //then - assertEquals(ExitCode.HTTP_CLIENT_EXCEPTION.getValue(), exception.applicationExitCode()); + //when //then + assertThatExceptionOfType(HttpClientException.class) + .isThrownBy(()->httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); } @Test - void shouldThrowHttpClientException_WhenCannotParseResponseToString() throws Exception{ + void shouldThrowHttpClientException_WhenCannotParseResponseToString() throws Exception { //given mockServerResponse(HTTP_OK, CORRECT_RESPONSE); when(httpEntity.getContent()).thenThrow(IOException.class); - //when - HttpClientException exception = - assertThrows(HttpClientException.class, - () -> httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); - - //then - assertEquals(ExitCode.HTTP_CLIENT_EXCEPTION.getValue(), exception.applicationExitCode()); + //when //then + assertThatExceptionOfType(HttpClientException.class) + .isThrownBy(()->httpClient.retrieveCertServiceData(CA_NAME, CSR, "")); } private void mockServerResponse(int serverCodeResponse, String stringResponse) |