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 * ====================================================================
23 package org.onap.music.main;
25 import java.util.Arrays;
26 import java.util.Calendar;
27 import java.util.HashMap;
28 import java.util.Iterator;
30 import java.util.UUID;
31 import javax.ws.rs.core.HttpHeaders;
32 import javax.ws.rs.core.MediaType;
33 import org.apache.commons.codec.binary.Base64;
34 import org.apache.commons.jcs.JCS;
35 import org.apache.commons.jcs.access.CacheAccess;
36 import org.codehaus.jackson.map.ObjectMapper;
37 import org.mindrot.jbcrypt.BCrypt;
38 import org.onap.music.datastore.PreparedQueryObject;
39 import org.onap.music.datastore.jsonobjects.AAFResponse;
40 import org.onap.music.eelf.logging.EELFLoggerDelegate;
41 import org.onap.music.eelf.logging.format.AppMessages;
42 import org.onap.music.eelf.logging.format.ErrorSeverity;
43 import org.onap.music.eelf.logging.format.ErrorTypes;
44 import org.onap.music.exceptions.MusicServiceException;
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 Map<String, Number> userAttempts = new HashMap<>();
70 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
72 public boolean isCacheRefreshNeeded() {
73 if (aafCache.get("initBlankMap") == null)
78 public void initializeMusicCache() {
79 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
80 musicCache.put("isInitialized", "true");
83 public void initializeAafCache() throws MusicServiceException {
84 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
86 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
87 PreparedQueryObject pQuery = new PreparedQueryObject();
88 pQuery.appendQueryString(query);
90 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
91 } catch (Exception e1) {
92 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
95 ResultSet rs = MusicCore.get(pQuery);
96 Iterator<Row> it = rs.iterator();
97 Map<String, String> map = null;
98 while (it.hasNext()) {
100 String nameSpace = row.getString("keyspace_name");
101 String userId = row.getString("username");
102 String password = row.getString("password");
103 String keySpace = row.getString("application_name");
105 userAttempts.put(nameSpace, 0);
106 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
107 if (responseObj.getNs().size() > 0) {
108 map = new HashMap<>();
109 map.put(userId, password);
110 aafCache.put(nameSpace, map);
111 musicCache.put(keySpace, nameSpace);
112 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
115 } catch (Exception e) {
116 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
117 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
126 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
128 initializeAafCache();
129 } catch (MusicServiceException e) {
130 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
134 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
135 String keySpace) throws Exception {
137 if (aafCache.get(nameSpace) != null) {
138 if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
139 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
140 } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
141 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
142 // reset invalid attempts to 0
143 userAttempts.put(nameSpace, 0);
146 // call AAF update cache with new password
147 if (userAttempts.get(nameSpace) == null)
148 userAttempts.put(nameSpace, 0);
149 if ((Integer) userAttempts.get(nameSpace) >= 3) {
150 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
151 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
152 Calendar calendar = Calendar.getInstance();
153 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
154 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
155 if( delayTime > 120000) {
156 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
157 userAttempts.put(nameSpace, 0);
159 logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
160 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
163 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
164 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
168 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
169 if (responseObj.getNs().size() > 0) {
170 if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
171 //Map<String, String> map = new HashMap<>();
172 //map.put(userId, password);
173 //aafCache.put(nameSpace, map);
177 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
181 private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
183 if (MusicUtil.getAafEndpointUrl() == null) {
184 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
185 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
187 Client client = Client.create();
188 // WebResource webResource =
189 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
190 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
191 String plainCreds = userId + ":" + password;
192 byte[] plainCredsBytes = plainCreds.getBytes();
193 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
194 String base64Creds = new String(base64CredsBytes);
196 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
197 .header("Authorization", "Basic " + base64Creds)
198 .header("content-type", "application/json").get(ClientResponse.class);
199 if (response.getStatus() != 200) {
200 if (userAttempts.get(nameSpace) == null)
201 userAttempts.put(nameSpace, 0);
202 if ((Integer) userAttempts.get(nameSpace) >= 2) {
203 lastFailedTime.put(nameSpace, Calendar.getInstance());
204 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
206 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
208 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
210 "Unable to authenticate. Please check the AAF credentials against namespace.");
211 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
212 // for specific time.
214 response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
215 Arrays.asList(MediaType.APPLICATION_JSON));
216 // AAFResponse output = response.getEntity(AAFResponse.class);
217 response.bufferEntity();
218 String x = response.getEntity(String.class);
219 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);
224 public static void updateMusicCache(String keyspace, String nameSpace) {
225 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
226 musicCache.put(keyspace, nameSpace);
229 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
230 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
231 Map<String, String> map = new HashMap<>();
232 map.put(userId, password);
233 musicValidateCache.put(nameSpace, map);
236 public static void updateisAAFCache(String namespace, String isAAF) {
237 appNameCache.put(namespace, isAAF);
240 public static String isAAFApplication(String namespace) throws MusicServiceException {
241 String isAAF = appNameCache.get(namespace);
243 PreparedQueryObject pQuery = new PreparedQueryObject();
244 pQuery.appendQueryString(
245 "SELECT is_aaf from admin.keyspace_master where application_name = '"
246 + namespace + "' allow filtering");
249 rs = MusicCore.get(pQuery).one();
250 } catch(InvalidQueryException e) {
251 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
252 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
255 isAAF = String.valueOf(rs.getBool("is_aaf"));
257 appNameCache.put(namespace, isAAF);
258 } catch (Exception e) {
259 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
266 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
269 PreparedQueryObject pQuery = new PreparedQueryObject();
270 pQuery.appendQueryString(
271 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
272 + keyspace + "' allow filtering");
273 Row rs = MusicCore.get(pQuery).one();
275 uuid = rs.getUUID("uuid").toString();
276 } catch (Exception e) {
277 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
284 public static String getAppName(String keyspace) throws MusicServiceException {
285 String appName = null;
286 PreparedQueryObject pQuery = new PreparedQueryObject();
287 pQuery.appendQueryString(
288 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
289 + keyspace + "' allow filtering");
290 Row rs = MusicCore.get(pQuery).one();
292 appName = rs.getString("application_name");
293 } catch (Exception e) {
294 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
300 public static String generateUUID() {
301 String uuid = UUID.randomUUID().toString();
302 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
306 public static Map<String, Object> validateRequest(String nameSpace, String userId,
307 String password, String keyspace, String aid, String operation) {
308 Map<String, Object> resultMap = new HashMap<>();
309 if (!"createKeySpace".equals(operation)) {
310 if (nameSpace == null) {
311 resultMap.put("Exception", "Application namespace is mandatory.");
318 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
319 Map<String, Object> resultMap = new HashMap<>();
320 if (ns == null || userId == null || password == null) {
321 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
322 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
323 resultMap.put("Exception",
324 "One or more required headers appName(ns), userId, password is missing. Please check.");
327 PreparedQueryObject queryObject = new PreparedQueryObject();
328 queryObject.appendQueryString(
329 "select * from admin.keyspace_master where application_name = ? allow filtering");
331 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
332 } catch(Exception e) {
333 resultMap.put("Exception",
334 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
339 rs = MusicCore.get(queryObject).one();
340 } catch (MusicServiceException e) {
341 // TODO Auto-generated catch block
343 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
345 } catch (InvalidQueryException e) {
346 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
347 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
351 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
352 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
354 if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
355 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
356 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
357 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
364 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
366 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(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
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 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(!BCrypt.checkpw(password, pwd)) {
413 resultMap.put("Exception", "Invalid password");
417 CachingUtil.updateMusicCache(keyspace, nameSpace);
418 CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);