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 * ====================================================================
25 package org.onap.music.main;
27 import java.util.Calendar;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.UUID;
34 import javax.ws.rs.core.MediaType;
36 import org.apache.commons.codec.binary.Base64;
37 import org.apache.commons.jcs.JCS;
38 import org.apache.commons.jcs.access.CacheAccess;
39 import org.apache.commons.jcs.engine.CompositeCacheAttributes;
40 import org.apache.commons.jcs.engine.ElementAttributes;
41 import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes;
42 import org.apache.commons.jcs.engine.behavior.IElementAttributes;
43 import org.mindrot.jbcrypt.BCrypt;
44 import org.onap.music.datastore.PreparedQueryObject;
45 import org.onap.music.eelf.logging.EELFLoggerDelegate;
46 import org.onap.music.eelf.logging.format.AppMessages;
47 import org.onap.music.eelf.logging.format.ErrorSeverity;
48 import org.onap.music.eelf.logging.format.ErrorTypes;
49 import org.onap.music.exceptions.MusicServiceException;
50 import org.onap.music.service.impl.MusicZKCore;
52 import com.datastax.driver.core.DataType;
53 import com.datastax.driver.core.PreparedStatement;
54 import com.datastax.driver.core.ResultSet;
55 import com.datastax.driver.core.Row;
56 import com.datastax.driver.core.exceptions.InvalidQueryException;
57 import com.sun.jersey.api.client.Client;
58 import com.sun.jersey.api.client.ClientResponse;
59 import com.sun.jersey.api.client.WebResource;
62 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
67 public class CachingUtil implements Runnable {
69 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
71 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
72 private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
73 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
74 private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
75 private static CacheAccess<String, List<String>> callbackNotifyList = JCS.getInstance("eternalCache");
76 private static Map<String, Number> userAttempts = new HashMap<>();
77 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
78 private static CacheAccess<String, PreparedStatement> queryBank = JCS.getInstance("statementBank");
79 private static CacheAccess<String, String> adminUserCache = JCS.getInstance("adminUserCache");
81 public static CacheAccess<String, String> getAdminUserCache() {
82 return adminUserCache;
85 public static void updateAdminUserCache(String authorization,String userId) {
86 adminUserCache.put(authorization,userId);
90 public static void updateStatementBank(String query,PreparedStatement statement) {
91 queryBank.put(query, statement);
94 public static void resetStatementBank() {
98 public static CacheAccess<String, PreparedStatement> getStatementBank() {
102 private static final String USERNAME="username";
103 private static final String PASSWORD="password";
106 public boolean isCacheRefreshNeeded() {
107 if (aafCache.get("initBlankMap") == null)
112 public static void updateCallbackNotifyList(List<String> notifyList) {
113 logger.info("callbackNotifyList: updating cache.....");
114 callbackNotifyList.put("callbackNotify", notifyList);
117 public static List<String> getCallbackNotifyList() {
118 return callbackNotifyList.get("callbackNotify");
121 public void initializeMusicCache() {
122 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
123 musicCache.put("isInitialized", "true");
126 public void initializeAafCache() throws MusicServiceException {
127 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
129 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
130 PreparedQueryObject pQuery = new PreparedQueryObject();
131 pQuery.appendQueryString(query);
133 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
134 } catch (Exception e1) {
135 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
136 e1.printStackTrace();
138 ResultSet rs = MusicCore.get(pQuery);
139 Iterator<Row> it = rs.iterator();
140 Map<String, String> map = null;
141 while (it.hasNext()) {
143 String nameSpace = row.getString("keyspace_name");
144 String userId = row.getString(USERNAME);
145 String password = row.getString(PASSWORD);
146 String keySpace = row.getString("application_name");
148 userAttempts.put(nameSpace, 0);
149 boolean responseObj = triggerAAF(nameSpace, userId, password);
151 map = new HashMap<>();
152 map.put(userId, password);
153 aafCache.put(nameSpace, map);
154 musicCache.put(keySpace, nameSpace);
155 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
158 } catch (Exception e) {
159 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
160 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
169 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
171 initializeAafCache();
172 } catch (MusicServiceException e) {
173 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
177 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
178 String keySpace) throws Exception {
180 if (aafCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) {
181 if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
182 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
183 } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
184 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
185 // reset invalid attempts to 0
186 userAttempts.put(nameSpace, 0);
189 // call AAF update cache with new password
190 if (userAttempts.get(nameSpace) == null)
191 userAttempts.put(nameSpace, 0);
192 if ((Integer) userAttempts.get(nameSpace) >= 3) {
193 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
194 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
195 Calendar calendar = Calendar.getInstance();
196 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
197 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
198 if( delayTime > 120000) {
199 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
200 userAttempts.put(nameSpace, 0);
202 logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
203 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
206 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
207 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
211 boolean responseObj = false;
213 responseObj = triggerAAF(nameSpace, userId, password);
214 }catch (Exception ex) {
215 logger.info("Exception while trigger aaf");
216 logger.info("Exception: " + ex.getMessage());
217 throw new Exception("Exception raised while triggering AAF authentication" +ex.getMessage());
220 logger.info(EELFLoggerDelegate.applicationLogger,"Valid user. Cache is updated for "+nameSpace);
221 Map<String, String> map = new HashMap<>();
222 map.put(userId, password);
223 aafCache.put(nameSpace, map);
224 musicCache.put(keySpace, nameSpace);
227 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
231 private static boolean triggerAAF(String nameSpace, String userId, String password)
233 logger.info(EELFLoggerDelegate.applicationLogger,"Inside AAF authorization");
234 if (MusicUtil.getAafEndpointUrl() == null) {
235 logger.error(EELFLoggerDelegate.errorLogger,"AAF endpoint is not set. Please specify in the properties file.",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
236 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
238 Client client = Client.create();
239 // WebResource webResource =
240 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
241 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
242 String plainCreds = userId + ":" + password;
243 byte[] plainCredsBytes = plainCreds.getBytes();
244 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
245 String base64Creds = new String(base64CredsBytes);
247 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
248 .header("Authorization", "Basic " + base64Creds)
249 .header("content-type", "application/json").get(ClientResponse.class);
250 logger.info(EELFLoggerDelegate.applicationLogger, "aaf response: "+response.toString());
251 if (response.getStatus() != 200) {
252 if (userAttempts.get(nameSpace) == null)
253 userAttempts.put(nameSpace, 0);
254 if ((Integer) userAttempts.get(nameSpace) >= 2) {
255 lastFailedTime.put(nameSpace, Calendar.getInstance());
256 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
258 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
260 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
262 "Unable to authenticate. Please check the AAF credentials against namespace.");
263 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
264 // for specific time.
266 /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
267 Arrays.asList(MediaType.APPLICATION_JSON));
268 // AAFResponse output = response.getEntity(AAFResponse.class);
269 response.bufferEntity();
270 String x = response.getEntity(String.class);
271 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
276 public static void updateMusicCache(String keyspace, String nameSpace) {
277 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
278 musicCache.put(keyspace, nameSpace);
281 public static void updateCadiCache(String user, String keyspace) {
282 musicCache.put(user, keyspace);
285 public static String getKSFromCadiCache(String user) {
286 return musicCache.get(user);
289 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
290 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
291 Map<String, String> map = new HashMap<>();
292 map.put(userId, password);
293 musicValidateCache.put(nameSpace, map);
296 public static void updateisAAFCache(String namespace, String isAAF) {
297 appNameCache.put(namespace, isAAF);
300 public static String isAAFApplication(String namespace) throws MusicServiceException {
301 String isAAF = appNameCache.get(namespace);
303 PreparedQueryObject pQuery = new PreparedQueryObject();
304 pQuery.appendQueryString(
305 "SELECT is_aaf from admin.keyspace_master where application_name = '"
306 + namespace + "' allow filtering");
309 rs = MusicCore.get(pQuery).one();
310 } catch(InvalidQueryException e) {
311 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
312 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
315 isAAF = String.valueOf(rs.getBool("is_aaf"));
317 appNameCache.put(namespace, isAAF);
318 } catch (Exception e) {
319 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
326 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
329 PreparedQueryObject pQuery = new PreparedQueryObject();
330 pQuery.appendQueryString(
331 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
332 + keyspace + "' allow filtering");
333 Row rs = MusicCore.get(pQuery).one();
335 uuid = rs.getUUID("uuid").toString();
336 } catch (Exception e) {
337 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
344 public static String getAppName(String keyspace) throws MusicServiceException {
345 String appName = null;
346 PreparedQueryObject pQuery = new PreparedQueryObject();
347 pQuery.appendQueryString(
348 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
349 + keyspace + "' allow filtering");
350 Row rs = MusicCore.get(pQuery).one();
352 appName = rs.getString("application_name");
353 } catch (Exception e) {
354 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
360 public static String generateUUID() {
361 String uuid = UUID.randomUUID().toString();
362 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
366 public static Map<String, Object> validateRequest(String nameSpace, String userId,
367 String password, String keyspace, String aid, String operation) {
368 Map<String, Object> resultMap = new HashMap<>();
369 if (!"createKeySpace".equals(operation)) {
370 if (nameSpace == null) {
371 resultMap.put("Exception", "Application namespace is mandatory.");
378 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
379 Map<String, Object> resultMap = new HashMap<>();
380 if (ns == null || userId == null || password == null) {
381 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
382 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
383 resultMap.put("Exception",
384 "One or more required headers appName(ns), userId, password is missing. Please check.");
387 PreparedQueryObject queryObject = new PreparedQueryObject();
388 queryObject.appendQueryString(
389 "select * from admin.keyspace_master where application_name = ? allow filtering");
391 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
392 } catch(Exception e) {
393 resultMap.put("Exception",
394 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
399 rs = MusicCore.get(queryObject).one();
400 } catch (MusicServiceException e) {
401 // TODO Auto-generated catch block
403 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
405 } catch (InvalidQueryException e) {
406 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
407 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
411 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
412 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
414 if(!(rs.getString(USERNAME).equals(userId)) || !(BCrypt.checkpw(password, rs.getString(PASSWORD)))) {
415 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
416 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
417 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
424 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
426 Map<String, Object> resultMap = new HashMap<>();
428 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
429 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
430 if(!musicCache.get(keyspace).equals(nameSpace)) {
431 resultMap.put("Exception", "Namespace and keyspace doesn't match");
434 if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
435 resultMap.put("Exception", "Namespace, userId and password doesn't match");
440 PreparedQueryObject queryObject = new PreparedQueryObject();
441 queryObject.appendQueryString(
442 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
444 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
445 } catch (Exception e) {
450 rs = MusicCore.get(queryObject).one();
451 } catch (MusicServiceException e) {
453 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
457 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
461 String user = rs.getString(USERNAME);
462 pwd = rs.getString(PASSWORD);
463 String ns = rs.getString("application_name");
464 if(!ns.equals(nameSpace)) {
465 resultMap.put("Exception", "Namespace and keyspace doesn't match");
468 if(!user.equals(userId)) {
469 resultMap.put("Exception", "Invalid userId :"+userId);
472 if(!BCrypt.checkpw(password, pwd)) {
473 resultMap.put("Exception", "Invalid password");
477 CachingUtil.updateMusicCache(keyspace, nameSpace);
478 CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
482 public static void deleteKeysFromDB(String deleteKeys) {
483 PreparedQueryObject pQuery = new PreparedQueryObject();
484 pQuery.appendQueryString(
485 "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")");
487 MusicCore.nonKeyRelatedPut(pQuery, "eventual");
488 } catch (Exception e) {