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.onap.music.datastore.PreparedQueryObject;
37 import org.onap.music.datastore.jsonobjects.AAFResponse;
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;
44 import com.att.eelf.configuration.EELFLogger;
45 import com.datastax.driver.core.DataType;
46 import com.datastax.driver.core.ResultSet;
47 import com.datastax.driver.core.Row;
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, String> musicLockCache = JCS.getInstance("musicLockCache");
64 private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
65 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
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 void initializeMusicCache() {
76 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
77 musicCache.put("isInitialized", "true");
80 public void initializeAafCache() throws MusicServiceException {
81 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
83 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
84 PreparedQueryObject pQuery = new PreparedQueryObject();
85 pQuery.appendQueryString(query);
87 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
88 } catch (Exception e1) {
89 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
92 ResultSet rs = MusicCore.get(pQuery);
93 Iterator<Row> it = rs.iterator();
94 Map<String, String> map = null;
95 while (it.hasNext()) {
97 String nameSpace = row.getString("keyspace_name");
98 String userId = row.getString("username");
99 String password = row.getString("password");
100 String keySpace = row.getString("application_name");
101 String uuid = row.getUUID("uuid").toString();
103 userAttempts.put(nameSpace, 0);
104 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
105 if (responseObj.getNs().size() > 0) {
106 map = new HashMap<>();
107 map.put(userId, password);
108 aafCache.put(nameSpace, map);
109 musicCache.put(nameSpace, keySpace);
110 musicLockCache.put(nameSpace, uuid);
111 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
114 } catch (Exception e) {
115 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
116 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
125 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
127 initializeAafCache();
128 } catch (MusicServiceException e) {
129 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
133 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
134 String keySpace) throws Exception {
136 if (aafCache.get(nameSpace) != null) {
137 if (keySpace != null && !musicCache.get(nameSpace).equals(keySpace)) {
138 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
139 } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
140 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
141 // reset invalid attempts to 0
142 userAttempts.put(nameSpace, 0);
145 // call AAF update cache with new password
146 if (userAttempts.get(nameSpace) == null)
147 userAttempts.put(nameSpace, 0);
148 if ((Integer) userAttempts.get(nameSpace) >= 3) {
149 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
150 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
151 Calendar calendar = Calendar.getInstance();
152 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
153 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
154 if( delayTime > 120000) {
155 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
156 userAttempts.put(nameSpace, 0);
158 logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
159 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
162 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
163 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
167 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
168 if (responseObj.getNs().size() > 0) {
169 if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
170 //Map<String, String> map = new HashMap<>();
171 //map.put(userId, password);
172 //aafCache.put(nameSpace, map);
176 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
180 private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
182 if (MusicUtil.getAafEndpointUrl() == null) {
183 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
184 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
186 Client client = Client.create();
187 // WebResource webResource =
188 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
189 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
190 String plainCreds = userId + ":" + password;
191 byte[] plainCredsBytes = plainCreds.getBytes();
192 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
193 String base64Creds = new String(base64CredsBytes);
195 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
196 .header("Authorization", "Basic " + base64Creds)
197 .header("content-type", "application/json").get(ClientResponse.class);
198 if (response.getStatus() != 200) {
199 if (userAttempts.get(nameSpace) == null)
200 userAttempts.put(nameSpace, 0);
201 if ((Integer) userAttempts.get(nameSpace) >= 2) {
202 lastFailedTime.put(nameSpace, Calendar.getInstance());
203 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
205 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
207 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
209 "Unable to authenticate. Please check the AAF credentials against namespace.");
210 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
211 // for specific time.
213 response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
214 Arrays.asList(MediaType.APPLICATION_JSON));
215 // AAFResponse output = response.getEntity(AAFResponse.class);
216 response.bufferEntity();
217 String x = response.getEntity(String.class);
218 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);
223 public static Map<String, Object> authenticateAIDUser(String aid, String keyspace)
225 Map<String, Object> resultMap = new HashMap<>();
228 * if(aid == null || aid.length() == 0) { resultMap.put("Exception Message",
229 * "AID is missing for the keyspace requested."); //create a new AID ?? } else
231 if (musicCache.get(keyspace) == null) {
232 PreparedQueryObject pQuery = new PreparedQueryObject();
233 pQuery.appendQueryString(
234 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
235 + keyspace + "' allow filtering");
236 Row rs = MusicCore.get(pQuery).one();
238 uuid = rs.getUUID("uuid").toString();
239 musicCache.put(keyspace, uuid);
240 } catch (Exception e) {
241 String msg = e.getMessage();
242 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
243 resultMap.put("Exception", "Unauthorized operation. Check AID and Keyspace. "
244 + "Exception from MUSIC is: "
245 + (msg == null ? "Keyspace is new so no AID should be passed in Header."
249 if (!musicCache.get(keyspace).toString().equals(aid)) {
250 resultMap.put("Exception Message",
251 "Unauthorized operation. Invalid AID for the keyspace");
254 } else if (musicCache.get(keyspace) != null
255 && !musicCache.get(keyspace).toString().equals(aid)) {
256 resultMap.put("Exception Message",
257 "Unauthorized operation. Invalid AID for the keyspace");
260 resultMap.put("aid", uuid);
265 public static Map<String, Object> authenticateAIDUserLock(String aid, String nameSpace)
267 Map<String, Object> resultMap = new HashMap<>();
270 if (musicLockCache.get(nameSpace) == null) {
271 PreparedQueryObject pQuery = new PreparedQueryObject();
272 pQuery.appendQueryString(
273 "SELECT uuid from admin.keyspace_master where application_name = '"
274 + nameSpace + "' allow filtering");
275 Row rs = MusicCore.get(pQuery).one();
277 uuid = rs.getUUID("uuid").toString();
278 musicLockCache.put(nameSpace, uuid);
279 } catch (Exception e) {
280 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
281 resultMap.put("Exception", "Unauthorized operation. Check AID and Namespace. ");
284 if (!musicLockCache.get(nameSpace).toString().equals(aid)) {
285 resultMap.put("Exception Message",
286 "Unauthorized operation. Invalid AID for the Namespace");
289 } else if (musicLockCache.get(nameSpace) != null
290 && !musicLockCache.get(nameSpace).toString().equals(aid)) {
291 resultMap.put("Exception Message",
292 "Unauthorized operation. Invalid AID for the Namespace");
301 public static void updateMusicCache(String aid, String keyspace) {
302 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with aid " + aid);
303 musicCache.put(keyspace, aid);
306 public static void updateisAAFCache(String namespace, String isAAF) {
307 appNameCache.put(namespace, isAAF);
310 public static Boolean isAAFApplication(String namespace) throws MusicServiceException {
312 String isAAF = appNameCache.get(namespace);
314 PreparedQueryObject pQuery = new PreparedQueryObject();
315 pQuery.appendQueryString(
316 "SELECT is_aaf from admin.keyspace_master where application_name = '"
317 + namespace + "' allow filtering");
318 Row rs = MusicCore.get(pQuery).one();
320 isAAF = String.valueOf(rs.getBool("is_aaf"));
321 appNameCache.put(namespace, isAAF);
322 } catch (Exception e) {
323 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
328 return Boolean.valueOf(isAAF);
331 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
332 String uuid = musicCache.get(keyspace);
334 PreparedQueryObject pQuery = new PreparedQueryObject();
335 pQuery.appendQueryString(
336 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
337 + keyspace + "' allow filtering");
338 Row rs = MusicCore.get(pQuery).one();
340 uuid = rs.getUUID("uuid").toString();
341 musicCache.put(keyspace, uuid);
342 } catch (Exception e) {
343 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
350 public static String getAppName(String keyspace) throws MusicServiceException {
351 String appName = null;
352 PreparedQueryObject pQuery = new PreparedQueryObject();
353 pQuery.appendQueryString(
354 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
355 + keyspace + "' allow filtering");
356 Row rs = MusicCore.get(pQuery).one();
358 appName = rs.getString("application_name");
359 } catch (Exception e) {
360 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
366 public static String generateUUID() {
367 String uuid = UUID.randomUUID().toString();
368 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
372 public static Map<String, Object> validateRequest(String nameSpace, String userId,
373 String password, String keyspace, String aid, String operation) {
374 Map<String, Object> resultMap = new HashMap<>();
375 if (!"createKeySpace".equals(operation)) {
376 if (nameSpace == null) {
377 resultMap.put("Exception", "Application namespace is mandatory.");
384 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
385 Map<String, Object> resultMap = new HashMap<>();
386 if (ns == null || userId == null || password == null) {
387 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
388 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
389 resultMap.put("Exception",
390 "One or more required headers appName(ns), userId, password is missing. Please check.");
393 PreparedQueryObject queryObject = new PreparedQueryObject();
394 queryObject.appendQueryString(
395 "select * from admin.keyspace_master where application_name = ? allow filtering");
397 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
398 } catch(Exception e) {
399 resultMap.put("Exception",
400 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
405 rs = MusicCore.get(queryObject).one();
406 } catch (MusicServiceException e) {
407 // TODO Auto-generated catch block
409 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
413 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
414 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
416 if(!(rs.getString("username").equals(userId)) && !(rs.getString("password").equals("password"))) {
417 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
418 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
419 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
422 boolean is_aaf = rs.getBool("is_aaf");
423 String keyspace = rs.getString("keyspace_name");
425 if (!keyspace.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
426 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.DATAERROR);
427 logger.error(EELFLoggerDelegate.errorLogger,"Non AAF applications are allowed to have only one keyspace per application.");
428 resultMap.put("Exception",
429 "Non AAF applications are allowed to have only one keyspace per application.");