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