Remove legacy certificate handling
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / externalapi / servlet / ServiceActivationServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. 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 package org.openecomp.sdc.be.externalapi.servlet;
21
22 import com.fasterxml.jackson.databind.ObjectMapper;
23 import com.jcabi.aspects.Loggable;
24 import fj.data.Either;
25 import io.swagger.v3.oas.annotations.Operation;
26 import io.swagger.v3.oas.annotations.Parameter;
27 import io.swagger.v3.oas.annotations.responses.ApiResponse;
28 import io.swagger.v3.oas.annotations.servers.Server;
29 import io.swagger.v3.oas.annotations.tags.Tag;
30 import java.io.IOException;
31 import javax.inject.Inject;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.ws.rs.Consumes;
34 import javax.ws.rs.HeaderParam;
35 import javax.ws.rs.POST;
36 import javax.ws.rs.Path;
37 import javax.ws.rs.PathParam;
38 import javax.ws.rs.Produces;
39 import javax.ws.rs.core.Context;
40 import javax.ws.rs.core.MediaType;
41 import javax.ws.rs.core.Response;
42 import org.apache.commons.lang3.StringUtils;
43 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
44 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
45 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
46 import org.openecomp.sdc.be.config.BeEcompErrorManager;
47 import org.openecomp.sdc.be.dao.api.ActionStatus;
48 import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
49 import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionRespInfo;
50 import org.openecomp.sdc.be.impl.ComponentsUtils;
51 import org.openecomp.sdc.be.impl.ServletUtils;
52 import org.openecomp.sdc.be.model.User;
53 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
54 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
55 import org.openecomp.sdc.be.servlets.RepresentationUtils;
56 import org.openecomp.sdc.common.api.Constants;
57 import org.openecomp.sdc.common.datastructure.Wrapper;
58 import org.openecomp.sdc.common.log.wrappers.Logger;
59 import org.openecomp.sdc.exception.ResponseFormat;
60 import org.springframework.stereotype.Controller;
61
62 /**
63  * Created by chaya on 10/17/2017.
64  */
65 @SuppressWarnings("ALL")
66 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
67 @Path("/v1/catalog")
68 @Tag(name = "SDCE-7 APIs")
69 @Server(url = "/sdc")
70 @Controller
71 public class ServiceActivationServlet extends AbstractValidationsServlet {
72
73     private static final Logger log = Logger.getLogger(ServiceActivationServlet.class);
74     private final ServiceBusinessLogic serviceBusinessLogic;
75     @Context
76     private HttpServletRequest request;
77
78     @Inject
79     public ServiceActivationServlet(ComponentInstanceBusinessLogic componentInstanceBL,
80                                     ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
81                                     ServiceBusinessLogic serviceBusinessLogic) {
82         super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
83         this.serviceBusinessLogic = serviceBusinessLogic;
84     }
85
86     /**
87      * Activates a service on a specific environment
88      */
89     @POST
90     @Path("/services/{serviceUUID}/distribution/{opEnvId}/activate")
91     @Consumes(MediaType.APPLICATION_JSON)
92     @Produces(MediaType.APPLICATION_JSON)
93     @Operation(description = "activate a service", method = "POST", summary = "Activates a service", responses = {
94         @ApiResponse(responseCode = "202", description = "ECOMP component is authenticated and required service may be distributed"),
95         @ApiResponse(responseCode = "400", description = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),
96         @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
97         @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
98         @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
99         @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
100         @ApiResponse(responseCode = "500", description = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
101         @ApiResponse(responseCode = "400", description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
102         @ApiResponse(responseCode = "400", description = "Missing request body. The post request did not contain the expected body - SVC4500"),
103         @ApiResponse(responseCode = "400", description = "The resource name is missing in the request body - SVC4062"),
104         @ApiResponse(responseCode = "409", description = "Service state is invalid for this action"),
105         @ApiResponse(responseCode = "502", description = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")})
106     public Response activateServiceExternal(
107         @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
108         @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
109         @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
110         @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
111         @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
112         @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
113         @Parameter(description = "The serviceUUid to activate", required = true) @PathParam("serviceUUID") final String serviceUUID,
114         @Parameter(description = "The operational environment on which to activate the service on", required = true) @PathParam("opEnvId") final String opEnvId,
115         String data) throws IOException {
116         init();
117         ResponseFormat responseFormat = null;
118         String requestURI = request.getRequestURI();
119         String url = request.getMethod() + " " + requestURI;
120         log.debug("Start handle request of {}", url);
121         User modifier = new User();
122         try {
123             Wrapper<ResponseFormat> responseWrapper = validateRequestHeaders(instanceIdHeader, userId);
124             if (responseWrapper.isEmpty()) {
125                 modifier.setUserId(userId);
126                 log.debug("modifier id is {}", userId);
127                 ServiceDistributionReqInfo reqMetadata = convertJsonToActivationMetadata(data);
128                 Either<String, ResponseFormat> distResponse = serviceBusinessLogic
129                     .activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata);
130                 if (distResponse.isRight()) {
131                     log.debug("failed to activate service distribution");
132                     responseFormat = distResponse.right().value();
133                     return buildErrorResponse(responseFormat);
134                 }
135                 String distributionId = distResponse.left().value();
136                 Object result = RepresentationUtils.toRepresentation(new ServiceDistributionRespInfo(distributionId));
137                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.ACCEPTED);
138                 return buildOkResponse(responseFormat, result);
139             } else {
140                 log.debug("request instanceId/userId header validation failed");
141                 responseFormat = responseWrapper.getInnerElement();
142                 return buildErrorResponse(responseFormat);
143             }
144         } catch (Exception e) {
145             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
146             log.debug("activate distribution failed with exception", e);
147             throw e;
148         } finally {
149             getComponentsUtils()
150                 .auditExternalActivateService(responseFormat, new DistributionData(instanceIdHeader, requestURI), requestId, serviceUUID, modifier);
151         }
152     }
153
154     private Wrapper<ResponseFormat> validateRequestHeaders(String instanceIdHeader, String userId) {
155         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
156         if (responseWrapper.isEmpty()) {
157             validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
158         }
159         if (responseWrapper.isEmpty()) {
160             validateHttpCspUserIdHeader(userId, responseWrapper);
161         }
162         return responseWrapper;
163     }
164
165     private ServiceDistributionReqInfo convertJsonToActivationMetadata(String data) {
166         ObjectMapper mapper = new ObjectMapper();
167         try {
168             return mapper.readValue(data, ServiceDistributionReqInfo.class);
169         } catch (IOException e) {
170             log.error("#convertJsonToActivationMetadata - json deserialization failed with error: ", e);
171             return new ServiceDistributionReqInfo(null);
172         }
173     }
174
175     @Override
176     protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {
177         ResponseFormat responseFormat;
178         if (StringUtils.isEmpty(header)) {
179             log.debug("MissingUSER_ID");
180             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
181             responseWrapper.setInnerElement(responseFormat);
182         }
183     }
184 }