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