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