2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2017 AT&T Intellectual Property
6 * ===================================================================
7 * Modifications Copyright (c) 2018 IBM
8 * Modifications Copyright (c) 2019 Samsung
9 * ===================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
22 * ============LICENSE_END=============================================
23 * ====================================================================
26 package org.onap.music.authentication;
28 import java.util.Calendar;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
33 import javax.ws.rs.core.MediaType;
35 import org.apache.commons.codec.binary.Base64;
36 import org.apache.commons.jcs.JCS;
37 import org.apache.commons.jcs.access.CacheAccess;
38 import org.mindrot.jbcrypt.BCrypt;
39 import org.onap.music.authentication.MusicAuthenticator.Operation;
40 import org.onap.music.datastore.PreparedQueryObject;
41 import org.onap.music.eelf.logging.EELFLoggerDelegate;
42 import org.onap.music.eelf.logging.format.AppMessages;
43 import org.onap.music.eelf.logging.format.ErrorSeverity;
44 import org.onap.music.eelf.logging.format.ErrorTypes;
45 import org.onap.music.exceptions.MusicServiceException;
46 import org.onap.music.main.MusicCore;
47 import org.onap.music.main.MusicUtil;
48 import com.datastax.driver.core.DataType;
49 import com.datastax.driver.core.PreparedStatement;
50 import com.datastax.driver.core.ResultSet;
51 import com.datastax.driver.core.Row;
52 import com.datastax.driver.core.exceptions.InvalidQueryException;
53 import com.sun.jersey.api.client.Client;
54 import com.sun.jersey.api.client.ClientResponse;
55 import com.sun.jersey.api.client.WebResource;
58 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
63 public class CachingUtil implements Runnable {
65 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
68 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
69 /** cache to hold isaaf application */
70 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
71 /** hold user creds for namespace */
72 private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
73 private static Map<String, Number> userAttempts = new HashMap<>();
74 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
75 private static CacheAccess<String, String> adminUserCache = JCS.getInstance("adminUserCache");
77 public static CacheAccess<String, String> getAdminUserCache() {
78 return adminUserCache;
81 public static void updateAdminUserCache(String authorization,String userId) {
82 adminUserCache.put(authorization,userId);
85 private static final String USERNAME="username";
86 private static final String PASSWORD="password";
89 public void initializeAafCache() throws MusicServiceException {
90 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
92 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
93 PreparedQueryObject pQuery = new PreparedQueryObject();
94 pQuery.appendQueryString(query);
96 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
97 } catch (Exception e1) {
98 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
100 ResultSet rs = MusicCore.get(pQuery);
101 Iterator<Row> it = rs.iterator();
102 Map<String, String> map = null;
103 while (it.hasNext()) {
105 String nameSpace = row.getString("keyspace_name");
106 String userId = row.getString(USERNAME);
107 String password = row.getString(PASSWORD);
108 String keySpace = row.getString("application_name");
110 userAttempts.put(nameSpace, 0);
111 boolean responseObj = triggerAAF(nameSpace, userId, password);
113 map = new HashMap<>();
114 map.put(userId, password);
115 musicValidateCache.put(nameSpace, map);
116 musicCache.put(keySpace, nameSpace);
117 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
120 } catch (Exception e) {
121 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
122 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
130 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
132 initializeAafCache();
133 } catch (MusicServiceException e) {
134 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
138 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
139 String keySpace) throws Exception {
141 if (musicValidateCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) {
142 if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
143 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
144 } else if (musicValidateCache.get(nameSpace).get(userId).equals(password)) {
145 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
146 // reset invalid attempts to 0
147 userAttempts.put(nameSpace, 0);
150 // call AAF update cache with new password
151 if (userAttempts.get(nameSpace) == null)
152 userAttempts.put(nameSpace, 0);
153 if ((Integer) userAttempts.get(nameSpace) >= 3) {
154 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
155 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
156 Calendar calendar = Calendar.getInstance();
157 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
158 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
159 if( delayTime > 120000) {
160 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
161 userAttempts.put(nameSpace, 0);
163 logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
164 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
167 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
168 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
172 boolean responseObj = false;
174 responseObj = triggerAAF(nameSpace, userId, password);
175 }catch (Exception ex) {
176 logger.info("Exception while trigger aaf");
177 logger.info("Exception: " + ex.getMessage());
178 throw new Exception("Exception raised while triggering AAF authentication" +ex.getMessage());
181 logger.info(EELFLoggerDelegate.applicationLogger,"Valid user. Cache is updated for "+nameSpace);
182 Map<String, String> map = new HashMap<>();
183 map.put(userId, password);
184 musicValidateCache.put(nameSpace, map);
185 musicCache.put(keySpace, nameSpace);
188 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
192 private static boolean triggerAAF(String nameSpace, String userId, String password)
194 logger.info(EELFLoggerDelegate.applicationLogger,"Inside AAF authorization");
195 if (MusicUtil.getAafEndpointUrl() == null) {
196 logger.error(EELFLoggerDelegate.errorLogger,"AAF endpoint is not set. Please specify in the properties file.",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
197 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
199 Client client = Client.create();
200 // WebResource webResource =
201 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
202 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
203 String plainCreds = userId + ":" + password;
204 byte[] plainCredsBytes = plainCreds.getBytes();
205 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
206 String base64Creds = new String(base64CredsBytes);
208 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
209 .header("Authorization", "Basic " + base64Creds)
210 .header("content-type", "application/json").get(ClientResponse.class);
211 logger.info(EELFLoggerDelegate.applicationLogger, "aaf response: "+response.toString());
212 if (response.getStatus() != 200) {
213 if (userAttempts.get(nameSpace) == null)
214 userAttempts.put(nameSpace, 0);
215 if ((Integer) userAttempts.get(nameSpace) >= 2) {
216 lastFailedTime.put(nameSpace, Calendar.getInstance());
217 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
219 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
221 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
223 "Unable to authenticate. Please check the AAF credentials against namespace.");
224 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
225 // for specific time.
227 /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
228 Arrays.asList(MediaType.APPLICATION_JSON));
229 // AAFResponse output = response.getEntity(AAFResponse.class);
230 response.bufferEntity();
231 String x = response.getEntity(String.class);
232 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
237 public static void updateMusicCache(String keyspace, String nameSpace) {
238 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
239 musicCache.put(keyspace, nameSpace);
242 public static void updateCadiCache(String user, String keyspace) {
243 musicCache.put(user, keyspace);
246 public static String getKSFromCadiCache(String user) {
247 return musicCache.get(user);
250 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
251 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
252 Map<String, String> map = new HashMap<>();
253 map.put(userId, password);
254 musicValidateCache.put(nameSpace, map);
257 public static void updateisAAFCache(String namespace, String isAAF) {
258 appNameCache.put(namespace, isAAF);
261 public static String isAAFApplication(String namespace) throws MusicServiceException {
262 String isAAF = appNameCache.get(namespace);
264 PreparedQueryObject pQuery = new PreparedQueryObject();
265 pQuery.appendQueryString(
266 "SELECT is_aaf from admin.keyspace_master where application_name = '"
267 + namespace + "' allow filtering");
270 rs = MusicCore.get(pQuery).one();
271 } catch(InvalidQueryException e) {
272 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
273 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
276 isAAF = String.valueOf(rs.getBool("is_aaf"));
278 appNameCache.put(namespace, isAAF);
279 } catch (Exception e) {
280 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
286 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
289 PreparedQueryObject pQuery = new PreparedQueryObject();
290 pQuery.appendQueryString(
291 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
292 + keyspace + "' allow filtering");
293 Row rs = MusicCore.get(pQuery).one();
295 uuid = rs.getUUID("uuid").toString();
296 } catch (Exception e) {
297 logger.error(EELFLoggerDelegate.errorLogger,"Exception occurred during uuid retrieval from DB."+e.getMessage());
303 public static String getAppName(String keyspace) throws MusicServiceException {
304 String appName = null;
305 PreparedQueryObject pQuery = new PreparedQueryObject();
306 pQuery.appendQueryString(
307 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
308 + keyspace + "' allow filtering");
309 Row rs = MusicCore.get(pQuery).one();
311 appName = rs.getString("application_name");
312 } catch (Exception e) {
313 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
319 public static Map<String, Object> validateRequest(String nameSpace, String userId,
320 String password, String keyspace, String aid, String operation) {
321 Map<String, Object> resultMap = new HashMap<>();
322 if (!"createKeySpace".equals(operation)) {
323 if (nameSpace == null) {
324 resultMap.put("Exception", "Application namespace is mandatory.");
330 public static Map<String, Object> validateRequest(String nameSpace, String userId,
331 String password, String keyspace, String aid, Operation operation) {
332 Map<String, Object> resultMap = new HashMap<>();
333 if (Operation.CREATE_KEYSPACE!=operation) {
334 if (nameSpace == null) {
335 resultMap.put("Exception", "Application namespace is mandatory.");
341 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
342 Map<String, Object> resultMap = new HashMap<>();
343 if (ns == null || userId == null || password == null) {
344 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
345 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
346 resultMap.put("Exception",
347 "One or more required headers appName(ns), userId, password is missing. Please check.");
350 PreparedQueryObject queryObject = new PreparedQueryObject();
351 queryObject.appendQueryString(
352 "select * from admin.keyspace_master where application_name = ? allow filtering");
354 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
355 } catch(Exception e) {
356 resultMap.put("Exception",
357 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
362 rs = MusicCore.get(queryObject).one();
363 } catch (MusicServiceException e) {
364 String errorMsg = "Unable to process operation. Error is "+e.getMessage();
365 logger.error(EELFLoggerDelegate.errorLogger, errorMsg);
366 resultMap.put("Exception", errorMsg);
368 } catch (InvalidQueryException e) {
369 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
370 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
374 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
375 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
377 if(!(rs.getString(USERNAME).equals(userId)) || !(BCrypt.checkpw(password, rs.getString(PASSWORD)))) {
378 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
379 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
380 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
387 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
389 Map<String, Object> resultMap = new HashMap<>();
391 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
392 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
393 if(!musicCache.get(keyspace).equals(nameSpace)) {
394 resultMap.put("Exception", "Namespace and keyspace doesn't match");
397 if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
398 resultMap.put("Exception", "Namespace, userId and password doesn't match");
403 PreparedQueryObject queryObject = new PreparedQueryObject();
404 queryObject.appendQueryString(
405 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
407 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
408 } catch (Exception e) {
409 logger.error(EELFLoggerDelegate.errorLogger,"Adding value to query object failed: " + e.getMessage());
413 rs = MusicCore.get(queryObject).one();
414 } catch (MusicServiceException e) {
415 String errMsg = "Unable to process operation. Error is "+e.getMessage();
416 logger.error(EELFLoggerDelegate.errorLogger, errMsg);
417 resultMap.put("Exception", errMsg);
421 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
425 String user = rs.getString(USERNAME);
426 pwd = rs.getString(PASSWORD);
427 String ns = rs.getString("application_name");
428 if(!ns.equals(nameSpace)) {
429 resultMap.put("Exception", "Namespace and keyspace doesn't match");
432 if(!user.equals(userId)) {
433 resultMap.put("Exception", "Invalid userId :"+userId);
436 if(!BCrypt.checkpw(password, pwd)) {
437 resultMap.put("Exception", "Invalid password");
441 CachingUtil.updateMusicCache(keyspace, nameSpace);
442 CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);