2 * ============LICENSE_START==========================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 * ============LICENSE_END=============================================
22 * ====================================================================
24 package org.onap.music.main;
26 import java.util.Calendar;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.UUID;
32 import javax.ws.rs.core.MediaType;
33 import org.apache.commons.codec.binary.Base64;
34 import org.apache.commons.jcs.JCS;
35 import org.apache.commons.jcs.access.CacheAccess;
36 import org.mindrot.jbcrypt.BCrypt;
37 import org.onap.music.datastore.PreparedQueryObject;
38 import org.onap.music.eelf.logging.EELFLoggerDelegate;
39 import org.onap.music.eelf.logging.format.AppMessages;
40 import org.onap.music.eelf.logging.format.ErrorSeverity;
41 import org.onap.music.eelf.logging.format.ErrorTypes;
42 import org.onap.music.exceptions.MusicServiceException;
43 import org.onap.music.datastore.jsonobjects.JsonCallback;
44 import com.datastax.driver.core.DataType;
45 import com.datastax.driver.core.ResultSet;
46 import com.datastax.driver.core.Row;
47 import com.datastax.driver.core.exceptions.InvalidQueryException;
48 import com.sun.jersey.api.client.Client;
49 import com.sun.jersey.api.client.ClientResponse;
50 import com.sun.jersey.api.client.WebResource;
53 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
58 public class CachingUtil implements Runnable {
60 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
62 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
63 private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
64 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
65 private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
66 private static CacheAccess<String, JsonCallback> callBackCache = JCS.getInstance("callBackCache");
67 private static CacheAccess<String, List<String>> callbackNotifyList = JCS.getInstance("callbackNotifyList");
68 private static Map<String, Number> userAttempts = new HashMap<>();
69 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
71 private static final String USERNAME="username";
72 private static final String PASSWORD="password";
74 public boolean isCacheRefreshNeeded() {
75 if (aafCache.get("initBlankMap") == null)
80 public static void updateCallBackCache(String appName, JsonCallback jsonCallBack) {
81 logger.info("updateCallBackCache: updating cache.....");
82 callBackCache.put(appName, jsonCallBack);
85 public static JsonCallback getCallBackCache(String appName) {
86 return callBackCache.get(appName);
89 public static void updateCallbackNotifyList(List<String> notifyList) {
90 logger.info("callbackNotifyList: updating cache.....");
91 callbackNotifyList.put("callbackNotify", notifyList);
94 public static List<String> getCallbackNotifyList() {
95 return callbackNotifyList.get("callbackNotify");
98 public void initializeMusicCache() {
99 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
100 musicCache.put("isInitialized", "true");
103 public void initializeAafCache() throws MusicServiceException {
104 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
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);
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);
114 ResultSet rs = MusicCore.get(pQuery);
115 Iterator<Row> it = rs.iterator();
116 Map<String, String> map = null;
117 while (it.hasNext()) {
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");
124 userAttempts.put(nameSpace, 0);
125 boolean responseObj = triggerAAF(nameSpace, userId, password);
127 map = new HashMap<>();
128 map.put(userId, password);
129 aafCache.put(nameSpace, map);
130 musicCache.put(keySpace, nameSpace);
131 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
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. ");
144 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
146 initializeAafCache();
147 } catch (MusicServiceException e) {
148 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
152 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
153 String keySpace) throws Exception {
155 if (aafCache.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 (aafCache.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);
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);
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.");
181 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
182 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
186 boolean responseObj = triggerAAF(nameSpace, userId, password);
188 //if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
189 Map<String, String> map = new HashMap<>();
190 map.put(userId, password);
191 aafCache.put(nameSpace, map);
192 CachingUtil.updateMusicCache(keySpace, nameSpace);
196 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
200 private static boolean triggerAAF(String nameSpace, String userId, String password)
202 if (MusicUtil.getAafEndpointUrl() == null) {
203 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
204 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
206 Client client = Client.create();
207 // WebResource webResource =
208 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
209 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
210 String plainCreds = userId + ":" + password;
211 byte[] plainCredsBytes = plainCreds.getBytes();
212 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
213 String base64Creds = new String(base64CredsBytes);
215 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
216 .header("Authorization", "Basic " + base64Creds)
217 .header("content-type", "application/json").get(ClientResponse.class);
218 if (response.getStatus() != 200) {
219 if (userAttempts.get(nameSpace) == null)
220 userAttempts.put(nameSpace, 0);
221 if ((Integer) userAttempts.get(nameSpace) >= 2) {
222 lastFailedTime.put(nameSpace, Calendar.getInstance());
223 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
225 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
227 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
229 "Unable to authenticate. Please check the AAF credentials against namespace.");
230 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
231 // for specific time.
233 /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
234 Arrays.asList(MediaType.APPLICATION_JSON));
235 // AAFResponse output = response.getEntity(AAFResponse.class);
236 response.bufferEntity();
237 String x = response.getEntity(String.class);
238 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
243 public static void updateMusicCache(String keyspace, String nameSpace) {
244 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
245 musicCache.put(keyspace, nameSpace);
248 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
249 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
250 Map<String, String> map = new HashMap<>();
251 map.put(userId, password);
252 musicValidateCache.put(nameSpace, map);
255 public static void updateisAAFCache(String namespace, String isAAF) {
256 appNameCache.put(namespace, isAAF);
259 public static String isAAFApplication(String namespace) throws MusicServiceException {
260 String isAAF = appNameCache.get(namespace);
262 PreparedQueryObject pQuery = new PreparedQueryObject();
263 pQuery.appendQueryString(
264 "SELECT is_aaf from admin.keyspace_master where application_name = '"
265 + namespace + "' allow filtering");
268 rs = MusicCore.get(pQuery).one();
269 } catch(InvalidQueryException e) {
270 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
271 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
274 isAAF = String.valueOf(rs.getBool("is_aaf"));
276 appNameCache.put(namespace, isAAF);
277 } catch (Exception e) {
278 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
284 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
287 PreparedQueryObject pQuery = new PreparedQueryObject();
288 pQuery.appendQueryString(
289 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
290 + keyspace + "' allow filtering");
291 Row rs = MusicCore.get(pQuery).one();
293 uuid = rs.getUUID("uuid").toString();
294 } catch (Exception e) {
295 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
301 public static String getAppName(String keyspace) throws MusicServiceException {
302 String appName = null;
303 PreparedQueryObject pQuery = new PreparedQueryObject();
304 pQuery.appendQueryString(
305 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
306 + keyspace + "' allow filtering");
307 Row rs = MusicCore.get(pQuery).one();
309 appName = rs.getString("application_name");
310 } catch (Exception e) {
311 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
316 public static String generateUUID() {
317 String uuid = UUID.randomUUID().toString();
318 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
322 public static Map<String, Object> validateRequest(String nameSpace, String userId,
323 String password, String keyspace, String aid, String operation) {
324 Map<String, Object> resultMap = new HashMap<>();
325 if (!"createKeySpace".equals(operation)) {
326 if (nameSpace == null) {
327 resultMap.put("Exception", "Application namespace is mandatory.");
334 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
335 Map<String, Object> resultMap = new HashMap<>();
336 if (ns == null || userId == null || password == null) {
337 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
338 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
339 resultMap.put("Exception",
340 "One or more required headers appName(ns), userId, password is missing. Please check.");
343 PreparedQueryObject queryObject = new PreparedQueryObject();
344 queryObject.appendQueryString(
345 "select * from admin.keyspace_master where application_name = ? allow filtering");
347 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
348 } catch(Exception e) {
349 resultMap.put("Exception",
350 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
355 rs = MusicCore.get(queryObject).one();
356 } catch (MusicServiceException e) {
357 // TODO Auto-generated catch block
358 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
360 } catch (InvalidQueryException e) {
361 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
362 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
366 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
367 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
369 if(!(rs.getString(USERNAME).equals(userId)) || !(BCrypt.checkpw(password, rs.getString(PASSWORD)))) {
370 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
371 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
372 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
379 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
381 Map<String, Object> resultMap = new HashMap<>();
383 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
384 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
385 if(!musicCache.get(keyspace).equals(nameSpace)) {
386 resultMap.put("Exception", "Namespace and keyspace doesn't match");
389 if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
390 resultMap.put("Exception", "Namespace, userId and password doesn't match");
395 PreparedQueryObject queryObject = new PreparedQueryObject();
396 queryObject.appendQueryString(
397 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
399 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
400 } catch (Exception e) {
401 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
405 rs = MusicCore.get(queryObject).one();
406 } catch (MusicServiceException e) {
407 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
411 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
415 String user = rs.getString(USERNAME);
416 pwd = rs.getString(PASSWORD);
417 String ns = rs.getString("application_name");
418 if(!ns.equals(nameSpace)) {
419 resultMap.put("Exception", "Namespace and keyspace doesn't match");
422 if(!user.equals(userId)) {
423 resultMap.put("Exception", "Invalid userId :"+userId);
426 if(!BCrypt.checkpw(password, pwd)) {
427 resultMap.put("Exception", "Invalid password");
431 CachingUtil.updateMusicCache(keyspace, nameSpace);
432 CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
436 public static void deleteKeysFromDB(String deleteKeys) {
437 PreparedQueryObject pQuery = new PreparedQueryObject();
438 pQuery.appendQueryString(
439 "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")");
441 MusicCore.nonKeyRelatedPut(pQuery, "eventual");
442 } catch (Exception e) {
443 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, "Error in deleteKeysFromDB");