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