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