Merge "Decision BlackList Guard Enhancements"
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / admin / CheckPDP.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.admin;
23
24
25 import java.io.FileInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.nio.charset.StandardCharsets;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Base64;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Properties;
40
41 import org.onap.policy.common.logging.flexlogger.FlexLogger;
42 import org.onap.policy.common.logging.flexlogger.Logger;
43 import org.onap.policy.rest.XACMLRestProperties;
44 import org.onap.policy.xacml.api.XACMLErrorConstants;
45
46 import com.att.research.xacml.util.XACMLProperties;
47
48 /**
49  * What is not good about this class is that once a value has been set for pdpProperties path
50  * you cannot change it. That may be ok for a highly controlled production environment in which
51  * nothing changes, but not a very good implementation.
52  * 
53  * The reset() method has been added to assist with the above problem in order to 
54  * acquire >80% JUnit code coverage.
55  * 
56  * This static class doesn't really check a PDP, it simply loads a properties file and tried
57  * to ensure that a valid URL exists for a PDP along with user/password.
58  *
59  */
60 public class CheckPDP {
61     private static Path pdpPath = null;
62     private static Long oldModified = null;
63     private static HashMap<String, String> pdpMap = null;
64     private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class);
65
66     private CheckPDP(){
67         //default constructor
68     }
69
70     public static Map<String, String> getPdpMap() {
71         return pdpMap;
72     }
73
74     private static void reset() {
75         pdpPath = null;
76         oldModified = null;
77         pdpMap = null;
78     }
79
80     public static boolean validateID(String id) {
81         // ReadFile
82         try {
83             readFile();
84         } catch (Exception e) {
85             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
86             return false;
87         }
88         if (pdpMap == null) {
89             return false;
90         }
91         // Check ID
92         return pdpMap.containsKey(id);
93     }
94
95     private static void readFile(){
96         String pdpFile = null;
97         try{
98             pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
99         }catch (Exception e){
100             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e);
101             return;
102         }
103         if (pdpFile == null) {
104             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile);
105         }
106         if (pdpPath == null) {
107             pdpPath = Paths.get(pdpFile);
108             if (!pdpPath.toString().endsWith(".properties") || !pdpPath.toFile().exists()) {
109                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : "     + pdpPath.toString());
110                 CheckPDP.reset();
111                 return;
112             }
113             readProps();
114         }
115         // Check if File is updated recently
116         else {
117             Long newModified = pdpPath.toFile().lastModified();
118             if (!newModified.equals(oldModified)) {
119                 // File has been updated.
120                 readProps();
121             }
122         }
123     }
124
125     @SuppressWarnings({ "unchecked", "rawtypes" })
126     private static void readProps() {
127         Properties pdpProp;
128         pdpProp = new Properties();
129         try(InputStream in = new FileInputStream(pdpPath.toFile())) {
130             oldModified = pdpPath.toFile().lastModified();
131             pdpProp.load(in);
132             // Read the Properties and Load the PDPs and encoding.
133             pdpMap = new HashMap<>();
134             // Check the Keys for PDP_URLs
135             Collection<Object> unsorted = pdpProp.keySet();
136             List<String> sorted = new ArrayList(unsorted);
137             Collections.sort(sorted);
138             for (String propKey : sorted) {
139                 loadPDPProperties(propKey, pdpProp);
140             }
141         } catch (IOException e) {
142             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
143         }
144         if (pdpMap == null || pdpMap.isEmpty()) {
145             LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
146             CheckPDP.reset();
147         }
148     }
149
150     private static void loadPDPProperties(String propKey, Properties pdpProp){
151         if (propKey.startsWith("PDP_URL")) {
152             String checkVal = pdpProp.getProperty(propKey);
153             if (checkVal == null) {
154                 LOGGER.error("Properties file doesn't have the PDP_URL parameter");
155             }
156             if (checkVal != null && checkVal.contains(";")) {
157                 List<String> pdpDefault = new ArrayList<>(Arrays.asList(checkVal.split("\\s*;\\s*")));
158                 int pdpCount = 0;
159                 while (pdpCount < pdpDefault.size()) {
160                     String pdpVal = pdpDefault.get(pdpCount);
161                     readPDPParam(pdpVal);
162                     pdpCount++;
163                 }
164             }
165         }
166     }
167
168     private static void readPDPParam(String pdpVal){
169         if(pdpVal.contains(",")){
170             List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
171             if(pdpValues.size()==3){
172                 // 1:2 will be UserID:Password
173                 String userID = pdpValues.get(1);
174                 String pass = pdpValues.get(2);
175                 Base64.Encoder encoder = Base64.getEncoder();
176                 // 0 - PDPURL
177                 pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
178             }else{
179                 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues);
180             }
181         }else{
182             LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal);
183         }
184     }
185
186     public static String getEncoding(String pdpID){
187         try {
188             readFile();
189         } catch (Exception e) {
190             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
191         }
192         String encoding = null;
193         if(pdpMap!=null && (!pdpMap.isEmpty())){
194             try{
195                 encoding = pdpMap.get(pdpID);
196             } catch(Exception e){
197                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
198             }
199             return encoding;
200         }else{
201             return null;
202         }
203     }
204 }