aee3abbf4ef8227e310049e2d20200467b986a13
[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.onap.music.datastore.PreparedQueryObject;
37 import org.onap.music.datastore.jsonobjects.AAFResponse;
38 import org.onap.music.eelf.logging.EELFLoggerDelegate;
39 import org.onap.music.eelf.logging.format.AppMessages;
40 import org.onap.music.eelf.logging.format.ErrorSeverity;
41 import org.onap.music.eelf.logging.format.ErrorTypes;
42 import org.onap.music.exceptions.MusicServiceException;
43
44 import com.att.eelf.configuration.EELFLogger;
45 import com.datastax.driver.core.DataType;
46 import com.datastax.driver.core.ResultSet;
47 import com.datastax.driver.core.Row;
48 import com.sun.jersey.api.client.Client;
49 import com.sun.jersey.api.client.ClientResponse;
50 import com.sun.jersey.api.client.WebResource;
51
52 /**
53  * All Caching related logic is handled by this class and a schedule cron runs to update cache.
54  * 
55  * @author Vikram
56  *
57  */
58 public class CachingUtil implements Runnable {
59
60     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
61
62     private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
63     private static CacheAccess<String, String> musicLockCache = JCS.getInstance("musicLockCache");
64     private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
65     private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
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 void initializeMusicCache() {
76         logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
77         musicCache.put("isInitialized", "true");
78     }
79
80     public void initializeAafCache() throws MusicServiceException {
81         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
82
83         String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
84         PreparedQueryObject pQuery = new PreparedQueryObject();
85         pQuery.appendQueryString(query);
86         try {
87             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
88         } catch (Exception e1) {
89             logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
90             e1.printStackTrace();
91         }
92         ResultSet rs = MusicCore.get(pQuery);
93         Iterator<Row> it = rs.iterator();
94         Map<String, String> map = null;
95         while (it.hasNext()) {
96             Row row = it.next();
97             String nameSpace = row.getString("keyspace_name");
98             String userId = row.getString("username");
99             String password = row.getString("password");
100             String keySpace = row.getString("application_name");
101             String uuid = row.getUUID("uuid").toString();
102             try {
103                 userAttempts.put(nameSpace, 0);
104                 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
105                 if (responseObj.getNs().size() > 0) {
106                     map = new HashMap<>();
107                     map.put(userId, password);
108                     aafCache.put(nameSpace, map);
109                     musicCache.put(nameSpace, keySpace);
110                     musicLockCache.put(nameSpace, uuid);
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(nameSpace).equals(keySpace)) {
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 Map<String, Object> authenticateAIDUser(String aid, String keyspace)
224                     throws Exception {
225         Map<String, Object> resultMap = new HashMap<>();
226         String uuid = null;
227         /*
228          * if(aid == null || aid.length() == 0) { resultMap.put("Exception Message",
229          * "AID is missing for the keyspace requested."); //create a new AID ?? } else
230          */
231         if (musicCache.get(keyspace) == null) {
232             PreparedQueryObject pQuery = new PreparedQueryObject();
233             pQuery.appendQueryString(
234                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
235                                             + keyspace + "' allow filtering");
236             Row rs = MusicCore.get(pQuery).one();
237             try {
238                 uuid = rs.getUUID("uuid").toString();
239                 musicCache.put(keyspace, uuid);
240             } catch (Exception e) {
241                 String msg = e.getMessage();
242                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
243                 resultMap.put("Exception", "Unauthorized operation. Check AID and Keyspace. "
244                                 + "Exception from MUSIC is: "
245                                 + (msg == null ? "Keyspace is new so no AID should be passed in Header."
246                                                 : msg));
247                 return resultMap;
248             }
249             if (!musicCache.get(keyspace).toString().equals(aid)) {
250                 resultMap.put("Exception Message",
251                                 "Unauthorized operation. Invalid AID for the keyspace");
252                 return resultMap;
253             }
254         } else if (musicCache.get(keyspace) != null
255                         && !musicCache.get(keyspace).toString().equals(aid)) {
256             resultMap.put("Exception Message",
257                             "Unauthorized operation. Invalid AID for the keyspace");
258             return resultMap;
259         }
260         resultMap.put("aid", uuid);
261         return resultMap;
262     }
263     
264     
265     public static Map<String, Object> authenticateAIDUserLock(String aid, String nameSpace)
266             throws Exception {
267                 Map<String, Object> resultMap = new HashMap<>();
268                 String uuid = null;
269                 
270                 if (musicLockCache.get(nameSpace) == null) {
271                     PreparedQueryObject pQuery = new PreparedQueryObject();
272                     pQuery.appendQueryString(
273                                     "SELECT uuid from admin.keyspace_master where application_name = '"
274                                                     + nameSpace + "' allow filtering");
275                     Row rs = MusicCore.get(pQuery).one();
276                     try {
277                         uuid = rs.getUUID("uuid").toString();
278                         musicLockCache.put(nameSpace, uuid);
279                     } catch (Exception e) {
280                         logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
281                         resultMap.put("Exception", "Unauthorized operation. Check AID and Namespace. ");
282                         return resultMap;
283                     }
284                     if (!musicLockCache.get(nameSpace).toString().equals(aid)) {
285                         resultMap.put("Exception Message",
286                                         "Unauthorized operation. Invalid AID for the Namespace");
287                         return resultMap;
288                     }
289                 } else if (musicLockCache.get(nameSpace) != null
290                                 && !musicLockCache.get(nameSpace).toString().equals(aid)) {
291                     resultMap.put("Exception Message",
292                                     "Unauthorized operation. Invalid AID for the Namespace");
293                     return resultMap;
294                 }
295                 return resultMap;
296         }
297     
298     
299     
300
301     public static void updateMusicCache(String aid, String keyspace) {
302         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with aid " + aid);
303         musicCache.put(keyspace, aid);
304     }
305
306     public static void updateisAAFCache(String namespace, String isAAF) {
307         appNameCache.put(namespace, isAAF);
308     }
309
310     public static Boolean isAAFApplication(String namespace) throws MusicServiceException {
311
312         String isAAF = appNameCache.get(namespace);
313         if (isAAF == null) {
314             PreparedQueryObject pQuery = new PreparedQueryObject();
315             pQuery.appendQueryString(
316                             "SELECT is_aaf from admin.keyspace_master where application_name = '"
317                                             + namespace + "' allow filtering");
318             Row rs = MusicCore.get(pQuery).one();
319             try {
320                 isAAF = String.valueOf(rs.getBool("is_aaf"));
321                 appNameCache.put(namespace, isAAF);
322             } catch (Exception e) {
323                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
324                 e.printStackTrace();
325             }
326         }
327
328         return Boolean.valueOf(isAAF);
329     }
330
331     public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
332         String uuid = musicCache.get(keyspace);
333         if (uuid == null) {
334             PreparedQueryObject pQuery = new PreparedQueryObject();
335             pQuery.appendQueryString(
336                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
337                                             + keyspace + "' allow filtering");
338             Row rs = MusicCore.get(pQuery).one();
339             try {
340                 uuid = rs.getUUID("uuid").toString();
341                 musicCache.put(keyspace, uuid);
342             } catch (Exception e) {
343                 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
344                 e.printStackTrace();
345             }
346         }
347         return uuid;
348     }
349
350     public static String getAppName(String keyspace) throws MusicServiceException {
351         String appName = null;
352         PreparedQueryObject pQuery = new PreparedQueryObject();
353         pQuery.appendQueryString(
354                         "SELECT application_name from admin.keyspace_master where keyspace_name = '"
355                                         + keyspace + "' allow filtering");
356         Row rs = MusicCore.get(pQuery).one();
357         try {
358             appName = rs.getString("application_name");
359         } catch (Exception e) {
360                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
361             e.printStackTrace();
362         }
363         return appName;
364     }
365
366     public static String generateUUID() {
367         String uuid = UUID.randomUUID().toString();
368         logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
369         return uuid;
370     }
371
372     public static Map<String, Object> validateRequest(String nameSpace, String userId,
373                     String password, String keyspace, String aid, String operation) {
374         Map<String, Object> resultMap = new HashMap<>();
375         if (!"createKeySpace".equals(operation)) {
376             if (nameSpace == null) {
377                 resultMap.put("Exception", "Application namespace is mandatory.");
378             }
379         }
380         return resultMap;
381
382     }
383
384     public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
385         Map<String, Object> resultMap = new HashMap<>();
386         if (ns == null || userId == null || password == null) {
387                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
388                 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
389             resultMap.put("Exception",
390                             "One or more required headers appName(ns), userId, password is missing. Please check.");
391             return resultMap;
392         }
393         PreparedQueryObject queryObject = new PreparedQueryObject();
394         queryObject.appendQueryString(
395                         "select * from admin.keyspace_master where application_name = ? allow filtering");
396         try {
397                 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
398         } catch(Exception e) {
399                 resultMap.put("Exception",
400                     "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
401                 return resultMap;
402         }
403         Row rs = null;
404                 try {
405                         rs = MusicCore.get(queryObject).one();
406                 } catch (MusicServiceException e) {
407                         // TODO Auto-generated catch block
408                         e.printStackTrace();
409                         resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
410                         return resultMap;
411                 }
412         if (rs == null) {
413             logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
414             resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
415         } else {
416             if(!(rs.getString("username").equals(userId)) && !(rs.getString("password").equals("password"))) {
417                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
418                 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
419                 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
420                 return resultMap;
421             }
422             boolean is_aaf = rs.getBool("is_aaf");
423             String keyspace = rs.getString("keyspace_name");
424             if (!is_aaf) {
425                 if (!keyspace.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
426                     logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.DATAERROR);
427                     logger.error(EELFLoggerDelegate.errorLogger,"Non AAF applications are allowed to have only one keyspace per application.");
428                     resultMap.put("Exception",
429                                     "Non AAF applications are allowed to have only one keyspace per application.");
430                 }
431             }
432         }
433         return resultMap;
434     }
435 }