Applying bug fixes
[music.git] / src / main / java / org / onap / music / main / CachingUtil.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
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  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22 package org.onap.music.main;
23
24 import java.util.Arrays;
25 import java.util.Calendar;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.Map;
29 import java.util.UUID;
30 import javax.ws.rs.core.HttpHeaders;
31 import javax.ws.rs.core.MediaType;
32 import org.apache.commons.codec.binary.Base64;
33 import org.apache.commons.jcs.JCS;
34 import org.apache.commons.jcs.access.CacheAccess;
35 import org.codehaus.jackson.map.ObjectMapper;
36 import org.onap.music.datastore.PreparedQueryObject;
37 import org.onap.music.datastore.jsonobjects.AAFResponse;
38 import org.onap.music.eelf.logging.EELFLoggerDelegate;
39 import org.onap.music.exceptions.MusicServiceException;
40
41 import com.att.eelf.configuration.EELFLogger;
42 import com.datastax.driver.core.DataType;
43 import com.datastax.driver.core.ResultSet;
44 import com.datastax.driver.core.Row;
45 import com.sun.jersey.api.client.Client;
46 import com.sun.jersey.api.client.ClientResponse;
47 import com.sun.jersey.api.client.WebResource;
48
49 /**
50  * All Caching related logic is handled by this class and a schedule cron runs to update cache.
51  * 
52  * @author Vikram
53  *
54  */
55 public class CachingUtil implements Runnable {
56
57     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
58
59     private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
60     private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
61     private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
62     private static Map<String, Number> userAttempts = new HashMap<>();
63     private static Map<String, Calendar> lastFailedTime = new HashMap<>();
64
65     public boolean isCacheRefreshNeeded() {
66         if (aafCache.get("initBlankMap") == null)
67             return true;
68         return false;
69     }
70
71     public void initializeMusicCache() {
72         logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
73         musicCache.put("isInitialized", "true");
74     }
75
76     public void initializeAafCache() throws MusicServiceException {
77         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
78
79         String query = "SELECT application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
80         PreparedQueryObject pQuery = new PreparedQueryObject();
81         pQuery.appendQueryString(query);
82         try {
83             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
84         } catch (Exception e1) {
85             e1.printStackTrace();
86             logger.error(EELFLoggerDelegate.errorLogger,"Exception is "+ e1.getMessage() + "during initalizeAafCache");
87         }
88         ResultSet rs = MusicCore.get(pQuery);
89         Iterator<Row> it = rs.iterator();
90         Map<String, String> map = null;
91         while (it.hasNext()) {
92             Row row = it.next();
93             String nameSpace = row.getString("keyspace_name");
94             String userId = row.getString("username");
95             String password = row.getString("password");
96             String keySpace = row.getString("application_name");
97             try {
98                 userAttempts.put(nameSpace, 0);
99                 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
100                 if (responseObj.getNs().size() > 0) {
101                     map = new HashMap<>();
102                     map.put(userId, password);
103                     aafCache.put(nameSpace, map);
104                     musicCache.put(nameSpace, keySpace);
105                     logger.debug("Cronjob: Cache Updated with AAF response for namespace "
106                                     + nameSpace);
107                 }
108             } catch (Exception e) {
109                 // TODO Auto-generated catch block
110                 e.printStackTrace();
111                 logger.error("Something at AAF was changed for ns: " + nameSpace
112                                 + ". So not updating Cache for the namespace. ");
113                 logger.error("Exception is " + e.getMessage());
114             }
115         }
116
117     }
118
119     @Override
120     public void run() {
121         logger.debug("Scheduled task invoked. Refreshing Cache...");
122         try {
123                         initializeAafCache();
124                 } catch (MusicServiceException e) {
125                         logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
126                 }
127     }
128
129     public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
130                     String keySpace) throws Exception {
131
132         if (aafCache.get(nameSpace) != null) {
133             if (!musicCache.get(nameSpace).equals(keySpace)) {
134                 logger.debug("Create new application for the same namespace.");
135             } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
136                 logger.debug("Authenticated with cache value..");
137                 // reset invalid attempts to 0
138                 userAttempts.put(nameSpace, 0);
139                 return true;
140             } else {
141                 // call AAF update cache with new password
142                 if (userAttempts.get(nameSpace) == null)
143                     userAttempts.put(nameSpace, 0);
144                 if ((Integer) userAttempts.get(nameSpace) >= 3) {
145                     logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
146                     logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
147                     Calendar calendar = Calendar.getInstance();
148                     long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
149                     logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
150                     if( delayTime > 120000) {
151                         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
152                         userAttempts.put(nameSpace, 0);
153                     } else {
154                         throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
155                     }
156                 }
157                 logger.error(EELFLoggerDelegate.errorLogger,"Cache not authenticated..");
158                 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
159             }
160         }
161
162         AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
163         if (responseObj.getNs().size() > 0) {
164             if (responseObj.getNs().get(0).getAdmin().contains(userId))
165                 return true;
166
167         }
168         logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
169         return false;
170     }
171
172     private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
173                     throws Exception {
174         if (MusicUtil.getAafEndpointUrl() == null) {
175             throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
176         }
177         Client client = Client.create();
178         // WebResource webResource =
179         // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
180         WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
181         String plainCreds = userId + ":" + password;
182         byte[] plainCredsBytes = plainCreds.getBytes();
183         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
184         String base64Creds = new String(base64CredsBytes);
185
186         ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
187                         .header("Authorization", "Basic " + base64Creds)
188                         .header("content-type", "application/json").get(ClientResponse.class);
189         if (response.getStatus() != 200) {
190             if (userAttempts.get(nameSpace) == null)
191                 userAttempts.put(nameSpace, 0);
192             if ((Integer) userAttempts.get(nameSpace) >= 2) {
193                 lastFailedTime.put(nameSpace, Calendar.getInstance());
194                 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
195                 throw new Exception(
196                                 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
197             }
198             userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
199             throw new Exception(
200                             "Unable to authenticate. Please check the AAF credentials against namespace.");
201             // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
202             // for specific time.
203         }
204         response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
205                         Arrays.asList(MediaType.APPLICATION_JSON));
206         // AAFResponse output = response.getEntity(AAFResponse.class);
207         response.bufferEntity();
208         String x = response.getEntity(String.class);
209         AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);
210         return responseObj;
211     }
212
213     public static Map<String, Object> authenticateAIDUser(String aid, String keyspace)
214                     throws Exception {
215         Map<String, Object> resultMap = new HashMap<>();
216         String uuid = null;
217         /*
218          * if(aid == null || aid.length() == 0) { resultMap.put("Exception Message",
219          * "AID is missing for the keyspace requested."); //create a new AID ?? } else
220          */
221         if (musicCache.get(keyspace) == null) {
222             PreparedQueryObject pQuery = new PreparedQueryObject();
223             pQuery.appendQueryString(
224                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
225                                             + keyspace + "' allow filtering");
226             Row rs = MusicCore.get(pQuery).one();
227             try {
228                 uuid = rs.getUUID("uuid").toString();
229                 musicCache.put(keyspace, uuid);
230             } catch (Exception e) {
231                 String msg = e.getMessage();
232                 logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
233                 resultMap.put("Exception", "Unauthorized operation. Check AID and Keyspace. "
234                                 + "Exception from MUSIC is: "
235                                 + (msg == null ? "Keyspace is new so no AID should be passed in Header."
236                                                 : msg));
237                 return resultMap;
238             }
239             if (!musicCache.get(keyspace).toString().equals(aid)) {
240                 resultMap.put("Exception Message",
241                                 "Unauthorized operation. Invalid AID for the keyspace");
242                 return resultMap;
243             }
244         } else if (musicCache.get(keyspace) != null
245                         && !musicCache.get(keyspace).toString().equals(aid)) {
246             resultMap.put("Exception Message",
247                             "Unauthorized operation. Invalid AID for the keyspace");
248             return resultMap;
249         }
250         resultMap.put("aid", uuid);
251         return resultMap;
252     }
253
254     public static void updateMusicCache(String aid, String keyspace) {
255         logger.info("Updating musicCache for keyspace " + keyspace + " with aid " + aid);
256         musicCache.put(keyspace, aid);
257     }
258
259     public static void updateisAAFCache(String namespace, String isAAF) {
260         appNameCache.put(namespace, isAAF);
261     }
262
263     public static Boolean isAAFApplication(String namespace) throws MusicServiceException {
264
265         String isAAF = appNameCache.get(namespace);
266         if (isAAF == null) {
267             PreparedQueryObject pQuery = new PreparedQueryObject();
268             pQuery.appendQueryString(
269                             "SELECT is_aaf from admin.keyspace_master where application_name = '"
270                                             + namespace + "' allow filtering");
271             Row rs = MusicCore.get(pQuery).one();
272             try {
273                 isAAF = String.valueOf(rs.getBool("is_aaf"));
274                 appNameCache.put(namespace, isAAF);
275             } catch (Exception e) {
276                 logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
277                 e.printStackTrace();
278             }
279         }
280
281         
282         return Boolean.valueOf(isAAF);
283     }
284
285     public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
286         String uuid = musicCache.get(keyspace);
287         if (uuid == null) {
288             PreparedQueryObject pQuery = new PreparedQueryObject();
289             pQuery.appendQueryString(
290                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
291                                             + keyspace + "' allow filtering");
292             Row rs = MusicCore.get(pQuery).one();
293             try {
294                 uuid = rs.getUUID("uuid").toString();
295                 musicCache.put(keyspace, uuid);
296             } catch (Exception e) {
297                 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
298                 e.printStackTrace();
299             }
300         }
301         return uuid;
302     }
303
304     public static String getAppName(String keyspace) throws MusicServiceException {
305         String appName = null;
306         PreparedQueryObject pQuery = new PreparedQueryObject();
307         pQuery.appendQueryString(
308                         "SELECT application_name from admin.keyspace_master where keyspace_name = '"
309                                         + keyspace + "' allow filtering");
310         Row rs = MusicCore.get(pQuery).one();
311         try {
312             appName = rs.getString("application_name");
313         } catch (Exception e) {
314             logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
315             e.printStackTrace();
316         }
317         return appName;
318     }
319
320     public static String generateUUID() {
321         String uuid = UUID.randomUUID().toString();
322         logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
323         return uuid;
324     }
325
326     public static Map<String, Object> validateRequest(String nameSpace, String userId,
327                     String password, String keyspace, String aid, String operation) {
328         Map<String, Object> resultMap = new HashMap<>();
329         if (!"createKeySpace".equals(operation)) {
330             if (nameSpace == null) {
331                 resultMap.put("Exception", "Application namespace is mandatory.");
332             }
333         }
334         return resultMap;
335
336     }
337
338     public static Map<String, Object> verifyOnboarding(String ns, String userId, String password)
339                     throws Exception {
340         Map<String, Object> resultMap = new HashMap<>();
341         if (ns == null || userId == null || password == null) {
342             logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
343             resultMap.put("Exception",
344                             "One or more required headers appName(ns), userId, password is missing. Please check.");
345             return resultMap;
346         }
347         PreparedQueryObject queryObject = new PreparedQueryObject();
348         queryObject.appendQueryString(
349                         "select * from admin.keyspace_master where application_name=? and username=? allow filtering");
350         queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
351         queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
352         Row rs = MusicCore.get(queryObject).one();
353         if (rs == null) {
354             logger.error(EELFLoggerDelegate.errorLogger,"Namespace and UserId doesn't match. namespace: "+ns+" and userId: "+userId);
355
356             resultMap.put("Exception", "Namespace and UserId doesn't match. namespace: "+ns+" and userId: "+userId);
357         } else {
358             boolean is_aaf = rs.getBool("is_aaf");
359             String keyspace = rs.getString("keyspace_name");
360             if (!is_aaf) {
361                 if (!keyspace.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
362                     logger.error(EELFLoggerDelegate.errorLogger,"Non AAF applications are allowed to have only one keyspace per application.");
363                     resultMap.put("Exception",
364                                     "Non AAF applications are allowed to have only one keyspace per application.");
365                 }
366             }
367         }
368         return resultMap;
369     }
370 }