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