From 8252e258b55d09a389a37d9880b97f16fd4d9275 Mon Sep 17 00:00:00 2001 From: Michal Banka Date: Tue, 17 Mar 2020 16:46:56 +0100 Subject: [PATCH] Remove CSRMeta class dependency Signed-off-by: Michal Banka Change-Id: If3458612629dd84f95bf9ba1e0778e65696bb13d Issue-ID: AAF-1107 --- .../certification/adapter/Cmpv2ClientAdapter.java | 13 +- .../certification/adapter/CsrMetaBuilder.java | 90 --------- .../certservice/certification/model/CsrModel.java | 4 +- .../aaf/certservice/cmpv2client/api/CmpClient.java | 103 +++++----- .../certservice/cmpv2client/external/CsrMeta.java | 208 --------------------- .../cmpv2client/impl/CmpClientImpl.java | 63 ++++--- .../adapter/Cmpv2ClientAdapterTest.java | 12 +- .../certification/adapter/CsrMetaBuilderTest.java | 99 ---------- .../certservice/cmpv2client/Cmpv2ClientTest.java | 118 ++++-------- 9 files changed, 137 insertions(+), 573 deletions(-) delete mode 100644 certService/src/main/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilder.java delete mode 100644 certService/src/main/java/org/onap/aaf/certservice/cmpv2client/external/CsrMeta.java delete mode 100644 certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilderTest.java 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 index c9e61b02..2477c421 100644 --- 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 @@ -29,6 +29,7 @@ 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; @@ -54,17 +55,15 @@ public class Cmpv2ClientAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(Cmpv2ClientAdapter.class); private final CmpClient cmpClient; - private final CsrMetaBuilder csrMetaBuilder; private final RsaContentSignerBuilder rsaContentSignerBuilder; private final X509CertificateBuilder x509CertificateBuilder; private final CertificateFactoryProvider certificateFactoryProvider; @Autowired - public Cmpv2ClientAdapter(CmpClient cmpClient, CsrMetaBuilder csrMetaBuilder, - RsaContentSignerBuilder rsaContentSignerBuilder, X509CertificateBuilder x509CertificateBuilder, + public Cmpv2ClientAdapter(CmpClient cmpClient, RsaContentSignerBuilder rsaContentSignerBuilder, + X509CertificateBuilder x509CertificateBuilder, CertificateFactoryProvider certificateFactoryProvider) { this.cmpClient = cmpClient; - this.csrMetaBuilder = csrMetaBuilder; this.rsaContentSignerBuilder = rsaContentSignerBuilder; this.x509CertificateBuilder = x509CertificateBuilder; this.certificateFactoryProvider = certificateFactoryProvider; @@ -82,7 +81,7 @@ public class Cmpv2ClientAdapter { public CertificationModel callCmpClient(CsrModel csrModel, Cmpv2Server server) throws CmpClientException, Cmpv2ClientAdapterException { List> certificates = cmpClient.createCertificate(server.getCaName(), - server.getCaMode().getProfile(), csrMetaBuilder.build(csrModel, server), + server.getCaMode().getProfile(), csrModel, server, convertCsrToX509Certificate(csrModel.getCsr(), csrModel.getPrivateKey())); return new CertificationModel(convertFromX509CertificateListToPemList(certificates.get(0)), convertFromX509CertificateListToPemList(certificates.get(1))); @@ -106,7 +105,7 @@ public class Cmpv2ClientAdapter { ContentSigner signer = rsaContentSignerBuilder.build(csr, privateKey); X509CertificateHolder holder = certificateGenerator.build(signer); return certificateFactoryProvider - .generateCertificate(new ByteArrayInputStream(holder.toASN1Structure().getEncoded())); + .generateCertificate(new ByteArrayInputStream(holder.toASN1Structure().getEncoded())); } catch (IOException | CertificateException | OperatorCreationException | NoSuchProviderException e) { throw new Cmpv2ClientAdapterException(e); } @@ -114,7 +113,7 @@ public class Cmpv2ClientAdapter { private List convertFromX509CertificateListToPemList(List certificates) { return certificates.stream().map(this::convertFromX509CertificateToPem).filter(cert -> !cert.isEmpty()) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } } diff --git a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilder.java b/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilder.java deleted file mode 100644 index cf35efa1..00000000 --- a/certService/src/main/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilder.java +++ /dev/null @@ -1,90 +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.security.KeyPair; -import java.util.Arrays; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.bouncycastle.asn1.x500.AttributeTypeAndValue; -import org.bouncycastle.asn1.x500.style.BCStyle; -import org.bouncycastle.asn1.x500.style.IETFUtils; -import org.bouncycastle.cert.CertException; -import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server; -import org.onap.aaf.certservice.certification.model.CsrModel; -import org.onap.aaf.certservice.cmpv2client.external.CsrMeta; -import org.onap.aaf.certservice.cmpv2client.external.Rdn; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -class CsrMetaBuilder { - - private static final Logger LOGGER = LoggerFactory.getLogger(CsrMetaBuilder.class); - - /** - * Creates CSRMeta from CsrModel and Cmpv2Server - * - * @param csrModel Certificate Signing Request from Service external API - * @param server Cmp Server configuration from cmpServers.json - * @return AAF native model for CSR metadata - */ - CsrMeta build(CsrModel csrModel, Cmpv2Server server) { - CsrMeta csrMeta = createCsrMeta(csrModel); - addSans(csrModel, csrMeta); - csrMeta.setKeyPair(new KeyPair(csrModel.getPublicKey(), csrModel.getPrivateKey())); - csrMeta.setPassword(server.getAuthentication().getIak()); - csrMeta.setIssuerName(server.getIssuerDN()); - csrMeta.setCaUrl(server.getUrl()); - csrMeta.setName(csrModel.getSubjectData()); - csrMeta.setSenderKid(server.getAuthentication().getRv()); - return csrMeta; - } - - private CsrMeta createCsrMeta(CsrModel csrModel) { - return new CsrMeta((Arrays.stream(csrModel.getSubjectData().getRDNs()).map(this::convertFromBcRdn) - .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()))); - } - - private void addSans(CsrModel csrModel, CsrMeta csrMeta) { - csrModel.getSans().forEach(csrMeta::addSan); - } - - private Optional convertFromBcRdn(org.bouncycastle.asn1.x500.RDN rdn) { - Rdn result = null; - try { - result = convertRdn(rdn); - } catch (CertException e) { - LOGGER.error("Exception occurred during convert of RDN", e); - } - return Optional.ofNullable(result); - } - - private Rdn convertRdn(org.bouncycastle.asn1.x500.RDN rdn) throws CertException { - AttributeTypeAndValue rdnData = rdn.getFirst(); - String tag = BCStyle.INSTANCE.oidToDisplayName(rdnData.getType()); - String value = IETFUtils.valueToString(rdnData.getValue()); - return new Rdn(tag, value); - } - -} diff --git a/certService/src/main/java/org/onap/aaf/certservice/certification/model/CsrModel.java b/certService/src/main/java/org/onap/aaf/certservice/certification/model/CsrModel.java index a29658f4..d81da10a 100644 --- a/certService/src/main/java/org/onap/aaf/certservice/certification/model/CsrModel.java +++ b/certService/src/main/java/org/onap/aaf/certservice/certification/model/CsrModel.java @@ -55,8 +55,8 @@ public class CsrModel { private final PublicKey publicKey; private final List sans; - CsrModel(PKCS10CertificationRequest csr, X500Name subjectData, PrivateKey privateKey, PublicKey publicKey, - List sans) { + public CsrModel(PKCS10CertificationRequest csr, X500Name subjectData, PrivateKey privateKey, PublicKey publicKey, + List sans) { this.csr = csr; this.subjectData = subjectData; this.privateKey = privateKey; 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 8f9d20bd..7de3b712 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 @@ -24,8 +24,9 @@ import java.security.cert.X509Certificate; import java.util.Date; import java.util.List; +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; -import org.onap.aaf.certservice.cmpv2client.external.CsrMeta; /** * This class represent CmpV2Client Interface for obtaining X.509 Digital Certificates in a Public @@ -34,53 +35,57 @@ import org.onap.aaf.certservice.cmpv2client.external.CsrMeta; */ public interface CmpClient { - /** - * Requests for a External Root CA Certificate to be created for the passed public keyPair wrapped - * in a CSRMeta with common details, accepts self-signed certificate. Basic Authentication using - * 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 csrMeta Certificate Signing Request Meta Data. 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 - * after this date. - * @return {@link X509Certificate} The newly created Certificate. - * @throws CmpClientException if client error occurs. - */ - List> createCertificate( - String caName, - String profile, - CsrMeta csrMeta, - X509Certificate csr, - Date notBefore, - Date notAfter) - throws CmpClientException; + /** + * Requests for a External Root CA Certificate to be created for the passed public keyPair wrapped + * in a CSRMeta with common details, accepts self-signed certificate. Basic Authentication using + * 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 + * after this date. + * @return {@link X509Certificate} The newly created Certificate. + * @throws CmpClientException if client error occurs. + */ + List> createCertificate( + String caName, + String profile, + CsrModel csrModel, + Cmpv2Server server, + X509Certificate csr, + Date notBefore, + Date notAfter) + throws CmpClientException; - /** - * Requests for a External Root CA Certificate to be created for the passed public keyPair wrapped - * in a CSRMeta with common details, accepts self-signed certificate. Basic Authentication using - * 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 csrMeta Certificate Signing Request Meta Data. 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> createCertificate( - String caName, - String profile, - CsrMeta csrMeta, - X509Certificate csr) - throws CmpClientException; + /** + * Requests for a External Root CA Certificate to be created for the passed public keyPair wrapped + * in a CSRMeta with common details, accepts self-signed certificate. Basic Authentication using + * 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> createCertificate( + String caName, + String profile, + CsrModel csrModel, + Cmpv2Server server, + X509Certificate csr) + throws CmpClientException; } diff --git a/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/external/CsrMeta.java b/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/external/CsrMeta.java deleted file mode 100644 index 4c4e784c..00000000 --- a/certService/src/main/java/org/onap/aaf/certservice/cmpv2client/external/CsrMeta.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * - * Modifications Copyright (C) 2019 IBM. - * =========================================================================== - * 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.cmpv2client.external; - -import java.security.KeyPair; -import java.util.ArrayList; -import java.util.List; - -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x500.X500NameBuilder; -import org.bouncycastle.asn1.x500.style.BCStyle; -import org.bouncycastle.asn1.x509.Certificate; - -public class CsrMeta { - - private String cn; - private String mechID; - private String environment; - private String email; - private String challenge; - private String issuerCn; - private String issuerEmail; - private String password; - private String caUrl; - private List rdns; - private ArrayList sanList = new ArrayList<>(); - private KeyPair keyPair; - private X500Name name; - private X500Name issuerName; - private Certificate certificate; - private String senderKid; - - public CsrMeta(List rdns) { - this.rdns = rdns; - } - - public X500Name getX500Name() { - if (name == null) { - X500NameBuilder nameBuilder = new X500NameBuilder(); - nameBuilder.addRDN(BCStyle.CN, cn); - nameBuilder.addRDN(BCStyle.E, email); - if (mechID != null) { - if (environment == null) { - nameBuilder.addRDN(BCStyle.OU, mechID); - } else { - nameBuilder.addRDN(BCStyle.OU, mechID + ':' + environment); - } - } - for (Rdn rdn : rdns) { - nameBuilder.addRDN(rdn.getAoi(), rdn.getValue()); - } - name = nameBuilder.build(); - } - return name; - } - - public X500Name getIssuerX500Name() { - if (issuerName == null) { - X500NameBuilder xnb = new X500NameBuilder(); - xnb.addRDN(BCStyle.CN, issuerCn); - if (issuerEmail != null) { - xnb.addRDN(BCStyle.E, issuerEmail); - } - issuerName = xnb.build(); - } - return issuerName; - } - - public void addSan(String san) { - sanList.add(san); - } - - public List getSans() { - return sanList; - } - - public KeyPair getKeyPairOrGenerateIfNull() { - if (keyPair == null) { - keyPair = Factory.generateKeyPair(); - } - return keyPair; - } - - public KeyPair getKeyPair() { - return keyPair; - } - - public void setKeyPair(KeyPair keyPair) { - this.keyPair = keyPair; - } - - public String getCn() { - return cn; - } - - public void setCn(String cn) { - this.cn = cn; - } - - public void setEnvironment(String env) { - environment = env; - } - - public String getEnvironment() { - return environment; - } - - public String getMechID() { - return mechID; - } - - public void setMechID(String mechID) { - this.mechID = mechID; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getChallenge() { - return challenge; - } - - public void setChallenge(String challenge) { - this.challenge = challenge; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getPassword() { - return password; - } - - public void setCertificate(Certificate certificate) { - this.certificate = certificate; - } - - public Certificate getCertificate() { - return certificate; - } - - public void setIssuerCn(String issuerCn) { - this.issuerCn = issuerCn; - } - - public String getCaUrl() { - return caUrl; - } - - public void setCaUrl(String caUrl) { - this.caUrl = caUrl; - } - - public String getSenderKid() { - return senderKid; - } - - public void setSenderKid(String senderKid) { - this.senderKid = senderKid; - } - - public String getIssuerCn() { - return issuerCn; - } - - public String getIssuerEmail() { - return issuerEmail; - } - - public void setIssuerEmail(String issuerEmail) { - this.issuerEmail = issuerEmail; - } - - public void setIssuerName(X500Name issuerName) { - this.issuerName = issuerName; - } - - public void setName(X500Name name) { - this.name = name; - } -} 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 39a0877c..79656e91 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 @@ -20,6 +20,7 @@ package org.onap.aaf.certservice.cmpv2client.impl; +import java.security.KeyPair; import java.security.PublicKey; import static org.onap.aaf.certservice.cmpv2client.impl.CmpResponseHelper.checkIfCmpResponseContainsError; @@ -47,9 +48,10 @@ 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.Cmpv2Server; +import org.onap.aaf.certservice.certification.model.CsrModel; import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException; import org.onap.aaf.certservice.cmpv2client.api.CmpClient; -import org.onap.aaf.certservice.cmpv2client.external.CsrMeta; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,36 +75,38 @@ public class CmpClientImpl implements CmpClient { public List> createCertificate( String caName, String profile, - CsrMeta csrMeta, + CsrModel csrModel, + Cmpv2Server server, X509Certificate cert, Date notBefore, Date notAfter) throws CmpClientException { - // Validate inputs for Certificate Request - validate(csrMeta, cert, caName, profile, httpClient, notBefore, notAfter); + + validate(csrModel, server, cert, caName, profile, httpClient, notBefore, notAfter); + KeyPair keyPair = new KeyPair(csrModel.getPublicKey(), csrModel.getPrivateKey()); final CreateCertRequest certRequest = CmpMessageBuilder.of(CreateCertRequest::new) - .with(CreateCertRequest::setIssuerDn, csrMeta.getIssuerX500Name()) - .with(CreateCertRequest::setSubjectDn, csrMeta.getX500Name()) - .with(CreateCertRequest::setSansList, csrMeta.getSans()) - .with(CreateCertRequest::setSubjectKeyPair, csrMeta.getKeyPair()) + .with(CreateCertRequest::setIssuerDn, server.getIssuerDN()) + .with(CreateCertRequest::setSubjectDn, csrModel.getSubjectData()) + .with(CreateCertRequest::setSansList, csrModel.getSans()) + .with(CreateCertRequest::setSubjectKeyPair, keyPair) .with(CreateCertRequest::setNotBefore, notBefore) .with(CreateCertRequest::setNotAfter, notAfter) - .with(CreateCertRequest::setInitAuthPassword, csrMeta.getPassword()) - .with(CreateCertRequest::setSenderKid, csrMeta.getSenderKid()) + .with(CreateCertRequest::setInitAuthPassword, server.getAuthentication().getIak()) + .with(CreateCertRequest::setSenderKid, server.getAuthentication().getRv()) .build(); final PKIMessage pkiMessage = certRequest.generateCertReq(); Cmpv2HttpClient cmpv2HttpClient = new Cmpv2HttpClient(httpClient); - return retrieveCertificates(caName, csrMeta, pkiMessage, cmpv2HttpClient); + return retrieveCertificates(caName, csrModel, server, pkiMessage, cmpv2HttpClient); } @Override public List> createCertificate( - String caName, String profile, CsrMeta csrMeta, X509Certificate csr) + String caName, String profile, CsrModel csrModel, Cmpv2Server server, X509Certificate csr) throws CmpClientException { - return createCertificate(caName, profile, csrMeta, csr, null, null); + return createCertificate(caName, profile, csrModel, server, csr, null, null); } private void checkCmpResponse( @@ -191,14 +195,16 @@ public class CmpClientImpl implements CmpClient { /** * Validate inputs for Certificate Creation. * - * @param csrMeta CSRMeta Object containing variables for creating a Certificate Request. + * @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 void validate( - final CsrMeta csrMeta, + private static void validate( + final CsrModel csrModel, + final Cmpv2Server server, final X509Certificate cert, final String incomingCaName, final String incomingProfile, @@ -206,20 +212,19 @@ public class CmpClientImpl implements CmpClient { final Date notBefore, final Date notAfter) { - String caName; - String caProfile; - caName = CmpUtil.isNullOrEmpty(incomingCaName) ? incomingCaName : DEFAULT_CA_NAME; - caProfile = CmpUtil.isNullOrEmpty(incomingProfile) ? incomingProfile : DEFAULT_PROFILE; + String caName = CmpUtil.isNullOrEmpty(incomingCaName) ? incomingCaName : DEFAULT_CA_NAME; + String caProfile = CmpUtil.isNullOrEmpty(incomingProfile) ? incomingProfile : DEFAULT_PROFILE; LOG.info( "Validate before creating Certificate Request for CA :{} in Mode {} ", caName, caProfile); - CmpUtil.notNull(csrMeta, "CSRMeta Instance"); - CmpUtil.notNull(csrMeta.getX500Name(), "Subject DN"); - CmpUtil.notNull(csrMeta.getIssuerX500Name(), "Issuer DN"); - CmpUtil.notNull(csrMeta.getPassword(), "IAK/RV Password"); + CmpUtil.notNull(csrModel, "CsrModel Instance"); + CmpUtil.notNull(csrModel.getSubjectData(), "Subject DN"); + CmpUtil.notNull(csrModel.getPrivateKey(), "Subject private key"); + CmpUtil.notNull(csrModel.getPublicKey(), "Subject public key"); + 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(csrMeta.getCaUrl(), "External CA URL"); - CmpUtil.notNull(csrMeta.getKeyPairOrGenerateIfNull(), "Subject KeyPair"); CmpUtil.notNull(httpClient, "Closeable Http Client"); if (notBefore != null && notAfter != null && notBefore.compareTo(notAfter) > 0) { @@ -228,14 +233,14 @@ public class CmpClientImpl implements CmpClient { } private List> retrieveCertificates( - String caName, CsrMeta csrMeta, PKIMessage pkiMessage, Cmpv2HttpClient cmpv2HttpClient) + String caName, CsrModel csrModel, Cmpv2Server server, PKIMessage pkiMessage, Cmpv2HttpClient cmpv2HttpClient) throws CmpClientException { - final byte[] respBytes = cmpv2HttpClient.postRequest(pkiMessage, csrMeta.getCaUrl(), caName); + final byte[] respBytes = cmpv2HttpClient.postRequest(pkiMessage, server.getUrl(), caName); try { final PKIMessage respPkiMessage = PKIMessage.getInstance(respBytes); LOG.info("Received response from Server"); checkIfCmpResponseContainsError(respPkiMessage); - checkCmpResponse(respPkiMessage, csrMeta.getKeyPairOrGenerateIfNull().getPublic(), csrMeta.getPassword()); + checkCmpResponse(respPkiMessage, csrModel.getPublicKey(), server.getAuthentication().getIak()); return checkCmpCertRepMessage(respPkiMessage); } catch (IllegalArgumentException iae) { CmpClientException cmpClientException = 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 index 32fd2074..e18d1ffb 100644 --- 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 @@ -51,7 +51,6 @@ 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.onap.aaf.certservice.cmpv2client.external.CsrMeta; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest @@ -83,10 +82,6 @@ class Cmpv2ClientAdapterTest { private X509Certificate certificate; @Mock private CertificateFactoryProvider certificateFactoryProvider; - @Mock - private CsrMetaBuilder csrMetaBuilder; - @Mock - private CsrMeta csrMeta; @InjectMocks private Cmpv2ClientAdapter adapter; @@ -102,7 +97,7 @@ class Cmpv2ClientAdapterTest { stubInternalProperties(); // When - Mockito.when(cmpClient.createCertificate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(cmpClient.createCertificate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenThrow(new CmpClientException(TEST_MSG)); // Then @@ -117,7 +112,7 @@ class Cmpv2ClientAdapterTest { stubInternalProperties(); // When - Mockito.when(cmpClient.createCertificate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(cmpClient.createCertificate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(createCorrectClientResponse()); CertificationModel certificationModel = adapter.callCmpClient(csrModel, server); @@ -144,7 +139,7 @@ class Cmpv2ClientAdapterTest { stubInternalProperties(); // When - Mockito.when(cmpClient.createCertificate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + 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)); @@ -179,7 +174,6 @@ class Cmpv2ClientAdapterTest { Mockito.when(holder.toASN1Structure()).thenReturn(asn1Certificate); Mockito.when(certificateFactoryProvider.generateCertificate(Mockito.any())).thenReturn(certificate); Mockito.when(holder.toASN1Structure().getEncoded()).thenReturn("".getBytes()); - Mockito.when(csrMetaBuilder.build(csrModel, server)).thenReturn(csrMeta); } } diff --git a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilderTest.java b/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilderTest.java deleted file mode 100644 index feb4bdba..00000000 --- a/certService/src/test/java/org/onap/aaf/certservice/certification/adapter/CsrMetaBuilderTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * AAF Certification 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 org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.aaf.certservice.certification.configuration.model.Authentication; -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.external.CsrMeta; - -import java.security.PrivateKey; -import java.security.PublicKey; -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class CsrMetaBuilderTest { - - private CsrMetaBuilder csrMetaBuilder; - - private static final String TEST_CA = "testCA"; - private static final X500Name TEST_SUBJECT_DATA = new X500Name("CN=testIssuer"); - - @BeforeEach - void setUp() { - csrMetaBuilder = new CsrMetaBuilder(); - } - - @Test - void shouldBuildCsrMetaWhenGivenCsrModelAndCmpv2ServerAreCorrect() { - // Given - CsrModel testCsrModel = mock(CsrModel.class); - Cmpv2Server testServer = createTestServer(); - - PKCS10CertificationRequest certificationRequest = mock(PKCS10CertificationRequest.class); - when(testCsrModel.getCsr()).thenReturn(certificationRequest); - PrivateKey mockPrivateKey = mock(PrivateKey.class); - when(testCsrModel.getPrivateKey()).thenReturn(mockPrivateKey); - PublicKey mockPublicKey = mock(PublicKey.class); - when(testCsrModel.getPublicKey()).thenReturn(mockPublicKey); - List testSans = Arrays.asList("SAN01", "SAN02"); - when(testCsrModel.getSans()).thenReturn(testSans); - - when(testCsrModel.getSubjectData()).thenReturn(TEST_SUBJECT_DATA); - - // When - CsrMeta createdCsrMeta = csrMetaBuilder.build(testCsrModel, testServer); - - // Then - assertThat(createdCsrMeta.getPassword()).isEqualTo(testServer.getAuthentication().getIak()); - assertThat(createdCsrMeta.getSenderKid()).isEqualTo(testServer.getAuthentication().getRv()); - assertThat(createdCsrMeta.getCaUrl()).isEqualTo(testServer.getUrl()); - assertThat(createdCsrMeta.getSans()).containsAll(testSans); - assertThat(createdCsrMeta.getKeyPair().getPrivate()).isEqualTo(mockPrivateKey); - assertThat(createdCsrMeta.getKeyPair().getPublic()).isEqualTo(mockPublicKey); - assertThat(createdCsrMeta.getX500Name()).isEqualTo(TEST_SUBJECT_DATA); - assertThat(createdCsrMeta.getIssuerX500Name()).isEqualTo(TEST_SUBJECT_DATA); - } - - private Cmpv2Server createTestServer() { - Cmpv2Server testServer = new Cmpv2Server(); - testServer.setCaName(TEST_CA); - testServer.setIssuerDN(TEST_SUBJECT_DATA); - testServer.setUrl("http://test.ca.server"); - Authentication testAuthentication = new Authentication(); - testAuthentication.setIak("testIak"); - testAuthentication.setRv("testRv"); - testServer.setAuthentication(testAuthentication); - testServer.setCaMode(CaMode.RA); - - return testServer; - } - -} 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 3f5a2540..bea6b6a1 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 @@ -30,7 +30,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.security.KeyFactory; import java.security.KeyPair; -import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; @@ -42,7 +41,7 @@ import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; +import java.util.Collections; import java.util.Date; import java.util.List; @@ -50,15 +49,18 @@ import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.impl.client.CloseableHttpClient; -import org.bouncycastle.cert.CertException; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.X500NameBuilder; +import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; +import org.onap.aaf.certservice.certification.configuration.model.Authentication; +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; -import org.onap.aaf.certservice.cmpv2client.external.CsrMeta; -import org.onap.aaf.certservice.cmpv2client.external.Rdn; import org.onap.aaf.certservice.cmpv2client.impl.CmpClientImpl; class Cmpv2ClientTest { @@ -67,12 +69,11 @@ class Cmpv2ClientTest { Security.addProvider(new BouncyCastleProvider()); } - private CsrMeta csrMeta; + private CsrModel csrModel; + private Cmpv2Server server; private Date notBefore; private Date notAfter; - - @Mock - KeyPairGenerator kpg; + private X500Name dn; @Mock X509Certificate cert; @@ -87,22 +88,15 @@ class Cmpv2ClientTest { HttpEntity httpEntity; private static KeyPair keyPair; - private static ArrayList rdns; @BeforeEach void setUp() throws NoSuchProviderException, NoSuchAlgorithmException, IOException, InvalidKeySpecException { - KeyPairGenerator keyGenerator; - keyGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); - keyGenerator.initialize(2048); keyPair = loadKeyPair(); - rdns = new ArrayList<>(); - try { - rdns.add(new Rdn("O=CommonCompany")); - } catch (CertException e) { - e.printStackTrace(); - } + dn = new X500NameBuilder() + .addRDN(BCStyle.O, "TestOrganization") + .build(); initMocks(this); } @@ -133,15 +127,10 @@ class Cmpv2ClientTest { // given Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=CommonName", - "CN=ManagementCA", - "CommonName.com", - "CommonName@cn.com", + setCsrModelAndServerValues( "mypassword", - "http://127.0.0.1/ejbca/publicweb/cmp/cmp", "senderKID", + "http://127.0.0.1/ejbca/publicweb/cmp/cmp", beforeDate, afterDate); when(httpClient.execute(any())).thenReturn(httpResponse); @@ -164,7 +153,7 @@ class Cmpv2ClientTest { CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient)); // when List> cmpClientResult = - cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter); + cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter); // then assertNotNull(cmpClientResult); } @@ -176,15 +165,10 @@ class Cmpv2ClientTest { // given Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=CommonName", - "CN=ManagementCA", - "CommonName.com", - "CommonName@cn.com", + setCsrModelAndServerValues( "password", - "http://127.0.0.1/ejbca/publicweb/cmp/cmp", "senderKID", + "http://127.0.0.1/ejbca/publicweb/cmp/cmp", beforeDate, afterDate); when(httpClient.execute(any())).thenReturn(httpResponse); @@ -208,7 +192,7 @@ class Cmpv2ClientTest { // then Assertions.assertThrows( CmpClientException.class, - () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); + () -> cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter)); } @Test @@ -217,15 +201,10 @@ class Cmpv2ClientTest { // given Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=CommonName", - "CN=ManagementCA", - "CommonName.com", - "CommonName@cn.com", + setCsrModelAndServerValues( "password", - "http://127.0.0.1/ejbca/publicweb/cmp/cmp", "senderKID", + "http://127.0.0.1/ejbca/publicweb/cmp/cmp", beforeDate, afterDate); when(httpClient.execute(any())).thenReturn(httpResponse); @@ -250,7 +229,7 @@ class Cmpv2ClientTest { // then Assertions.assertThrows( CmpClientException.class, - () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); + () -> cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter)); } @Test @@ -259,22 +238,17 @@ class Cmpv2ClientTest { // given Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=CommonName", - "CN=ManagementCA", - "CommonName.com", - "CommonName@cn.com", + setCsrModelAndServerValues( "password", - "http://127.0.0.1/ejbca/publicweb/cmp/cmp", "senderKID", + "http://127.0.0.1/ejbca/publicweb/cmp/cmp", beforeDate, afterDate); CmpClientImpl cmpClient = new CmpClientImpl(httpClient); // then Assertions.assertThrows( IllegalArgumentException.class, - () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); + () -> cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter)); } @Test @@ -283,15 +257,10 @@ class Cmpv2ClientTest { // given Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00"); Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00"); - setCsrMetaValuesAndDateValues( - rdns, - "CN=Common", - "CN=CommonCA", - "Common.com", - "Common@cn.com", + setCsrModelAndServerValues( "myPassword", - "http://127.0.0.1/ejbca/publicweb/cmp/cmpTest", "sender", + "http://127.0.0.1/ejbca/publicweb/cmp/cmpTest", beforeDate, afterDate); when(httpClient.execute(any())).thenThrow(IOException.class); @@ -299,30 +268,19 @@ class Cmpv2ClientTest { // then Assertions.assertThrows( CmpClientException.class, - () -> cmpClient.createCertificate("data", "RA", csrMeta, cert, notBefore, notAfter)); + () -> cmpClient.createCertificate("data", "RA", csrModel, server, cert, notBefore, notAfter)); } - private void setCsrMetaValuesAndDateValues( - List rdns, - String cn, - String issuerCn, - String san, - String email, - String password, - String externalCaUrl, - String senderKid, - Date notBefore, - Date notAfter) { - csrMeta = new CsrMeta(rdns); - csrMeta.setCn(cn); - csrMeta.addSan(san); - csrMeta.setPassword(password); - csrMeta.setEmail(email); - csrMeta.setIssuerCn(issuerCn); - when(kpg.generateKeyPair()).thenReturn(keyPair); - csrMeta.getKeyPairOrGenerateIfNull(); - csrMeta.setCaUrl(externalCaUrl); - csrMeta.setSenderKid(senderKid); + private void setCsrModelAndServerValues(String iak, String rv, String externalCaUrl, Date notBefore, Date notAfter) { + csrModel = new CsrModel(null, dn, keyPair.getPrivate(), keyPair.getPublic(), Collections.emptyList()); + + Authentication authentication = new Authentication(); + authentication.setIak(iak); + authentication.setRv(rv); + server = new Cmpv2Server(); + server.setAuthentication(authentication); + server.setUrl(externalCaUrl); + server.setIssuerDN(dn); this.notBefore = notBefore; this.notAfter = notAfter; } -- 2.16.6