2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2017 AT&T Intellectual Property
6 * ===================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * ============LICENSE_END=============================================
20 * ====================================================================
22 package org.onap.music.main;
24 import java.util.ArrayList;
25 import java.util.Arrays;
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.HttpHeaders;
33 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.codehaus.jackson.map.ObjectMapper;
38 import org.mindrot.jbcrypt.BCrypt;
39 import org.onap.music.datastore.PreparedQueryObject;
40 import org.onap.music.datastore.jsonobjects.AAFResponse;
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.datastore.jsonobjects.JsonNotification;
47 import org.onap.music.datastore.jsonobjects.JsonCallback;
48 import com.att.eelf.configuration.EELFLogger;
49 import com.datastax.driver.core.DataType;
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;
58 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
63 public class CachingUtil implements Runnable {
65 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
67 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
68 private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
69 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
70 private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
71 private static CacheAccess<String, JsonCallback> callBackCache = JCS.getInstance("callBackCache");
72 private static CacheAccess<String, List<String>> callbackNotifyList = JCS.getInstance("callbackNotifyList");
73 private static Map<String, Number> userAttempts = new HashMap<>();
74 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
76 public boolean isCacheRefreshNeeded() {
77 if (aafCache.get("initBlankMap") == null)
82 public static void updateCallBackCache(String appName, JsonCallback jsonCallBack) {
83 logger.info("updateCallBackCache: updating cache.....");
84 callBackCache.put(appName, jsonCallBack);
87 public static JsonCallback getCallBackCache(String appName) {
88 return callBackCache.get(appName);
91 public static void updateCallbackNotifyList(List<String> notifyList) {
92 logger.info("callbackNotifyList: updating cache.....");
93 callbackNotifyList.put("callbackNotify", notifyList);
96 public static List<String> getCallbackNotifyList() {
97 return callbackNotifyList.get("callbackNotify");
100 public void initializeMusicCache() {
101 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
102 musicCache.put("isInitialized", "true");
105 public void initializeAafCache() throws MusicServiceException {
106 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
108 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
109 PreparedQueryObject pQuery = new PreparedQueryObject();
110 pQuery.appendQueryString(query);
112 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
113 } catch (Exception e1) {
114 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
115 e1.printStackTrace();
117 ResultSet rs = MusicCore.get(pQuery);
118 Iterator<Row> it = rs.iterator();
119 Map<String, String> map = null;
120 while (it.hasNext()) {
122 String nameSpace = row.getString("keyspace_name");
123 String userId = row.getString("username");
124 String password = row.getString("password");
125 String keySpace = row.getString("application_name");
127 userAttempts.put(nameSpace, 0);
128 boolean responseObj = triggerAAF(nameSpace, userId, password);
130 map = new HashMap<>();
131 map.put(userId, password);
132 aafCache.put(nameSpace, map);
133 musicCache.put(keySpace, nameSpace);
134 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
137 } catch (Exception e) {
138 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
139 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
148 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
150 initializeAafCache();
151 } catch (MusicServiceException e) {
152 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
156 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
157 String keySpace) throws Exception {
159 if (aafCache.get(nameSpace) != null) {
160 if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
161 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
162 } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
163 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
164 // reset invalid attempts to 0
165 userAttempts.put(nameSpace, 0);
168 // call AAF update cache with new password
169 if (userAttempts.get(nameSpace) == null)
170 userAttempts.put(nameSpace, 0);
171 if ((Integer) userAttempts.get(nameSpace) >= 3) {
172 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
173 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
174 Calendar calendar = Calendar.getInstance();
175 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
176 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
177 if( delayTime > 120000) {
178 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
179 userAttempts.put(nameSpace, 0);
181 logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
182 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
185 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
186 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
190 boolean responseObj = triggerAAF(nameSpace, userId, password);
192 //if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
193 //Map<String, String> map = new HashMap<>();
194 //map.put(userId, password);
195 //aafCache.put(nameSpace, map);
199 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
203 private static boolean triggerAAF(String nameSpace, String userId, String password)
205 if (MusicUtil.getAafEndpointUrl() == null) {
206 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
207 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
209 Client client = Client.create();
210 // WebResource webResource =
211 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
212 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
213 String plainCreds = userId + ":" + password;
214 byte[] plainCredsBytes = plainCreds.getBytes();
215 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
216 String base64Creds = new String(base64CredsBytes);
218 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
219 .header("Authorization", "Basic " + base64Creds)
220 .header("content-type", "application/json").get(ClientResponse.class);
221 if (response.getStatus() != 200) {
222 if (userAttempts.get(nameSpace) == null)
223 userAttempts.put(nameSpace, 0);
224 if ((Integer) userAttempts.get(nameSpace) >= 2) {
225 lastFailedTime.put(nameSpace, Calendar.getInstance());
226 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
228 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
230 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
232 "Unable to authenticate. Please check the AAF credentials against namespace.");
233 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
234 // for specific time.
236 /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
237 Arrays.asList(MediaType.APPLICATION_JSON));
238 // AAFResponse output = response.getEntity(AAFResponse.class);
239 response.bufferEntity();
240 String x = response.getEntity(String.class);
241 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
246 public static void updateMusicCache(String keyspace, String nameSpace) {
247 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
248 musicCache.put(keyspace, nameSpace);
251 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
252 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
253 Map<String, String> map = new HashMap<>();
254 map.put(userId, password);
255 musicValidateCache.put(nameSpace, map);
258 public static void updateisAAFCache(String namespace, String isAAF) {
259 appNameCache.put(namespace, isAAF);
262 public static String isAAFApplication(String namespace) throws MusicServiceException {
263 String isAAF = appNameCache.get(namespace);
265 PreparedQueryObject pQuery = new PreparedQueryObject();
266 pQuery.appendQueryString(
267 "SELECT is_aaf from admin.keyspace_master where application_name = '"
268 + namespace + "' allow filtering");
271 rs = MusicCore.get(pQuery).one();
272 } catch(InvalidQueryException e) {
273 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
274 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
277 isAAF = String.valueOf(rs.getBool("is_aaf"));
279 appNameCache.put(namespace, isAAF);
280 } catch (Exception e) {
281 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
288 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
291 PreparedQueryObject pQuery = new PreparedQueryObject();
292 pQuery.appendQueryString(
293 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
294 + keyspace + "' allow filtering");
295 Row rs = MusicCore.get(pQuery).one();
297 uuid = rs.getUUID("uuid").toString();
298 } catch (Exception e) {
299 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
306 public static String getAppName(String keyspace) throws MusicServiceException {
307 String appName = null;
308 PreparedQueryObject pQuery = new PreparedQueryObject();
309 pQuery.appendQueryString(
310 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
311 + keyspace + "' allow filtering");
312 Row rs = MusicCore.get(pQuery).one();
314 appName = rs.getString("application_name");
315 } catch (Exception e) {
316 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
322 public static String generateUUID() {
323 String uuid = UUID.randomUUID().toString();
324 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
328 public static Map<String, Object> validateRequest(String nameSpace, String userId,
329 String password, String keyspace, String aid, String operation) {
330 Map<String, Object> resultMap = new HashMap<>();
331 if (!"createKeySpace".equals(operation)) {
332 if (nameSpace == null) {
333 resultMap.put("Exception", "Application namespace is mandatory.");
340 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
341 Map<String, Object> resultMap = new HashMap<>();
342 if (ns == null || userId == null || password == null) {
343 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
344 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
345 resultMap.put("Exception",
346 "One or more required headers appName(ns), userId, password is missing. Please check.");
349 PreparedQueryObject queryObject = new PreparedQueryObject();
350 queryObject.appendQueryString(
351 "select * from admin.keyspace_master where application_name = ? allow filtering");
353 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
354 } catch(Exception e) {
355 resultMap.put("Exception",
356 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
361 rs = MusicCore.get(queryObject).one();
362 } catch (MusicServiceException e) {
363 // TODO Auto-generated catch block
365 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
367 } catch (InvalidQueryException e) {
368 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
369 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
373 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
374 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
376 if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
377 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
378 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
379 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
386 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
388 Map<String, Object> resultMap = new HashMap<>();
390 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
391 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
392 if(!musicCache.get(keyspace).equals(nameSpace)) {
393 resultMap.put("Exception", "Namespace and keyspace doesn't match");
396 if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
397 resultMap.put("Exception", "Namespace, userId and password doesn't match");
402 PreparedQueryObject queryObject = new PreparedQueryObject();
403 queryObject.appendQueryString(
404 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
406 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
407 } catch (Exception e) {
412 rs = MusicCore.get(queryObject).one();
413 } catch (MusicServiceException e) {
415 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
419 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
423 String user = rs.getString("username");
424 pwd = rs.getString("password");
425 String ns = rs.getString("application_name");
426 if(!ns.equals(nameSpace)) {
427 resultMap.put("Exception", "Namespace and keyspace doesn't match");
430 if(!user.equals(userId)) {
431 resultMap.put("Exception", "Invalid userId :"+userId);
434 if(!BCrypt.checkpw(password, pwd)) {
435 resultMap.put("Exception", "Invalid password");
439 CachingUtil.updateMusicCache(keyspace, nameSpace);
440 CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
444 public static void deleteKeysFromDB(String deleteKeys) {
445 PreparedQueryObject pQuery = new PreparedQueryObject();
446 pQuery.appendQueryString(
447 "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")");
449 MusicCore.nonKeyRelatedPut(pQuery, "eventual");
450 } catch (Exception e) {