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