Update distribution files to support helm charts
[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 && musicCache.get(keySpace)!=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                 CachingUtil.updateMusicCache(keySpace, nameSpace);
188                 return true;
189             //}
190         }
191         logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
192         return false;
193     }
194
195     private static boolean triggerAAF(String nameSpace, String userId, String password)
196                     throws Exception {
197         if (MusicUtil.getAafEndpointUrl() == null) {
198                 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
199             throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
200         }
201         Client client = Client.create();
202         // WebResource webResource =
203         // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
204         WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
205         String plainCreds = userId + ":" + password;
206         byte[] plainCredsBytes = plainCreds.getBytes();
207         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
208         String base64Creds = new String(base64CredsBytes);
209
210         ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
211                         .header("Authorization", "Basic " + base64Creds)
212                         .header("content-type", "application/json").get(ClientResponse.class);
213         if (response.getStatus() != 200) {
214             if (userAttempts.get(nameSpace) == null)
215                 userAttempts.put(nameSpace, 0);
216             if ((Integer) userAttempts.get(nameSpace) >= 2) {
217                 lastFailedTime.put(nameSpace, Calendar.getInstance());
218                 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
219                 throw new Exception(
220                                 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
221             }
222             userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
223             throw new Exception(
224                             "Unable to authenticate. Please check the AAF credentials against namespace.");
225             // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
226             // for specific time.
227         }
228         /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
229                         Arrays.asList(MediaType.APPLICATION_JSON));
230         // AAFResponse output = response.getEntity(AAFResponse.class);
231         response.bufferEntity();
232         String x = response.getEntity(String.class);
233         AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
234         
235         return true;
236     }
237
238     public static void updateMusicCache(String keyspace, String nameSpace) {
239         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
240         musicCache.put(keyspace, nameSpace);
241     }
242
243     public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
244         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
245         Map<String, String> map = new HashMap<>();
246         map.put(userId, password);
247         musicValidateCache.put(nameSpace, map);
248     }
249     
250     public static void updateisAAFCache(String namespace, String isAAF) {
251         appNameCache.put(namespace, isAAF);
252     }
253
254     public static String isAAFApplication(String namespace) throws MusicServiceException {
255         String isAAF = appNameCache.get(namespace);
256         if (isAAF == null) {
257             PreparedQueryObject pQuery = new PreparedQueryObject();
258             pQuery.appendQueryString(
259                             "SELECT is_aaf from admin.keyspace_master where application_name = '"
260                                             + namespace + "' allow filtering");
261             Row rs = null;
262             try {
263                 rs = MusicCore.get(pQuery).one();
264             } catch(InvalidQueryException e) {
265                 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
266                 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
267             }
268             try {
269                 isAAF = String.valueOf(rs.getBool("is_aaf"));
270                 if(isAAF != null)
271                     appNameCache.put(namespace, isAAF);
272             } catch (Exception e) {
273                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
274             }
275         }
276         return isAAF;
277     }
278
279     public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
280         String uuid = null;
281         if (uuid == null) {
282             PreparedQueryObject pQuery = new PreparedQueryObject();
283             pQuery.appendQueryString(
284                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
285                                             + keyspace + "' allow filtering");
286             Row rs = MusicCore.get(pQuery).one();
287             try {
288                 uuid = rs.getUUID("uuid").toString();
289             } catch (Exception e) {
290                 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
291             }
292         }
293         return uuid;
294     }
295
296     public static String getAppName(String keyspace) throws MusicServiceException {
297         String appName = null;
298         PreparedQueryObject pQuery = new PreparedQueryObject();
299         pQuery.appendQueryString(
300                         "SELECT application_name from admin.keyspace_master where keyspace_name = '"
301                                         + keyspace + "' allow filtering");
302         Row rs = MusicCore.get(pQuery).one();
303         try {
304             appName = rs.getString("application_name");
305         } catch (Exception e) {
306                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
307         }
308         return appName;
309     }
310
311     public static String generateUUID() {
312         String uuid = UUID.randomUUID().toString();
313         logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
314         return uuid;
315     }
316
317     public static Map<String, Object> validateRequest(String nameSpace, String userId,
318                     String password, String keyspace, String aid, String operation) {
319         Map<String, Object> resultMap = new HashMap<>();
320         if (!"createKeySpace".equals(operation)) {
321             if (nameSpace == null) {
322                 resultMap.put("Exception", "Application namespace is mandatory.");
323             }
324         }
325         return resultMap;
326
327     }
328
329     public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
330         Map<String, Object> resultMap = new HashMap<>();
331         if (ns == null || userId == null || password == null) {
332                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
333                 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
334             resultMap.put("Exception",
335                             "One or more required headers appName(ns), userId, password is missing. Please check.");
336             return resultMap;
337         }
338         PreparedQueryObject queryObject = new PreparedQueryObject();
339         queryObject.appendQueryString(
340                         "select * from admin.keyspace_master where application_name = ? allow filtering");
341         try {
342                 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
343         } catch(Exception e) {
344                 resultMap.put("Exception",
345                     "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
346                 return resultMap;
347         }
348         Row rs = null;
349                 try {
350                         rs = MusicCore.get(queryObject).one();
351                 } catch (MusicServiceException e) {
352                         // TODO Auto-generated catch block
353                         resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
354                         return resultMap;
355         } catch (InvalidQueryException e) {
356             logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
357             resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
358             return resultMap;
359         }
360         if (rs == null) {
361             logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
362             resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
363         } else {
364                 if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
365                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
366                 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
367                 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
368                 return resultMap;
369             }
370         }
371         return resultMap;
372     }
373
374     public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
375            String keyspace) {
376         Map<String, Object> resultMap = new HashMap<>();
377         String pwd = null;
378         if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null) 
379                 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
380             if(!musicCache.get(keyspace).equals(nameSpace)) {
381                 resultMap.put("Exception", "Namespace and keyspace doesn't match");
382                 return resultMap;
383             }
384             if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
385                 resultMap.put("Exception", "Namespace, userId and password doesn't match");
386                 return resultMap;
387             }
388             return resultMap;
389         }
390         PreparedQueryObject queryObject = new PreparedQueryObject();
391         queryObject.appendQueryString(
392                         "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
393         try {
394             queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
395         } catch (Exception e) {
396                  logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
397         }
398         Row rs = null;
399         try {
400             rs = MusicCore.get(queryObject).one();
401         } catch (MusicServiceException e) {
402                 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
403             return resultMap;
404         }
405         if(rs == null) {
406             resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
407             return resultMap;
408         }
409         else {
410             String user = rs.getString("username");
411             pwd = rs.getString("password");
412             String ns = rs.getString("application_name");
413             if(!ns.equals(nameSpace)) {
414             resultMap.put("Exception", "Namespace and keyspace doesn't match");
415             return resultMap;
416             }
417             if(!user.equals(userId)) {
418                 resultMap.put("Exception", "Invalid userId :"+userId);
419                 return resultMap;
420             }
421             if(!BCrypt.checkpw(password, pwd)) {
422                 resultMap.put("Exception", "Invalid password");
423                 return resultMap;
424             }
425         }
426         CachingUtil.updateMusicCache(keyspace, nameSpace);
427         CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
428         return resultMap;
429     }
430
431     public static void deleteKeysFromDB(String deleteKeys) {
432         PreparedQueryObject pQuery = new PreparedQueryObject();
433         pQuery.appendQueryString(
434                         "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")");
435         try {
436             MusicCore.nonKeyRelatedPut(pQuery, "eventual");
437         } catch (Exception e) {
438                  logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, "Error in deleteKeysFromDB");
439         }
440     }
441 }