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.datastax.driver.core.exceptions.InvalidQueryException;
49 import com.sun.jersey.api.client.Client;
50 import com.sun.jersey.api.client.ClientResponse;
51 import com.sun.jersey.api.client.WebResource;
54 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
59 public class CachingUtil implements Runnable {
61 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
63 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
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 CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
67 private static Map<String, Number> userAttempts = new HashMap<>();
68 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
70 public boolean isCacheRefreshNeeded() {
71 if (aafCache.get("initBlankMap") == null)
76 public void initializeMusicCache() {
77 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
78 musicCache.put("isInitialized", "true");
81 public void initializeAafCache() throws MusicServiceException {
82 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
84 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
85 PreparedQueryObject pQuery = new PreparedQueryObject();
86 pQuery.appendQueryString(query);
88 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
89 } catch (Exception e1) {
90 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
93 ResultSet rs = MusicCore.get(pQuery);
94 Iterator<Row> it = rs.iterator();
95 Map<String, String> map = null;
96 while (it.hasNext()) {
98 String nameSpace = row.getString("keyspace_name");
99 String userId = row.getString("username");
100 String password = row.getString("password");
101 String keySpace = row.getString("application_name");
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(keySpace, nameSpace);
110 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
113 } catch (Exception e) {
114 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
115 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
124 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
126 initializeAafCache();
127 } catch (MusicServiceException e) {
128 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
132 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
133 String keySpace) throws Exception {
135 if (aafCache.get(nameSpace) != null) {
136 if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
137 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
138 } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
139 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
140 // reset invalid attempts to 0
141 userAttempts.put(nameSpace, 0);
144 // call AAF update cache with new password
145 if (userAttempts.get(nameSpace) == null)
146 userAttempts.put(nameSpace, 0);
147 if ((Integer) userAttempts.get(nameSpace) >= 3) {
148 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
149 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
150 Calendar calendar = Calendar.getInstance();
151 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
152 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
153 if( delayTime > 120000) {
154 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
155 userAttempts.put(nameSpace, 0);
157 logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
158 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
161 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
162 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
166 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
167 if (responseObj.getNs().size() > 0) {
168 if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
169 //Map<String, String> map = new HashMap<>();
170 //map.put(userId, password);
171 //aafCache.put(nameSpace, map);
175 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
179 private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
181 if (MusicUtil.getAafEndpointUrl() == null) {
182 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
183 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
185 Client client = Client.create();
186 // WebResource webResource =
187 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
188 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
189 String plainCreds = userId + ":" + password;
190 byte[] plainCredsBytes = plainCreds.getBytes();
191 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
192 String base64Creds = new String(base64CredsBytes);
194 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
195 .header("Authorization", "Basic " + base64Creds)
196 .header("content-type", "application/json").get(ClientResponse.class);
197 if (response.getStatus() != 200) {
198 if (userAttempts.get(nameSpace) == null)
199 userAttempts.put(nameSpace, 0);
200 if ((Integer) userAttempts.get(nameSpace) >= 2) {
201 lastFailedTime.put(nameSpace, Calendar.getInstance());
202 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
204 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
206 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
208 "Unable to authenticate. Please check the AAF credentials against namespace.");
209 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
210 // for specific time.
212 response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
213 Arrays.asList(MediaType.APPLICATION_JSON));
214 // AAFResponse output = response.getEntity(AAFResponse.class);
215 response.bufferEntity();
216 String x = response.getEntity(String.class);
217 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);
222 public static void updateMusicCache(String keyspace, String nameSpace) {
223 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
224 musicCache.put(keyspace, nameSpace);
227 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
228 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
229 Map<String, String> map = new HashMap<>();
230 map.put(userId, password);
231 musicValidateCache.put(nameSpace, map);
234 public static void updateisAAFCache(String namespace, String isAAF) {
235 appNameCache.put(namespace, isAAF);
238 public static String isAAFApplication(String namespace) throws MusicServiceException {
239 String isAAF = appNameCache.get(namespace);
241 PreparedQueryObject pQuery = new PreparedQueryObject();
242 pQuery.appendQueryString(
243 "SELECT is_aaf from admin.keyspace_master where application_name = '"
244 + namespace + "' allow filtering");
247 rs = MusicCore.get(pQuery).one();
248 } catch(InvalidQueryException e) {
249 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
250 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
253 isAAF = String.valueOf(rs.getBool("is_aaf"));
255 appNameCache.put(namespace, isAAF);
256 } catch (Exception e) {
257 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
264 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
267 PreparedQueryObject pQuery = new PreparedQueryObject();
268 pQuery.appendQueryString(
269 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
270 + keyspace + "' allow filtering");
271 Row rs = MusicCore.get(pQuery).one();
273 uuid = rs.getUUID("uuid").toString();
274 } catch (Exception e) {
275 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
282 public static String getAppName(String keyspace) throws MusicServiceException {
283 String appName = null;
284 PreparedQueryObject pQuery = new PreparedQueryObject();
285 pQuery.appendQueryString(
286 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
287 + keyspace + "' allow filtering");
288 Row rs = MusicCore.get(pQuery).one();
290 appName = rs.getString("application_name");
291 } catch (Exception e) {
292 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
298 public static String generateUUID() {
299 String uuid = UUID.randomUUID().toString();
300 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
304 public static Map<String, Object> validateRequest(String nameSpace, String userId,
305 String password, String keyspace, String aid, String operation) {
306 Map<String, Object> resultMap = new HashMap<>();
307 if (!"createKeySpace".equals(operation)) {
308 if (nameSpace == null) {
309 resultMap.put("Exception", "Application namespace is mandatory.");
316 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
317 Map<String, Object> resultMap = new HashMap<>();
318 if (ns == null || userId == null || password == null) {
319 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
320 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
321 resultMap.put("Exception",
322 "One or more required headers appName(ns), userId, password is missing. Please check.");
325 PreparedQueryObject queryObject = new PreparedQueryObject();
326 queryObject.appendQueryString(
327 "select * from admin.keyspace_master where application_name = ? allow filtering");
329 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
330 } catch(Exception e) {
331 resultMap.put("Exception",
332 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
337 rs = MusicCore.get(queryObject).one();
338 } catch (MusicServiceException e) {
339 // TODO Auto-generated catch block
341 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
343 } catch (InvalidQueryException e) {
344 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
345 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
349 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
350 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
352 if(!(rs.getString("username").equals(userId)) || !(rs.getString("password").equals(password))) {
353 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
354 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
355 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
362 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
364 Map<String, Object> resultMap = new HashMap<>();
365 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
366 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
367 if(!musicCache.get(keyspace).equals(nameSpace)) {
368 resultMap.put("Exception", "Namespace and keyspace doesn't match");
371 if(!musicValidateCache.get(nameSpace).get(userId).equals(password)) {
372 resultMap.put("Exception", "Namespace, userId and password doesn't match");
377 PreparedQueryObject queryObject = new PreparedQueryObject();
378 queryObject.appendQueryString(
379 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
381 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
382 } catch (Exception e) {
387 rs = MusicCore.get(queryObject).one();
388 } catch (MusicServiceException e) {
390 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
394 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
398 String user = rs.getString("username");
399 String pwd = rs.getString("password");
400 String ns = rs.getString("application_name");
401 if(!ns.equals(nameSpace)) {
402 resultMap.put("Exception", "Namespace and keyspace doesn't match");
405 if(!user.equals(userId)) {
406 resultMap.put("Exception", "Invalid userId :"+userId);
409 if(!pwd.equals(password)) {
410 resultMap.put("Exception", "Invalid password");
414 CachingUtil.updateMusicCache(keyspace, nameSpace);
415 CachingUtil.updateMusicValidateCache(nameSpace, userId, password);