2 * ============LICENSE_START==========================================
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
14 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 * ============LICENSE_END=============================================
23 * ====================================================================
26 package org.onap.music.authentication;
28 import java.util.Calendar;
29 import java.util.HashMap;
30 import java.util.Iterator;
32 import javax.ws.rs.core.MediaType;
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;
60 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
65 public class CachingUtil implements Runnable {
67 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
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");
79 public static CacheAccess<String, String> getAdminUserCache() {
80 return adminUserCache;
83 public static void updateAdminUserCache(String authorization,String userId) {
84 adminUserCache.put(authorization,userId);
87 private static final String USERNAME="username";
88 private static final String PASSWORD="password";
91 public void initializeAafCache() throws MusicServiceException {
92 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
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);
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);
103 ResultSet rs = MusicCore.get(pQuery);
104 Iterator<Row> it = rs.iterator();
105 Map<String, String> map = null;
106 while (it.hasNext()) {
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");
113 userAttempts.put(nameSpace, 0);
114 boolean responseObj = triggerAAF(nameSpace, userId, password);
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 "
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. ");
134 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
136 initializeAafCache();
137 } catch (MusicServiceException e) {
138 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO,
139 ErrorTypes.GENERALSERVICEERROR, e);
143 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
144 String keySpace) throws Exception {
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);
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);
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.");
172 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
173 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
177 boolean responseObj = false;
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());
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);
193 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
197 private static boolean triggerAAF(String nameSpace, String userId, String password)
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.");
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);
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));
222 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
224 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
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.
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);*/
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);
245 public static void updateCadiCache(String user, String keyspace) {
246 musicCache.put(user, keyspace);
249 public static String getKSFromCadiCache(String user) {
250 return musicCache.get(user);
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);
260 public static void updateisAAFCache(String namespace, String isAAF) {
261 appNameCache.put(namespace, isAAF);
264 public static String isAAFApplication(String namespace) throws MusicServiceException {
265 String isAAF = appNameCache.get(namespace);
267 PreparedQueryObject pQuery = new PreparedQueryObject();
268 pQuery.appendQueryString(
269 "SELECT is_aaf from admin.keyspace_master where application_name = '"
270 + namespace + "' allow filtering");
273 rs = MusicCore.get(pQuery).one();
274 } catch(InvalidQueryException e) {
275 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+ e.getMessage
277 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
280 isAAF = String.valueOf(rs.getBool("is_aaf"));
282 appNameCache.put(namespace, isAAF);
283 } catch (Exception e) {
284 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity
285 .ERROR, ErrorTypes.QUERYERROR, e);
291 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
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();
300 uuid = rs.getUUID("uuid").toString();
301 } catch (Exception e) {
302 logger.error(EELFLoggerDelegate.errorLogger,"Exception occurred during uuid retrieval from DB."+e
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();
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);
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.");
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.");
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.");
357 PreparedQueryObject queryObject = new PreparedQueryObject();
358 queryObject.appendQueryString(
359 "select * from admin.keyspace_master where application_name = ? allow filtering");
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());
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);
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.");
381 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
382 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
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);
394 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
396 Map<String, Object> resultMap = new HashMap<>();
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");
404 if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
405 resultMap.put("Exception", "Namespace, userId and password doesn't match");
410 PreparedQueryObject queryObject = new PreparedQueryObject();
411 queryObject.appendQueryString(
412 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
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);
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);
428 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
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");
439 if(!user.equals(userId)) {
440 resultMap.put("Exception", "Invalid userId :"+userId);
443 if(!BCrypt.checkpw(password, pwd)) {
444 resultMap.put("Exception", "Invalid password");
448 CachingUtil.updateMusicCache(keyspace, nameSpace);
449 CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);