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