Fix security risk 'Improper Input Validation'
[sdc.git] / openecomp-be / lib / openecomp-common-lib / src / main / java / org / openecomp / sdc / common / errors / DefaultExceptionMapper.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openecomp.sdc.common.errors;
17
18 import com.fasterxml.jackson.databind.JsonMappingException;
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Set;
24 import javax.servlet.http.HttpServletResponse;
25 import javax.validation.ConstraintViolation;
26 import javax.validation.ConstraintViolationException;
27 import javax.validation.Path;
28 import javax.ws.rs.core.MediaType;
29 import javax.ws.rs.core.Response;
30 import javax.ws.rs.core.Response.Status;
31 import javax.ws.rs.ext.ExceptionMapper;
32 import org.apache.commons.collections4.CollectionUtils;
33 import org.hibernate.validator.internal.engine.path.PathImpl;
34 import org.onap.sdc.security.RepresentationUtils;
35 import org.openecomp.core.utilities.file.FileUtils;
36 import org.openecomp.core.utilities.json.JsonUtil;
37 import org.openecomp.sdc.exception.NotAllowedSpecialCharsException;
38 import org.openecomp.sdc.exception.ResponseFormat;
39 import org.openecomp.sdc.exception.ServiceException;
40 import org.openecomp.sdc.logging.api.Logger;
41 import org.openecomp.sdc.logging.api.LoggerFactory;
42
43 public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
44
45     private static final String ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE = "errorCodesToResponseStatusMapping.json";
46     @SuppressWarnings("unchecked")
47     private static final Map<String, String> ERROR_CODE_TO_RESPONSE_STATUS = FileUtils
48         .readViaInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE, stream -> JsonUtil.json2Object(stream, Map.class));
49     private static final Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionMapper.class);
50
51     @Override
52     public Response toResponse(Exception exception) {
53         Response response;
54         if (exception instanceof CoreException) {
55             response = transform((CoreException) exception);
56         } else if (exception instanceof ConstraintViolationException) {
57             response = transform((ConstraintViolationException) exception);
58         } else if (exception instanceof JsonMappingException) {
59             response = transform((JsonMappingException) exception);
60         } else {
61             response = transform(exception);
62         }
63         List<Object> contentTypes = new ArrayList<>();
64         contentTypes.add(MediaType.APPLICATION_JSON);
65         response.getMetadata().put("Content-Type", contentTypes);
66         return response;
67     }
68
69     private Response transform(final CoreException coreException) {
70         final ErrorCode code = coreException.code();
71         LOGGER.error(code.message(), coreException);
72         if (coreException.code().category().equals(ErrorCategory.APPLICATION)) {
73             final Status errorStatus = Status.valueOf(ERROR_CODE_TO_RESPONSE_STATUS.get(code.id()));
74             if (List.of(Status.BAD_REQUEST, Status.FORBIDDEN, Status.NOT_FOUND, Status.INTERNAL_SERVER_ERROR).contains(errorStatus)) {
75                 return buildResponse(errorStatus, code);
76             }
77             return buildResponse(Status.EXPECTATION_FAILED, code);
78         }
79         return buildResponse(Status.INTERNAL_SERVER_ERROR, code);
80     }
81
82     private Response buildResponse(final Status status, final ErrorCode code) {
83         return Response.status(status).entity(toEntity(status, code)).build();
84     }
85
86     private Response transform(ConstraintViolationException validationException) {
87         Set<ConstraintViolation<?>> constraintViolationSet = validationException.getConstraintViolations();
88         String message;
89         String fieldName = null;
90         if (CollectionUtils.isEmpty(constraintViolationSet)) {
91             message = validationException.getMessage();
92         } else {
93             // getting the first violation message for the output response.
94             ConstraintViolation<?> constraintViolation = constraintViolationSet.iterator().next();
95             message = constraintViolation.getMessage();
96             fieldName = getFieldName(constraintViolation.getPropertyPath());
97         }
98         ErrorCode validationErrorCode = new ValidationErrorBuilder(message, fieldName).build();
99         LOGGER.error(validationErrorCode.message(), validationException);
100         return buildResponse(Status.EXPECTATION_FAILED, validationErrorCode);
101     }
102
103     private Response transform(JsonMappingException jsonMappingException) {
104         ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build();
105         LOGGER.error(jsonMappingErrorCode.message(), jsonMappingException);
106         return buildResponse(Status.EXPECTATION_FAILED, jsonMappingErrorCode);
107     }
108
109     private Response transform(Exception exception) {
110         ErrorCode errorCode = new GeneralErrorBuilder().build();
111         LOGGER.error(errorCode.message(), exception);
112         return buildResponse(Status.INTERNAL_SERVER_ERROR, errorCode);
113     }
114
115     private String getFieldName(Path propertyPath) {
116         return ((PathImpl) propertyPath).getLeafNode().toString();
117     }
118
119     private Object toEntity(final Status status, final ErrorCode code) {
120         return new ErrorCodeAndMessage(status, code);
121     }
122
123     public void writeToResponse(final NotAllowedSpecialCharsException e, final HttpServletResponse httpResponse) throws IOException {
124         final ResponseFormat responseFormat = new ResponseFormat(400);
125         responseFormat.setServiceException(new ServiceException(e.getErrorId(), e.getMessage(), new String[0]));
126         httpResponse.setStatus(responseFormat.getStatus());
127         httpResponse.setContentType("application/json");
128         httpResponse.setCharacterEncoding("UTF-8");
129         httpResponse.getWriter().write(RepresentationUtils.toRepresentation(responseFormat.getRequestError()));
130     }
131
132 }