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