[OOM-CERT-SERVICE] Fix sonar and checkstyle issues, code cleanup
[oom/platform/cert-service.git] / certService / src / main / java / org / onap / oom / certservice / api / CertificationController.java
1 /*
2  * ============LICENSE_START=======================================================
3  * Cert Service
4  * ================================================================================
5  * Copyright (C) 2020-2021 Nokia. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.oom.certservice.api;
22
23 import io.swagger.v3.oas.annotations.Operation;
24 import io.swagger.v3.oas.annotations.Parameter;
25 import io.swagger.v3.oas.annotations.media.Content;
26 import io.swagger.v3.oas.annotations.media.Schema;
27 import io.swagger.v3.oas.annotations.responses.ApiResponse;
28 import io.swagger.v3.oas.annotations.responses.ApiResponses;
29 import io.swagger.v3.oas.annotations.tags.Tag;
30 import org.onap.oom.certservice.certification.CertificationResponseModelFactory;
31 import org.onap.oom.certservice.certification.exception.DecryptionException;
32 import org.onap.oom.certservice.certification.exception.ErrorResponseModel;
33 import org.onap.oom.certservice.certification.model.CertificateUpdateModel;
34 import org.onap.oom.certservice.certification.model.CertificationResponseModel;
35 import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.http.HttpStatus;
40 import org.springframework.http.ResponseEntity;
41 import org.springframework.web.bind.annotation.GetMapping;
42 import org.springframework.web.bind.annotation.PathVariable;
43 import org.springframework.web.bind.annotation.RequestHeader;
44 import org.springframework.web.bind.annotation.RestController;
45
46
47 @RestController
48 @Tag(name = "CertificationService")
49 public class CertificationController {
50
51     private static final Logger LOGGER = LoggerFactory.getLogger(CertificationController.class);
52
53     private final CertificationResponseModelFactory certificationResponseModelFactory;
54
55     @Autowired
56     CertificationController(CertificationResponseModelFactory certificationResponseModelFactory) {
57         this.certificationResponseModelFactory = certificationResponseModelFactory;
58     }
59
60     /**
61      * Request for signing certificate by given CA.
62      *
63      * @param caName            the name of Certification Authority that will sign root certificate
64      * @param encodedCsr        Certificate Sign Request encoded in Base64 form
65      * @param encodedPrivateKey Private key for CSR, needed for PoP, encoded in Base64 form
66      * @return JSON containing trusted certificates and certificate chain
67      */
68     @GetMapping(value = "v1/certificate/{caName}", produces = "application/json")
69     @ApiResponses(value = {
70             @ApiResponse(responseCode = "200", description = "Certificate successfully signed"),
71             @ApiResponse(responseCode = "400", description = "Given CSR or/and PK is incorrect",
72                     content = @Content(schema = @Schema(implementation = ErrorResponseModel.class))),
73             @ApiResponse(responseCode = "404", description = "CA not found for given name",
74                     content = @Content(schema = @Schema(implementation = ErrorResponseModel.class))),
75             @ApiResponse(responseCode = "500", description = "Something went wrong during connectiion to CMPv2 server",
76                     content = @Content(schema = @Schema(implementation = ErrorResponseModel.class)))
77     })
78     @Operation(
79             summary = "sign certificate",
80             description = "Web endpoint for requesting certificate signing. Used by system components to gain certificate signed by CA.",
81             tags = {"CertificationService"})
82     public ResponseEntity<CertificationResponseModel> signCertificate(
83             @Parameter(description = "Name of certification authority that will sign CSR.")
84             @PathVariable String caName,
85             @Parameter(description = "Certificate signing request in form of PEM object encoded in Base64 (with header and footer).")
86             @RequestHeader("CSR") String encodedCsr,
87             @Parameter(description = "Private key in form of PEM object encoded in Base64 (with header and footer).")
88             @RequestHeader("PK") String encodedPrivateKey
89     ) throws DecryptionException, CmpClientException {
90         caName = replaceWhiteSpaceChars(caName);
91         LOGGER.info("Received certificate signing request for CA named: {}", caName);
92         CertificationResponseModel certificationResponseModel = certificationResponseModelFactory
93                 .provideCertificationModelFromInitialRequest(encodedCsr, encodedPrivateKey, caName);
94         return new ResponseEntity<>(certificationResponseModel, HttpStatus.OK);
95     }
96
97     /**
98      * Request for updating certificate by given CA.
99      *
100      * @param caName                the name of Certification Authority that will sign root certificate
101      * @param encodedCsr            Certificate Sign Request encoded in Base64 form
102      * @param encodedPrivateKey     Private key for CSR, needed for PoP, encoded in Base64 form
103      * @param encodedOldCert        Certificate (signed by Certification Authority) that should be renewed
104      * @param encodedOldPrivateKey  Old private key corresponding with old certificate
105      * @return JSON containing trusted certificates and certificate chain
106      */
107     @GetMapping(value = "v1/certificate-update/{caName}", produces = "application/json")
108     public ResponseEntity<CertificationResponseModel> updateCertificate(
109             @PathVariable String caName,
110             @RequestHeader("CSR") String encodedCsr,
111             @RequestHeader("PK") String encodedPrivateKey,
112             @RequestHeader("OLD_CERT") String encodedOldCert,
113             @RequestHeader("OLD_PK") String encodedOldPrivateKey
114     ) throws DecryptionException, CmpClientException {
115         caName = replaceWhiteSpaceChars(caName);
116         LOGGER.info("Received certificate update request for CA named: {}", caName);
117         CertificateUpdateModel certificateUpdateModel = new CertificateUpdateModel.CertificateUpdateModelBuilder()
118                 .setEncodedCsr(encodedCsr)
119                 .setEncodedPrivateKey(encodedPrivateKey)
120                 .setEncodedOldCert(encodedOldCert)
121                 .setEncodedOldPrivateKey(encodedOldPrivateKey)
122                 .setCaName(caName)
123                 .build();
124         CertificationResponseModel certificationResponseModel = certificationResponseModelFactory
125                 .provideCertificationModelFromUpdateRequest(certificateUpdateModel);
126         return new ResponseEntity<>(certificationResponseModel, HttpStatus.OK);
127     }
128
129     private String replaceWhiteSpaceChars(String text) {
130         return text.replaceAll("[\n\r\t]", "_");
131     }
132 }