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