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.Arrays;
25 import java.util.Calendar;
26 import java.util.HashMap;
27 import java.util.Iterator;
29 import java.util.UUID;
30 import javax.ws.rs.core.HttpHeaders;
31 import javax.ws.rs.core.MediaType;
32 import org.apache.commons.codec.binary.Base64;
33 import org.apache.commons.jcs.JCS;
34 import org.apache.commons.jcs.access.CacheAccess;
35 import org.codehaus.jackson.map.ObjectMapper;
36 import org.mindrot.jbcrypt.BCrypt;
37 import org.onap.music.datastore.PreparedQueryObject;
38 import org.onap.music.datastore.jsonobjects.AAFResponse;
39 import org.onap.music.eelf.logging.EELFLoggerDelegate;
40 import org.onap.music.eelf.logging.format.AppMessages;
41 import org.onap.music.eelf.logging.format.ErrorSeverity;
42 import org.onap.music.eelf.logging.format.ErrorTypes;
43 import org.onap.music.exceptions.MusicServiceException;
44 import org.onap.music.datastore.jsonobjects.JsonNotification;
45 import org.onap.music.datastore.jsonobjects.JsonCallback;
46 import com.att.eelf.configuration.EELFLogger;
47 import com.datastax.driver.core.DataType;
48 import com.datastax.driver.core.ResultSet;
49 import com.datastax.driver.core.Row;
50 import com.datastax.driver.core.exceptions.InvalidQueryException;
51 import com.sun.jersey.api.client.Client;
52 import com.sun.jersey.api.client.ClientResponse;
53 import com.sun.jersey.api.client.WebResource;
56 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
61 public class CachingUtil implements Runnable {
63 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
65 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
66 private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
67 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
68 private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
69 private static CacheAccess<String, JsonCallback> callBackCache = JCS.getInstance("callBackCache");
70 private static Map<String, Number> userAttempts = new HashMap<>();
71 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
73 public boolean isCacheRefreshNeeded() {
74 if (aafCache.get("initBlankMap") == null)
79 public static void updateCallBackCache(String appName, JsonCallback jsonCallBack) {
80 callBackCache.put(appName, jsonCallBack);
83 public static JsonCallback getCallBackCache(String appName) {
84 return callBackCache.get(appName);
87 public void initializeMusicCache() {
88 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
89 musicCache.put("isInitialized", "true");
92 public void initializeAafCache() throws MusicServiceException {
93 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
95 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
96 PreparedQueryObject pQuery = new PreparedQueryObject();
97 pQuery.appendQueryString(query);
99 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
100 } catch (Exception e1) {
101 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
102 e1.printStackTrace();
104 ResultSet rs = MusicCore.get(pQuery);
105 Iterator<Row> it = rs.iterator();
106 Map<String, String> map = null;
107 while (it.hasNext()) {
109 String nameSpace = row.getString("keyspace_name");
110 String userId = row.getString("username");
111 String password = row.getString("password");
112 String keySpace = row.getString("application_name");
114 userAttempts.put(nameSpace, 0);
115 boolean responseObj = triggerAAF(nameSpace, userId, password);
117 map = new HashMap<>();
118 map.put(userId, password);
119 aafCache.put(nameSpace, map);
120 musicCache.put(keySpace, nameSpace);
121 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
124 } catch (Exception e) {
125 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
126 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
135 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
137 initializeAafCache();
138 } catch (MusicServiceException e) {
139 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
143 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
144 String keySpace) throws Exception {
146 if (aafCache.get(nameSpace) != 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 (aafCache.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 = triggerAAF(nameSpace, userId, password);
179 //if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
180 //Map<String, String> map = new HashMap<>();
181 //map.put(userId, password);
182 //aafCache.put(nameSpace, map);
186 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
190 private static boolean triggerAAF(String nameSpace, String userId, String password)
192 if (MusicUtil.getAafEndpointUrl() == null) {
193 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
194 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
196 Client client = Client.create();
197 // WebResource webResource =
198 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
199 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
200 String plainCreds = userId + ":" + password;
201 byte[] plainCredsBytes = plainCreds.getBytes();
202 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
203 String base64Creds = new String(base64CredsBytes);
205 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
206 .header("Authorization", "Basic " + base64Creds)
207 .header("content-type", "application/json").get(ClientResponse.class);
208 if (response.getStatus() != 200) {
209 if (userAttempts.get(nameSpace) == null)
210 userAttempts.put(nameSpace, 0);
211 if ((Integer) userAttempts.get(nameSpace) >= 2) {
212 lastFailedTime.put(nameSpace, Calendar.getInstance());
213 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
215 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
217 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
219 "Unable to authenticate. Please check the AAF credentials against namespace.");
220 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
221 // for specific time.
223 /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
224 Arrays.asList(MediaType.APPLICATION_JSON));
225 // AAFResponse output = response.getEntity(AAFResponse.class);
226 response.bufferEntity();
227 String x = response.getEntity(String.class);
228 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
233 public static void updateMusicCache(String keyspace, String nameSpace) {
234 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
235 musicCache.put(keyspace, nameSpace);
238 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
239 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
240 Map<String, String> map = new HashMap<>();
241 map.put(userId, password);
242 musicValidateCache.put(nameSpace, map);
245 public static void updateisAAFCache(String namespace, String isAAF) {
246 appNameCache.put(namespace, isAAF);
249 public static String isAAFApplication(String namespace) throws MusicServiceException {
250 String isAAF = appNameCache.get(namespace);
252 PreparedQueryObject pQuery = new PreparedQueryObject();
253 pQuery.appendQueryString(
254 "SELECT is_aaf from admin.keyspace_master where application_name = '"
255 + namespace + "' allow filtering");
258 rs = MusicCore.get(pQuery).one();
259 } catch(InvalidQueryException e) {
260 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
261 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
264 isAAF = String.valueOf(rs.getBool("is_aaf"));
266 appNameCache.put(namespace, isAAF);
267 } catch (Exception e) {
268 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
275 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
278 PreparedQueryObject pQuery = new PreparedQueryObject();
279 pQuery.appendQueryString(
280 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
281 + keyspace + "' allow filtering");
282 Row rs = MusicCore.get(pQuery).one();
284 uuid = rs.getUUID("uuid").toString();
285 } catch (Exception e) {
286 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
293 public static String getAppName(String keyspace) throws MusicServiceException {
294 String appName = null;
295 PreparedQueryObject pQuery = new PreparedQueryObject();
296 pQuery.appendQueryString(
297 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
298 + keyspace + "' allow filtering");
299 Row rs = MusicCore.get(pQuery).one();
301 appName = rs.getString("application_name");
302 } catch (Exception e) {
303 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
309 public static String generateUUID() {
310 String uuid = UUID.randomUUID().toString();
311 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
315 public static Map<String, Object> validateRequest(String nameSpace, String userId,
316 String password, String keyspace, String aid, String operation) {
317 Map<String, Object> resultMap = new HashMap<>();
318 if (!"createKeySpace".equals(operation)) {
319 if (nameSpace == null) {
320 resultMap.put("Exception", "Application namespace is mandatory.");
327 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
328 Map<String, Object> resultMap = new HashMap<>();
329 if (ns == null || userId == null || password == null) {
330 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
331 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
332 resultMap.put("Exception",
333 "One or more required headers appName(ns), userId, password is missing. Please check.");
336 PreparedQueryObject queryObject = new PreparedQueryObject();
337 queryObject.appendQueryString(
338 "select * from admin.keyspace_master where application_name = ? allow filtering");
340 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
341 } catch(Exception e) {
342 resultMap.put("Exception",
343 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
348 rs = MusicCore.get(queryObject).one();
349 } catch (MusicServiceException e) {
350 // TODO Auto-generated catch block
352 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
354 } catch (InvalidQueryException e) {
355 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
356 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
360 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
361 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
363 if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
364 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
365 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
366 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
373 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
375 Map<String, Object> resultMap = new HashMap<>();
377 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
378 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
379 if(!musicCache.get(keyspace).equals(nameSpace)) {
380 resultMap.put("Exception", "Namespace and keyspace doesn't match");
383 if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
384 resultMap.put("Exception", "Namespace, userId and password doesn't match");
389 PreparedQueryObject queryObject = new PreparedQueryObject();
390 queryObject.appendQueryString(
391 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
393 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
394 } catch (Exception e) {
399 rs = MusicCore.get(queryObject).one();
400 } 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) {