Removed unused imports. added error log
[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.Calendar;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.UUID;
30 import javax.ws.rs.core.MediaType;
31 import org.apache.commons.codec.binary.Base64;
32 import org.apache.commons.jcs.JCS;
33 import org.apache.commons.jcs.access.CacheAccess;
34 import org.mindrot.jbcrypt.BCrypt;
35 import org.onap.music.datastore.PreparedQueryObject;
36 import org.onap.music.eelf.logging.EELFLoggerDelegate;
37 import org.onap.music.eelf.logging.format.AppMessages;
38 import org.onap.music.eelf.logging.format.ErrorSeverity;
39 import org.onap.music.eelf.logging.format.ErrorTypes;
40 import org.onap.music.exceptions.MusicServiceException;
41 import org.onap.music.datastore.jsonobjects.JsonCallback;
42 import com.datastax.driver.core.DataType;
43 import com.datastax.driver.core.ResultSet;
44 import com.datastax.driver.core.Row;
45 import com.datastax.driver.core.exceptions.InvalidQueryException;
46 import com.sun.jersey.api.client.Client;
47 import com.sun.jersey.api.client.ClientResponse;
48 import com.sun.jersey.api.client.WebResource;
49
50 /**
51  * All Caching related logic is handled by this class and a schedule cron runs to update cache.
52  * 
53  * @author Vikram
54  *
55  */
56 public class CachingUtil implements Runnable {
57
58     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
59
60     private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
61     private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
62     private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
63     private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
64     private static CacheAccess<String, JsonCallback> callBackCache = JCS.getInstance("callBackCache");
65     private static CacheAccess<String, List<String>> callbackNotifyList = JCS.getInstance("callbackNotifyList");
66     private static Map<String, Number> userAttempts = new HashMap<>();
67     private static Map<String, Calendar> lastFailedTime = new HashMap<>();
68
69     public boolean isCacheRefreshNeeded() {
70         if (aafCache.get("initBlankMap") == null)
71             return true;
72         return false;
73     }
74     
75     public static void updateCallBackCache(String appName, JsonCallback jsonCallBack) {
76         logger.info("updateCallBackCache: updating cache.....");
77         callBackCache.put(appName, jsonCallBack);
78     }
79     
80     public static JsonCallback getCallBackCache(String appName) {
81         return callBackCache.get(appName);
82     }
83
84     public static void updateCallbackNotifyList(List<String> notifyList) {
85         logger.info("callbackNotifyList: updating cache.....");
86         callbackNotifyList.put("callbackNotify", notifyList);
87     }
88     
89     public static List<String> getCallbackNotifyList() {
90         return callbackNotifyList.get("callbackNotify");
91     }
92     
93     public void initializeMusicCache() {
94         logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
95         musicCache.put("isInitialized", "true");
96     }
97
98     public void initializeAafCache() throws MusicServiceException {
99         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
100
101         String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
102         PreparedQueryObject pQuery = new PreparedQueryObject();
103         pQuery.appendQueryString(query);
104         try {
105             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
106         } catch (Exception e1) {
107             logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
108         }
109         ResultSet rs = MusicCore.get(pQuery);
110         Iterator<Row> it = rs.iterator();
111         Map<String, String> map = null;
112         while (it.hasNext()) {
113             Row row = it.next();
114             String nameSpace = row.getString("keyspace_name");
115             String userId = row.getString("username");
116             String password = row.getString("password");
117             String keySpace = row.getString("application_name");
118             try {
119                 userAttempts.put(nameSpace, 0);
120                 boolean responseObj = triggerAAF(nameSpace, userId, password);
121                 if (responseObj) {
122                     map = new HashMap<>();
123                     map.put(userId, password);
124                     aafCache.put(nameSpace, map);
125                     musicCache.put(keySpace, nameSpace);
126                     logger.debug("Cronjob: Cache Updated with AAF response for namespace "
127                                     + nameSpace);
128                 }
129             } catch (Exception e) {
130                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
131                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
132             }
133         }
134
135     }
136
137     @Override
138     public void run() {
139         logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
140         try {
141                         initializeAafCache();
142                 } catch (MusicServiceException e) {
143                         logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
144                 }
145     }
146
147     public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
148                     String keySpace) throws Exception {
149
150         if (aafCache.get(nameSpace) != null) {
151             if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
152                 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
153             } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
154                 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
155                 // reset invalid attempts to 0
156                 userAttempts.put(nameSpace, 0);
157                 return true;
158             } else {
159                 // call AAF update cache with new password
160                 if (userAttempts.get(nameSpace) == null)
161                     userAttempts.put(nameSpace, 0);
162                 if ((Integer) userAttempts.get(nameSpace) >= 3) {
163                     logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
164                     logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
165                     Calendar calendar = Calendar.getInstance();
166                     long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
167                     logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
168                     if( delayTime > 120000) {
169                         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
170                         userAttempts.put(nameSpace, 0);
171                     } else {
172                         logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
173                         throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
174                     }
175                 }
176                 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
177                 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
178             }
179         }
180
181         boolean responseObj = triggerAAF(nameSpace, userId, password);
182         if (responseObj) {
183             //if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
184                 //Map<String, String> map = new HashMap<>();
185                 //map.put(userId, password);
186                 //aafCache.put(nameSpace, map);
187                 return true;
188             //}
189         }
190         logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
191         return false;
192     }
193
194     private static boolean triggerAAF(String nameSpace, String userId, String password)
195                     throws Exception {
196         if (MusicUtil.getAafEndpointUrl() == null) {
197                 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
198             throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
199         }
200         Client client = Client.create();
201         // WebResource webResource =
202         // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
203         WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
204         String plainCreds = userId + ":" + password;
205         byte[] plainCredsBytes = plainCreds.getBytes();
206         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
207         String base64Creds = new String(base64CredsBytes);
208
209         ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
210                         .header("Authorization", "Basic " + base64Creds)
211                         .header("content-type", "application/json").get(ClientResponse.class);
212         if (response.getStatus() != 200) {
213             if (userAttempts.get(nameSpace) == null)
214                 userAttempts.put(nameSpace, 0);
215             if ((Integer) userAttempts.get(nameSpace) >= 2) {
216                 lastFailedTime.put(nameSpace, Calendar.getInstance());
217                 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
218                 throw new Exception(
219                                 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
220             }
221             userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
222             throw new Exception(
223                             "Unable to authenticate. Please check the AAF credentials against namespace.");
224             // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
225             // for specific time.
226         }
227         /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
228                         Arrays.asList(MediaType.APPLICATION_JSON));
229         // AAFResponse output = response.getEntity(AAFResponse.class);
230         response.bufferEntity();
231         String x = response.getEntity(String.class);
232         AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
233         
234         return true;
235     }
236
237     public static void updateMusicCache(String keyspace, String nameSpace) {
238         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
239         musicCache.put(keyspace, nameSpace);
240     }
241
242     public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
243         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
244         Map<String, String> map = new HashMap<>();
245         map.put(userId, password);
246         musicValidateCache.put(nameSpace, map);
247     }
248     
249     public static void updateisAAFCache(String namespace, String isAAF) {
250         appNameCache.put(namespace, isAAF);
251     }
252
253     public static String isAAFApplication(String namespace) throws MusicServiceException {
254         String isAAF = appNameCache.get(namespace);
255         if (isAAF == null) {
256             PreparedQueryObject pQuery = new PreparedQueryObject();
257             pQuery.appendQueryString(
258                             "SELECT is_aaf from admin.keyspace_master where application_name = '"
259                                             + namespace + "' allow filtering");
260             Row rs = null;
261             try {
262                 rs = MusicCore.get(pQuery).one();
263             } catch(InvalidQueryException e) {
264                 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
265                 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
266             }
267             try {
268                 isAAF = String.valueOf(rs.getBool("is_aaf"));
269                 if(isAAF != null)
270                     appNameCache.put(namespace, isAAF);
271             } catch (Exception e) {
272                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
273             }
274         }
275         return isAAF;
276     }
277
278     public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
279         String uuid = null;
280         if (uuid == null) {
281             PreparedQueryObject pQuery = new PreparedQueryObject();
282             pQuery.appendQueryString(
283                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
284                                             + keyspace + "' allow filtering");
285             Row rs = MusicCore.get(pQuery).one();
286             try {
287                 uuid = rs.getUUID("uuid").toString();
288             } catch (Exception e) {
289                 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
290             }
291         }
292         return uuid;
293     }
294
295     public static String getAppName(String keyspace) throws MusicServiceException {
296         String appName = null;
297         PreparedQueryObject pQuery = new PreparedQueryObject();
298         pQuery.appendQueryString(
299                         "SELECT application_name from admin.keyspace_master where keyspace_name = '"
300                                         + keyspace + "' allow filtering");
301         Row rs = MusicCore.get(pQuery).one();
302         try {
303             appName = rs.getString("application_name");
304         } catch (Exception e) {
305                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
306         }
307         return appName;
308     }
309
310     public static String generateUUID() {
311         String uuid = UUID.randomUUID().toString();
312         logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
313         return uuid;
314     }
315
316     public static Map<String, Object> validateRequest(String nameSpace, String userId,
317                     String password, String keyspace, String aid, String operation) {
318         Map<String, Object> resultMap = new HashMap<>();
319         if (!"createKeySpace".equals(operation)) {
320             if (nameSpace == null) {
321                 resultMap.put("Exception", "Application namespace is mandatory.");
322             }
323         }
324         return resultMap;
325
326     }
327
328     public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
329         Map<String, Object> resultMap = new HashMap<>();
330         if (ns == null || userId == null || password == null) {
331                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
332                 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
333             resultMap.put("Exception",
334                             "One or more required headers appName(ns), userId, password is missing. Please check.");
335             return resultMap;
336         }
337         PreparedQueryObject queryObject = new PreparedQueryObject();
338         queryObject.appendQueryString(
339                         "select * from admin.keyspace_master where application_name = ? allow filtering");
340         try {
341                 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
342         } catch(Exception e) {
343                 resultMap.put("Exception",
344                     "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
345                 return resultMap;
346         }
347         Row rs = null;
348                 try {
349                         rs = MusicCore.get(queryObject).one();
350                 } catch (MusicServiceException e) {
351                         // TODO Auto-generated catch block
352                         resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
353                         return resultMap;
354         } catch (InvalidQueryException e) {
355             logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
356             resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
357             return resultMap;
358         }
359         if (rs == null) {
360             logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
361             resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
362         } else {
363                 if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
364                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
365                 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
366                 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
367                 return resultMap;
368             }
369         }
370         return resultMap;
371     }
372
373     public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
374            String keyspace) {
375         Map<String, Object> resultMap = new HashMap<>();
376         String pwd = null;
377         if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null) 
378                 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
379             if(!musicCache.get(keyspace).equals(nameSpace)) {
380                 resultMap.put("Exception", "Namespace and keyspace doesn't match");
381                 return resultMap;
382             }
383             if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
384                 resultMap.put("Exception", "Namespace, userId and password doesn't match");
385                 return resultMap;
386             }
387             return resultMap;
388         }
389         PreparedQueryObject queryObject = new PreparedQueryObject();
390         queryObject.appendQueryString(
391                         "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
392         try {
393             queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
394         } catch (Exception e) {
395                  logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
396         }
397         Row rs = null;
398         try {
399             rs = MusicCore.get(queryObject).one();
400         } catch (MusicServiceException e) {
401                 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
402             return resultMap;
403         }
404         if(rs == null) {
405             resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
406             return resultMap;
407         }
408         else {
409             String user = rs.getString("username");
410             pwd = rs.getString("password");
411             String ns = rs.getString("application_name");
412             if(!ns.equals(nameSpace)) {
413             resultMap.put("Exception", "Namespace and keyspace doesn't match");
414             return resultMap;
415             }
416             if(!user.equals(userId)) {
417                 resultMap.put("Exception", "Invalid userId :"+userId);
418                 return resultMap;
419             }
420             if(!BCrypt.checkpw(password, pwd)) {
421                 resultMap.put("Exception", "Invalid password");
422                 return resultMap;
423             }
424         }
425         CachingUtil.updateMusicCache(keyspace, nameSpace);
426         CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
427         return resultMap;
428     }
429
430     public static void deleteKeysFromDB(String deleteKeys) {
431         PreparedQueryObject pQuery = new PreparedQueryObject();
432         pQuery.appendQueryString(
433                         "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")");
434         try {
435             MusicCore.nonKeyRelatedPut(pQuery, "eventual");
436         } catch (Exception e) {
437                  logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, "Error in deleteKeysFromDB");
438         }
439     }
440 }