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.Calendar;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
29 import java.util.UUID;
30 import javax.ws.rs.core.MediaType;
31 import org.apache.commons.codec.binary.Base64;
32 import org.apache.commons.jcs.JCS;
33 import org.apache.commons.jcs.access.CacheAccess;
34 import org.mindrot.jbcrypt.BCrypt;
35 import org.onap.music.datastore.PreparedQueryObject;
36 import org.onap.music.eelf.logging.EELFLoggerDelegate;
37 import org.onap.music.eelf.logging.format.AppMessages;
38 import org.onap.music.eelf.logging.format.ErrorSeverity;
39 import org.onap.music.eelf.logging.format.ErrorTypes;
40 import org.onap.music.exceptions.MusicServiceException;
41 import org.onap.music.datastore.jsonobjects.JsonCallback;
42 import com.datastax.driver.core.DataType;
43 import com.datastax.driver.core.ResultSet;
44 import com.datastax.driver.core.Row;
45 import com.datastax.driver.core.exceptions.InvalidQueryException;
46 import com.sun.jersey.api.client.Client;
47 import com.sun.jersey.api.client.ClientResponse;
48 import com.sun.jersey.api.client.WebResource;
51 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
56 public class CachingUtil implements Runnable {
58 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
60 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
61 private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
62 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
63 private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
64 private static CacheAccess<String, JsonCallback> callBackCache = JCS.getInstance("callBackCache");
65 private static CacheAccess<String, List<String>> callbackNotifyList = JCS.getInstance("callbackNotifyList");
66 private static Map<String, Number> userAttempts = new HashMap<>();
67 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
69 public boolean isCacheRefreshNeeded() {
70 if (aafCache.get("initBlankMap") == null)
75 public static void updateCallBackCache(String appName, JsonCallback jsonCallBack) {
76 logger.info("updateCallBackCache: updating cache.....");
77 callBackCache.put(appName, jsonCallBack);
80 public static JsonCallback getCallBackCache(String appName) {
81 return callBackCache.get(appName);
84 public static void updateCallbackNotifyList(List<String> notifyList) {
85 logger.info("callbackNotifyList: updating cache.....");
86 callbackNotifyList.put("callbackNotify", notifyList);
89 public static List<String> getCallbackNotifyList() {
90 return callbackNotifyList.get("callbackNotify");
93 public void initializeMusicCache() {
94 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
95 musicCache.put("isInitialized", "true");
98 public void initializeAafCache() throws MusicServiceException {
99 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
101 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
102 PreparedQueryObject pQuery = new PreparedQueryObject();
103 pQuery.appendQueryString(query);
105 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
106 } catch (Exception e1) {
107 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
109 ResultSet rs = MusicCore.get(pQuery);
110 Iterator<Row> it = rs.iterator();
111 Map<String, String> map = null;
112 while (it.hasNext()) {
114 String nameSpace = row.getString("keyspace_name");
115 String userId = row.getString("username");
116 String password = row.getString("password");
117 String keySpace = row.getString("application_name");
119 userAttempts.put(nameSpace, 0);
120 boolean responseObj = triggerAAF(nameSpace, userId, password);
122 map = new HashMap<>();
123 map.put(userId, password);
124 aafCache.put(nameSpace, map);
125 musicCache.put(keySpace, nameSpace);
126 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
129 } catch (Exception e) {
130 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
131 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
139 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
141 initializeAafCache();
142 } catch (MusicServiceException e) {
143 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
147 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
148 String keySpace) throws Exception {
150 if (aafCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) {
151 if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
152 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
153 } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
154 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
155 // reset invalid attempts to 0
156 userAttempts.put(nameSpace, 0);
159 // call AAF update cache with new password
160 if (userAttempts.get(nameSpace) == null)
161 userAttempts.put(nameSpace, 0);
162 if ((Integer) userAttempts.get(nameSpace) >= 3) {
163 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
164 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
165 Calendar calendar = Calendar.getInstance();
166 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
167 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
168 if( delayTime > 120000) {
169 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
170 userAttempts.put(nameSpace, 0);
172 logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
173 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
176 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
177 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
181 boolean responseObj = triggerAAF(nameSpace, userId, password);
183 //if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
184 Map<String, String> map = new HashMap<>();
185 map.put(userId, password);
186 aafCache.put(nameSpace, map);
187 CachingUtil.updateMusicCache(keySpace, nameSpace);
191 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
195 private static boolean triggerAAF(String nameSpace, String userId, String password)
197 if (MusicUtil.getAafEndpointUrl() == null) {
198 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
199 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
201 Client client = Client.create();
202 // WebResource webResource =
203 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
204 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
205 String plainCreds = userId + ":" + password;
206 byte[] plainCredsBytes = plainCreds.getBytes();
207 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
208 String base64Creds = new String(base64CredsBytes);
210 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
211 .header("Authorization", "Basic " + base64Creds)
212 .header("content-type", "application/json").get(ClientResponse.class);
213 if (response.getStatus() != 200) {
214 if (userAttempts.get(nameSpace) == null)
215 userAttempts.put(nameSpace, 0);
216 if ((Integer) userAttempts.get(nameSpace) >= 2) {
217 lastFailedTime.put(nameSpace, Calendar.getInstance());
218 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
220 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
222 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
224 "Unable to authenticate. Please check the AAF credentials against namespace.");
225 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
226 // for specific time.
228 /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
229 Arrays.asList(MediaType.APPLICATION_JSON));
230 // AAFResponse output = response.getEntity(AAFResponse.class);
231 response.bufferEntity();
232 String x = response.getEntity(String.class);
233 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
238 public static void updateMusicCache(String keyspace, String nameSpace) {
239 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
240 musicCache.put(keyspace, nameSpace);
243 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
244 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
245 Map<String, String> map = new HashMap<>();
246 map.put(userId, password);
247 musicValidateCache.put(nameSpace, map);
250 public static void updateisAAFCache(String namespace, String isAAF) {
251 appNameCache.put(namespace, isAAF);
254 public static String isAAFApplication(String namespace) throws MusicServiceException {
255 String isAAF = appNameCache.get(namespace);
257 PreparedQueryObject pQuery = new PreparedQueryObject();
258 pQuery.appendQueryString(
259 "SELECT is_aaf from admin.keyspace_master where application_name = '"
260 + namespace + "' allow filtering");
263 rs = MusicCore.get(pQuery).one();
264 } catch(InvalidQueryException e) {
265 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
266 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
269 isAAF = String.valueOf(rs.getBool("is_aaf"));
271 appNameCache.put(namespace, isAAF);
272 } catch (Exception e) {
273 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
279 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
282 PreparedQueryObject pQuery = new PreparedQueryObject();
283 pQuery.appendQueryString(
284 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
285 + keyspace + "' allow filtering");
286 Row rs = MusicCore.get(pQuery).one();
288 uuid = rs.getUUID("uuid").toString();
289 } catch (Exception e) {
290 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
296 public static String getAppName(String keyspace) throws MusicServiceException {
297 String appName = null;
298 PreparedQueryObject pQuery = new PreparedQueryObject();
299 pQuery.appendQueryString(
300 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
301 + keyspace + "' allow filtering");
302 Row rs = MusicCore.get(pQuery).one();
304 appName = rs.getString("application_name");
305 } catch (Exception e) {
306 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
311 public static String generateUUID() {
312 String uuid = UUID.randomUUID().toString();
313 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
317 public static Map<String, Object> validateRequest(String nameSpace, String userId,
318 String password, String keyspace, String aid, String operation) {
319 Map<String, Object> resultMap = new HashMap<>();
320 if (!"createKeySpace".equals(operation)) {
321 if (nameSpace == null) {
322 resultMap.put("Exception", "Application namespace is mandatory.");
329 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
330 Map<String, Object> resultMap = new HashMap<>();
331 if (ns == null || userId == null || password == null) {
332 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
333 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
334 resultMap.put("Exception",
335 "One or more required headers appName(ns), userId, password is missing. Please check.");
338 PreparedQueryObject queryObject = new PreparedQueryObject();
339 queryObject.appendQueryString(
340 "select * from admin.keyspace_master where application_name = ? allow filtering");
342 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
343 } catch(Exception e) {
344 resultMap.put("Exception",
345 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
350 rs = MusicCore.get(queryObject).one();
351 } catch (MusicServiceException e) {
352 // TODO Auto-generated catch block
353 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
355 } catch (InvalidQueryException e) {
356 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
357 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
361 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
362 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
364 if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
365 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
366 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
367 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
374 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
376 Map<String, Object> resultMap = new HashMap<>();
378 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
379 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
380 if(!musicCache.get(keyspace).equals(nameSpace)) {
381 resultMap.put("Exception", "Namespace and keyspace doesn't match");
384 if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
385 resultMap.put("Exception", "Namespace, userId and password doesn't match");
390 PreparedQueryObject queryObject = new PreparedQueryObject();
391 queryObject.appendQueryString(
392 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
394 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
395 } catch (Exception e) {
396 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
400 rs = MusicCore.get(queryObject).one();
401 } catch (MusicServiceException e) {
402 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
406 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
410 String user = rs.getString("username");
411 pwd = rs.getString("password");
412 String ns = rs.getString("application_name");
413 if(!ns.equals(nameSpace)) {
414 resultMap.put("Exception", "Namespace and keyspace doesn't match");
417 if(!user.equals(userId)) {
418 resultMap.put("Exception", "Invalid userId :"+userId);
421 if(!BCrypt.checkpw(password, pwd)) {
422 resultMap.put("Exception", "Invalid password");
426 CachingUtil.updateMusicCache(keyspace, nameSpace);
427 CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
431 public static void deleteKeysFromDB(String deleteKeys) {
432 PreparedQueryObject pQuery = new PreparedQueryObject();
433 pQuery.appendQueryString(
434 "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")");
436 MusicCore.nonKeyRelatedPut(pQuery, "eventual");
437 } catch (Exception e) {
438 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, "Error in deleteKeysFromDB");