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;
45 import com.att.eelf.configuration.EELFLogger;
46 import com.datastax.driver.core.DataType;
47 import com.datastax.driver.core.ResultSet;
48 import com.datastax.driver.core.Row;
49 import com.datastax.driver.core.exceptions.InvalidQueryException;
50 import com.sun.jersey.api.client.Client;
51 import com.sun.jersey.api.client.ClientResponse;
52 import com.sun.jersey.api.client.WebResource;
55 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
60 public class CachingUtil implements Runnable {
62 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
64 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
65 private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
66 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
67 private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
68 private static Map<String, Number> userAttempts = new HashMap<>();
69 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
71 public boolean isCacheRefreshNeeded() {
72 if (aafCache.get("initBlankMap") == null)
77 public void initializeMusicCache() {
78 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
79 musicCache.put("isInitialized", "true");
82 public void initializeAafCache() throws MusicServiceException {
83 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
85 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
86 PreparedQueryObject pQuery = new PreparedQueryObject();
87 pQuery.appendQueryString(query);
89 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
90 } catch (Exception e1) {
91 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
94 ResultSet rs = MusicCore.get(pQuery);
95 Iterator<Row> it = rs.iterator();
96 Map<String, String> map = null;
97 while (it.hasNext()) {
99 String nameSpace = row.getString("keyspace_name");
100 String userId = row.getString("username");
101 String password = row.getString("password");
102 String keySpace = row.getString("application_name");
104 userAttempts.put(nameSpace, 0);
105 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
106 if (responseObj.getNs().size() > 0) {
107 map = new HashMap<>();
108 map.put(userId, password);
109 aafCache.put(nameSpace, map);
110 musicCache.put(keySpace, nameSpace);
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(keySpace).equals(nameSpace)) {
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 void updateMusicCache(String keyspace, String nameSpace) {
224 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
225 musicCache.put(keyspace, nameSpace);
228 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
229 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
230 Map<String, String> map = new HashMap<>();
231 map.put(userId, password);
232 musicValidateCache.put(nameSpace, map);
235 public static void updateisAAFCache(String namespace, String isAAF) {
236 appNameCache.put(namespace, isAAF);
239 public static String isAAFApplication(String namespace) throws MusicServiceException {
240 String isAAF = appNameCache.get(namespace);
242 PreparedQueryObject pQuery = new PreparedQueryObject();
243 pQuery.appendQueryString(
244 "SELECT is_aaf from admin.keyspace_master where application_name = '"
245 + namespace + "' allow filtering");
248 rs = MusicCore.get(pQuery).one();
249 } catch(InvalidQueryException e) {
250 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
251 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
254 isAAF = String.valueOf(rs.getBool("is_aaf"));
256 appNameCache.put(namespace, isAAF);
257 } catch (Exception e) {
258 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
265 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
268 PreparedQueryObject pQuery = new PreparedQueryObject();
269 pQuery.appendQueryString(
270 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
271 + keyspace + "' allow filtering");
272 Row rs = MusicCore.get(pQuery).one();
274 uuid = rs.getUUID("uuid").toString();
275 } catch (Exception e) {
276 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
283 public static String getAppName(String keyspace) throws MusicServiceException {
284 String appName = null;
285 PreparedQueryObject pQuery = new PreparedQueryObject();
286 pQuery.appendQueryString(
287 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
288 + keyspace + "' allow filtering");
289 Row rs = MusicCore.get(pQuery).one();
291 appName = rs.getString("application_name");
292 } catch (Exception e) {
293 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
299 public static String generateUUID() {
300 String uuid = UUID.randomUUID().toString();
301 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
305 public static Map<String, Object> validateRequest(String nameSpace, String userId,
306 String password, String keyspace, String aid, String operation) {
307 Map<String, Object> resultMap = new HashMap<>();
308 if (!"createKeySpace".equals(operation)) {
309 if (nameSpace == null) {
310 resultMap.put("Exception", "Application namespace is mandatory.");
317 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
318 Map<String, Object> resultMap = new HashMap<>();
319 if (ns == null || userId == null || password == null) {
320 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
321 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
322 resultMap.put("Exception",
323 "One or more required headers appName(ns), userId, password is missing. Please check.");
326 PreparedQueryObject queryObject = new PreparedQueryObject();
327 queryObject.appendQueryString(
328 "select * from admin.keyspace_master where application_name = ? allow filtering");
330 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
331 } catch(Exception e) {
332 resultMap.put("Exception",
333 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
338 rs = MusicCore.get(queryObject).one();
339 } catch (MusicServiceException e) {
340 // TODO Auto-generated catch block
342 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
344 } catch (InvalidQueryException e) {
345 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
346 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
350 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
351 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
353 if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
354 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
355 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
356 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
363 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
365 Map<String, Object> resultMap = new HashMap<>();
367 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
368 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
369 if(!musicCache.get(keyspace).equals(nameSpace)) {
370 resultMap.put("Exception", "Namespace and keyspace doesn't match");
373 if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
374 resultMap.put("Exception", "Namespace, userId and password doesn't match");
379 PreparedQueryObject queryObject = new PreparedQueryObject();
380 queryObject.appendQueryString(
381 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
383 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
384 } catch (Exception e) {
389 rs = MusicCore.get(queryObject).one();
390 } catch (MusicServiceException e) {
392 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
396 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
400 String user = rs.getString("username");
401 pwd = rs.getString("password");
402 String ns = rs.getString("application_name");
403 if(!ns.equals(nameSpace)) {
404 resultMap.put("Exception", "Namespace and keyspace doesn't match");
407 if(!user.equals(userId)) {
408 resultMap.put("Exception", "Invalid userId :"+userId);
411 if(!BCrypt.checkpw(password, pwd)) {
412 resultMap.put("Exception", "Invalid password");
416 CachingUtil.updateMusicCache(keyspace, nameSpace);
417 CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);