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 boolean aafRresponse = triggerAAF(nameSpace, userId, password);
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 boolean aafRresponse = triggerAAF(nameSpace, userId, password);
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 boolean 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)
200 else if (response.getStatus() != 200) {
201 if (userAttempts.get(nameSpace) == null)
202 userAttempts.put(nameSpace, 0);
203 if ((Integer) userAttempts.get(nameSpace) >= 2) {
204 lastFailedTime.put(nameSpace, Calendar.getInstance());
205 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
207 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
209 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
211 "Unable to authenticate. Please check the AAF credentials against namespace.");
212 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
213 // for specific time.
215 /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
216 Arrays.asList(MediaType.APPLICATION_JSON));
217 // AAFResponse output = response.getEntity(AAFResponse.class);
218 response.bufferEntity();
219 String x = response.getEntity(String.class);
220 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
225 public static void updateMusicCache(String keyspace, String nameSpace) {
226 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
227 musicCache.put(keyspace, nameSpace);
230 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
231 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
232 Map<String, String> map = new HashMap<>();
233 map.put(userId, password);
234 musicValidateCache.put(nameSpace, map);
237 public static void updateisAAFCache(String namespace, String isAAF) {
238 appNameCache.put(namespace, isAAF);
241 public static String isAAFApplication(String namespace) throws MusicServiceException {
242 String isAAF = appNameCache.get(namespace);
244 PreparedQueryObject pQuery = new PreparedQueryObject();
245 pQuery.appendQueryString(
246 "SELECT is_aaf from admin.keyspace_master where application_name = '"
247 + namespace + "' allow filtering");
250 rs = MusicCore.get(pQuery).one();
251 } catch(InvalidQueryException e) {
252 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
253 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
256 isAAF = String.valueOf(rs.getBool("is_aaf"));
258 appNameCache.put(namespace, isAAF);
259 } catch (Exception e) {
260 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
267 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
270 PreparedQueryObject pQuery = new PreparedQueryObject();
271 pQuery.appendQueryString(
272 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
273 + keyspace + "' allow filtering");
274 Row rs = MusicCore.get(pQuery).one();
276 uuid = rs.getUUID("uuid").toString();
277 } catch (Exception e) {
278 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
285 public static String getAppName(String keyspace) throws MusicServiceException {
286 String appName = null;
287 PreparedQueryObject pQuery = new PreparedQueryObject();
288 pQuery.appendQueryString(
289 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
290 + keyspace + "' allow filtering");
291 Row rs = MusicCore.get(pQuery).one();
293 appName = rs.getString("application_name");
294 } catch (Exception e) {
295 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
301 public static String generateUUID() {
302 String uuid = UUID.randomUUID().toString();
303 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
307 public static Map<String, Object> validateRequest(String nameSpace, String userId,
308 String password, String keyspace, String aid, String operation) {
309 Map<String, Object> resultMap = new HashMap<>();
310 if (!"createKeySpace".equals(operation)) {
311 if (nameSpace == null) {
312 resultMap.put("Exception", "Application namespace is mandatory.");
319 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
320 Map<String, Object> resultMap = new HashMap<>();
321 if (ns == null || userId == null || password == null) {
322 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
323 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
324 resultMap.put("Exception",
325 "One or more required headers appName(ns), userId, password is missing. Please check.");
328 PreparedQueryObject queryObject = new PreparedQueryObject();
329 queryObject.appendQueryString(
330 "select * from admin.keyspace_master where application_name = ? allow filtering");
332 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
333 } catch(Exception e) {
334 resultMap.put("Exception",
335 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
340 rs = MusicCore.get(queryObject).one();
341 } catch (MusicServiceException e) {
342 // TODO Auto-generated catch block
344 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
346 } catch (InvalidQueryException e) {
347 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
348 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
352 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
353 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
355 if(!(rs.getString("username").equals(userId)) || !(rs.getString("password").equals(password))) {
356 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
357 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
358 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
365 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
367 Map<String, Object> resultMap = new HashMap<>();
368 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
369 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
370 if(!musicCache.get(keyspace).equals(nameSpace)) {
371 resultMap.put("Exception", "Namespace and keyspace doesn't match");
374 if(!musicValidateCache.get(nameSpace).get(userId).equals(password)) {
375 resultMap.put("Exception", "Namespace, userId and password doesn't match");
380 PreparedQueryObject queryObject = new PreparedQueryObject();
381 queryObject.appendQueryString(
382 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
384 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
385 } catch (Exception e) {
390 rs = MusicCore.get(queryObject).one();
391 } catch (MusicServiceException e) {
393 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
397 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
401 String user = rs.getString("username");
402 String pwd = rs.getString("password");
403 String ns = rs.getString("application_name");
404 if(!ns.equals(nameSpace)) {
405 resultMap.put("Exception", "Namespace and keyspace doesn't match");
408 if(!user.equals(userId)) {
409 resultMap.put("Exception", "Invalid userId :"+userId);
412 if(!pwd.equals(password)) {
413 resultMap.put("Exception", "Invalid password");
417 CachingUtil.updateMusicCache(keyspace, nameSpace);
418 CachingUtil.updateMusicValidateCache(nameSpace, userId, password);