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