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