[POLICY-117] Resolve the Policy Critical issues
[policy/engine.git] / ECOMP-PDP / src / main / java / org / openecomp / policy / xacml / action / FindAction.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PDP
4  * ================================================================================
5  * Copyright (C) 2017 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.policy.xacml.action;
21
22 import java.io.BufferedReader;
23 import java.io.InputStreamReader;
24 import java.net.URL;
25 import java.net.URLConnection;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32
33 import javax.json.Json;
34 import javax.json.JsonReader;
35
36 import org.apache.http.HttpResponse;
37 import org.apache.http.client.methods.HttpGet;
38 import org.apache.http.client.methods.HttpPost;
39 import org.apache.http.client.methods.HttpPut;
40 import org.apache.http.entity.StringEntity;
41 import org.apache.http.impl.client.DefaultHttpClient;
42 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
43 import org.openecomp.policy.common.logging.flexlogger.Logger;
44 import org.openecomp.policy.rest.XACMLRestProperties;
45
46 import com.att.research.xacml.api.Advice;
47 import com.att.research.xacml.api.Attribute;
48 import com.att.research.xacml.api.AttributeAssignment;
49 import com.att.research.xacml.api.AttributeValue;
50 import com.att.research.xacml.api.Identifier;
51 import com.att.research.xacml.api.Obligation;
52 import com.att.research.xacml.api.Request;
53 import com.att.research.xacml.api.RequestAttributes;
54 import com.att.research.xacml.api.Result;
55 import com.att.research.xacml.std.IdentifierImpl;
56 import com.att.research.xacml.std.StdAdvice;
57 import com.att.research.xacml.std.StdAttributeAssignment;
58 import com.att.research.xacml.std.StdAttributeValue;
59 import com.att.research.xacml.std.StdMutableResponse;
60 import com.att.research.xacml.std.StdMutableResult;
61 import com.att.research.xacml.std.StdObligation;
62 import com.att.research.xacml.util.XACMLProperties;
63
64 @SuppressWarnings("deprecation")
65 public class FindAction {
66         private Logger LOGGER = FlexLogger.getLogger(this.getClass());
67         private Boolean changeIt = false;
68         private String configURL = null;
69         private StdMutableResponse newResponse = new StdMutableResponse();
70         private StdMutableResult addResult = new StdMutableResult();
71
72         public StdMutableResponse run(StdMutableResponse stdResponse, Request pepRequest) {
73                 int count = 0;
74                 boolean config = false;
75                 boolean decide = false; 
76                 Collection<RequestAttributes> requestAttributes =  pepRequest.getRequestAttributes();
77                 for(RequestAttributes requestAttribute : requestAttributes){
78                         Collection<Attribute> attributes = requestAttribute.getAttributes();
79                         for(Attribute attribute : attributes){
80                                 if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:action:action-id")){
81                                         for(AttributeValue<?> attributeValue : attribute.getValues()){
82                                                 if(attributeValue.getValue().toString().equalsIgnoreCase("ACCESS")){
83                                                         count++;
84                                                 }
85                                                 if(attributeValue.getValue().toString().equalsIgnoreCase("DECIDE")){
86                                                         decide = true;
87                                                 }
88                                         }
89                                 }
90                                 if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:resource:resource-id")){
91                                         for(AttributeValue<?> attributeValue : attribute.getValues()){
92                                                 if(attributeValue.getValue().toString().equalsIgnoreCase("Config")){
93                                                         count++;
94                                                 }
95                                         }
96                                 }
97                         }
98                 }
99                 if(count==2){
100                         config = true;
101                 }
102                 if(!config){
103                         search(stdResponse);
104                 }
105                 addResults(stdResponse, config , decide);
106                 LOGGER.info("Original Result is " + stdResponse.toString());
107                 LOGGER.info("Generated Result is " + addResult.toString());
108                 return newResponse;
109         }
110
111         private Collection<Obligation> obligations = new ArrayList<>();
112         private Map<String, String> matchValues = new HashMap<>();
113         private Map<String, String> headers = new HashMap<>();
114         private boolean header = false;
115
116         private void search(StdMutableResponse stdResponse) {
117                 for (Result result : stdResponse.getResults()) {
118                         if (!result.getObligations().isEmpty()) {
119                                 System.out.println("Obligation Received");
120                                 // Is there any action that PDP needs to take
121                                 for (Obligation obligation : result.getObligations()) {
122                                         int count = 0, uri = 0, PEP = 0;
123                                         header = false;
124                                         changeIt = false;
125                                         Collection<AttributeAssignment> afterRemoveAssignments = new ArrayList<>();
126                                         Identifier oblId = new IdentifierImpl(obligation.getId().stringValue());
127                                         StdAttributeAssignment attributeURI = null;
128                                         for (AttributeAssignment attribute : obligation.getAttributeAssignments()) {
129                                                 matchValues.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString());
130                                                 if (attribute.getAttributeId().stringValue().equalsIgnoreCase("performer")) {
131                                                         if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PEPACTION")) {
132                                                                 PEP++;
133                                                         } else if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PDPACTION")) {
134                                                                 count++;
135                                                         }
136                                                 } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("URL")) {
137                                                         uri++;
138                                                         if (uri == 1) {
139                                                                 configURL = attribute.getAttributeValue().getValue().toString();
140                                                                 attributeURI = new StdAttributeAssignment(attribute);
141                                                         }
142                                                 } else if (attribute.getAttributeId().stringValue().startsWith("headers")) {
143                                                         LOGGER.info("Headers are : "+ attribute.getAttributeValue().getValue().toString());
144                                                         header = true;
145                                                         headers.put(attribute.getAttributeId().stringValue().replaceFirst("(headers).", ""),
146                                                                         attribute.getAttributeValue().getValue().toString());
147                                                         afterRemoveAssignments.add(attribute);
148                                                 } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("body")) { 
149                                                         String papPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
150                                                         papPath= papPath.replace("/pap", "");
151                                                         matchValues.put("body",attribute.getAttributeValue().getValue().toString().replace("$URL", papPath));
152                                                 }else {
153                                                         StdAttributeAssignment attributeObligation = new StdAttributeAssignment(attribute);
154                                                         afterRemoveAssignments.add(attributeObligation);
155                                                 }
156                                         }
157                                         if (count == 1 && uri == 1 && PEP == 0) {
158                                                 // Remove Obligation and add Advice
159                                                 changeIt = true;
160                                                 takeAction(stdResponse, oblId, afterRemoveAssignments);
161                                         } else if (PEP == 1 && count == 0) {
162                                                 // Strip the PEPACTION if available
163                                                 if (uri == 1) {
164                                                         afterRemoveAssignments.add(attributeURI);
165                                                 }
166                                                 Obligation afterRemoveObligation = new StdObligation(
167                                                                 oblId, afterRemoveAssignments);
168                                                 obligations.add(afterRemoveObligation);
169                                         } else {
170                                                 obligations.add(obligation);
171                                         }
172                                 }
173                         }
174                 }
175         }
176
177         private void takeAction(StdMutableResponse stdResponse, Identifier advId,
178                         Collection<AttributeAssignment> afterRemoveAssignments) {
179                 if (changeIt) {
180                         LOGGER.info("the URL is :" + configURL);
181                         // Calling Rest URL..
182                         callRest();
183                         // Including the Results in an Advice
184                         Identifier id = new IdentifierImpl(
185                                         "org:openecomp:policy:pdp:reply");
186                         Identifier statId = new IdentifierImpl(
187                                         "org:openecomp:ecomp:policy:pdp:reply:status");
188                         Identifier statCategory = new IdentifierImpl(
189                                         "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject");
190                         Identifier strId = new IdentifierImpl(
191                                         "http://www.w3.org/2001/XMLSchema#string");
192                         Identifier resId = new IdentifierImpl(
193                                         "org:openecomp:ecomp:policy:pdp:reply:resource");
194                         Identifier resCategory = new IdentifierImpl(
195                                         "urn:oasis:names:tc:xacml:3.0:attribute-category:resource");
196                         Identifier urlId = new IdentifierImpl(
197                                         "http://www.w3.org/2001/XMLSchema#anyURI");
198                         AttributeValue<String> attributeStatusValue = new StdAttributeValue<>(
199                                         strId, status + response);
200                         AttributeValue<String> attributeResourceValue = new StdAttributeValue<>(
201                                         urlId, configURL);
202                         StdAttributeAssignment attributeStatus = new StdAttributeAssignment(
203                                         statCategory, statId, "PDP", attributeStatusValue);
204                         StdAttributeAssignment attributeResouce = new StdAttributeAssignment(
205                                         resCategory, resId, "PDP", attributeResourceValue);
206                         afterRemoveAssignments.add(attributeStatus);
207                         afterRemoveAssignments.add(attributeResouce);
208                         Advice advice = new StdAdvice(id, afterRemoveAssignments);
209                         addResult.addAdvice(advice);
210                 }
211         }
212
213         private void addResults(StdMutableResponse stdResponse, boolean config, boolean decide) {
214                 if(decide){
215                         newResponse = stdResponse;
216                         return;
217                 }
218                 for (Result result : stdResponse.getResults()) {
219                         if(config){
220                                 addResult.addAdvice(result.getAssociatedAdvice());
221                         }
222                         addResult.addAttributeCategories(result.getAttributes());
223                         addResult.addPolicyIdentifiers(result.getPolicyIdentifiers());
224                         addResult.addPolicySetIdentifiers(result.getPolicySetIdentifiers());
225                         addResult.setStatus(result.getStatus());
226                         addResult.setDecision(result.getDecision());
227                         if(!config){
228                                 addResult.addObligations(obligations);
229                         }
230                 }
231                 newResponse.add(addResult);
232         }
233
234         private int status;
235         private String response;
236         private DefaultHttpClient httpClient;
237
238         private void callRest() {
239                 // Finding the Macros in the URL..
240                 Pattern pattern = Pattern.compile("\\$([a-zA-Z0-9.:]*)");
241                 Matcher match = pattern.matcher(configURL);
242                 StringBuffer sb = new StringBuffer();
243                 while (match.find()) {
244                         LOGGER.info("Found Macro : " + match.group(1));
245                         String replaceValue = matchValues.get(match.group(1));
246                         LOGGER.info("Replacing with :" + replaceValue);
247                         match.appendReplacement(sb, replaceValue);
248                 }
249                 match.appendTail(sb);
250                 LOGGER.info("URL is : " + sb.toString());
251                 configURL = sb.toString();
252                 // Calling the Requested service. 
253                 if (matchValues.get("method").equalsIgnoreCase("GET")) {
254                         httpClient = new DefaultHttpClient();
255                         try {
256                                 HttpGet getRequest = new HttpGet(configURL);
257                                 // Adding Headers here
258                                 if (header) {
259                                         for (String key : headers.keySet()) {
260                                                 getRequest.addHeader(key, headers.get(key));
261                                         }
262                                 }
263                                 HttpResponse result = httpClient.execute(getRequest);
264                                 status = result.getStatusLine().getStatusCode();
265                                 BufferedReader br = new BufferedReader(new InputStreamReader(
266                                                 (result.getEntity().getContent())));
267                                 String output = " ";
268                                 String out;
269                                 while ((out = br.readLine()) != null) {
270                                         output = output + out;
271                                 }
272                                 response = output;
273                         } catch (Exception e) {
274                                 LOGGER.error(e.getMessage()+e);
275                                 response = e.getMessage();
276                         } finally {
277                                 httpClient.getConnectionManager().shutdown();
278                         }
279                 } else if(matchValues.get("method").equalsIgnoreCase("POST")) {
280                         httpClient = new DefaultHttpClient();
281                         try {
282                                 HttpPost postRequest = new HttpPost(configURL);
283                                 // Adding Headers here
284                                 if (header) {
285                                         for (String key : headers.keySet()) {
286                                                 postRequest.addHeader(key, headers.get(key));
287                                         }
288                                 }
289                                 // Adding the Body. 
290                                 URL configURL = new URL(matchValues.get("body"));
291                                 URLConnection connection = null;
292                                 connection = configURL.openConnection();
293                                 // InputStream in = connection.getInputStrem();
294                                 // LOGGER.info("The Body Content is : " + IOUtils.toString(in));
295                                 JsonReader jsonReader = Json.createReader(connection.getInputStream());
296                                 StringEntity input = new StringEntity(jsonReader.readObject().toString());
297                                 input.setContentType("application/json");
298                                 postRequest.setEntity(input);
299                                 // Executing the Request. 
300                                 HttpResponse result = httpClient.execute(postRequest);
301                                 LOGGER.info("Result Headers are : " + result.getAllHeaders());
302                                 status = result.getStatusLine().getStatusCode();
303                                 BufferedReader br = new BufferedReader(new InputStreamReader(
304                                                 (result.getEntity().getContent())));
305                                 String output = " ";
306                                 String out;
307                                 while ((out = br.readLine()) != null) {
308                                         output = output + out;
309                                 }
310                                 response = output;
311                         }catch (Exception e) {
312                                 LOGGER.error(e.getMessage() +e);
313                                 response = e.getMessage();
314                         } finally {
315                                 httpClient.getConnectionManager().shutdown();
316                         }
317                 } else if(matchValues.get("method").equalsIgnoreCase("PUT")) {
318                         httpClient = new DefaultHttpClient();
319                         try {
320                                 HttpPut putRequest = new HttpPut(configURL);
321                                 // Adding Headers here
322                                 if (header) {
323                                         for (String key : headers.keySet()) {
324                                                 putRequest.addHeader(key, headers.get(key));
325                                         }
326                                 }
327                                 // Adding the Body. 
328                                 URL configURL = new URL(matchValues.get("body"));
329                                 URLConnection connection = null;
330                                 connection = configURL.openConnection();
331                                 //InputStream in = connection.getInputStream();
332                                 //LOGGER.info("The Body Content is : " + IOUtils.toString(in));
333                                 JsonReader jsonReader = Json.createReader(connection.getInputStream());
334                                 StringEntity input = new StringEntity(jsonReader.readObject().toString());
335                                 input.setContentType("application/json");
336                                 putRequest.setEntity(input);
337                                 // Executing the Request. 
338                                 HttpResponse result = httpClient.execute(putRequest);
339                                 status = result.getStatusLine().getStatusCode();
340                                 BufferedReader br = new BufferedReader(new InputStreamReader(
341                                                 (result.getEntity().getContent())));
342                                 String output = " ";
343                                 String out;
344                                 while ((out = br.readLine()) != null) {
345                                         output = output + out;
346                                 }
347                                 response = output;
348                         } catch (Exception e) {
349                                 LOGGER.error(e.getMessage() +e);
350                                 response = e.getMessage();
351                         }finally {
352                                 httpClient.getConnectionManager().shutdown();
353                         }
354                 }
355         }
356 }