Merge "Fix comparison issues in onap pap rest"
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / restAuth / CheckPDP.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
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
21 package org.onap.policy.pap.xacml.restAuth;
22
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.nio.charset.StandardCharsets;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Base64;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Objects;
38 import java.util.Properties;
39
40 import org.onap.policy.common.logging.eelf.MessageCodes;
41 import org.onap.policy.common.logging.eelf.PolicyLogger;
42 import org.onap.policy.common.logging.flexlogger.FlexLogger;
43 import org.onap.policy.common.logging.flexlogger.Logger;
44 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
45 import org.onap.policy.xacml.api.XACMLErrorConstants;
46
47 import com.att.research.xacml.api.pap.PAPException;
48
49 public class CheckPDP {
50
51     private static Path pdpPath = null;
52     private static Properties pdpProp = null;
53     private static Long oldModified = null;
54     private static Long newModified = null;
55     private static HashMap<String, String> pdpMap = null;
56     private static final Logger logger = FlexLogger.getLogger(CheckPDP.class);
57
58     public static boolean validateID(String id) {
59         // ReadFile
60         try {
61             readFile();
62         } catch (Exception e) {
63             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception reading file");
64             return false;
65         }
66         // Check ID
67         if (pdpMap.containsKey(id)) {
68             return true;
69         }
70         return false;
71     }
72
73     private static void readFile() throws PAPException {
74         String pdpFile = XACMLPapServlet.getPDPFile();
75         if (pdpFile == null) {
76             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "PDP File name is undefined");
77             throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile);
78         }
79         if (pdpPath == null) {
80             pdpPath = Paths.get(pdpFile);
81             if (Files.notExists(pdpPath)) {
82                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path");
83                 throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString());
84             }
85             if (pdpPath.toString().endsWith(".properties")) {
86                 readProps();
87             } else {
88                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "Not a .properties file");
89                 throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file");
90             }
91         }
92         // Check if File is updated recently
93         else {
94             newModified = pdpPath.toFile().lastModified();
95             if (!Objects.equals(newModified, oldModified)) {
96                 // File has been updated.
97                 readProps();
98             }
99         }
100     }
101
102     @SuppressWarnings({ "rawtypes", "unchecked" })
103     private static void readProps() throws PAPException {
104         InputStream in;
105         pdpProp = new Properties();
106         try {
107             in = new FileInputStream(pdpPath.toFile());
108             oldModified = pdpPath.toFile().lastModified();
109             pdpProp.load(in);
110         } catch (IOException e) {
111             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Cannot load the Properties file");
112             throw new PAPException("Cannot Load the Properties file", e);
113         }
114         // Read the Properties and Load the PDPs and encoding.
115         pdpMap = new HashMap<>();
116         // Check the Keys for PDP_URLs
117         Collection<Object> unsorted = pdpProp.keySet();
118         List<String> sorted = new ArrayList(unsorted);
119         Collections.sort(sorted);
120         for (String propKey : sorted) {
121             if (propKey.startsWith("PDP_URL")) {
122                 String check_val = pdpProp.getProperty(propKey);
123                 if (check_val == null) {
124                     throw new PAPException("Properties file doesn't have the PDP_URL parameter");
125                 }
126                 if (check_val.contains(";")) {
127                     List<String> pdp_default = new ArrayList<>(Arrays.asList(check_val.split("\\s*;\\s*")));
128                     int pdpCount = 0;
129                     while (pdpCount < pdp_default.size()) {
130                         String pdpVal = pdp_default.get(pdpCount);
131                         readPDPParam(pdpVal);
132                         pdpCount++;
133                     }
134                 } else {
135                     readPDPParam(check_val);
136                 }
137             }
138         }
139         if (pdpMap == null || pdpMap.isEmpty()) {
140             logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
141             throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs");
142         }
143     }
144
145     private static void readPDPParam(String pdpVal) throws PAPException{
146         if(pdpVal.contains(",")){
147             List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
148             if(pdpValues.size()==3){
149                 // 1:2 will be UserID:Password
150                 String userID = pdpValues.get(1);
151                 String pass = pdpValues.get(2);
152                 Base64.Encoder encoder = Base64.getEncoder();
153                 // 0 - PDPURL
154                 pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
155             }else{
156                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request");
157                 throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues);
158             }
159         }else{
160             PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal);
161             throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request.");
162         }
163     }
164
165     public static String getEncoding(String pdpID){
166         try {
167             readFile();
168         } catch (Exception e) {
169             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exeption reading Properties file");
170         }
171         String encoding = null;
172         if(pdpMap!=null && (!pdpMap.isEmpty())){
173             try{
174                 encoding = pdpMap.get(pdpID);
175             } catch(Exception e){
176                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding");
177             }
178             return encoding;
179         }else{
180             return null;
181         }
182     }
183
184 }