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, PreparedStatement> queryBank = JCS.getInstance("statementBank");
76 private static CacheAccess<String, String> adminUserCache = JCS.getInstance("adminUserCache");
78 public static CacheAccess<String, String> getAdminUserCache() {
79 return adminUserCache;
82 public static void updateAdminUserCache(String authorization,String userId) {
83 adminUserCache.put(authorization,userId);
87 public static void updateStatementBank(String query,PreparedStatement statement) {
88 queryBank.put(query, statement);
91 public static void resetStatementBank() {
95 public static CacheAccess<String, PreparedStatement> getStatementBank() {
99 private static final String USERNAME="username";
100 private static final String PASSWORD="password";
103 public void initializeAafCache() throws MusicServiceException {
104 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
106 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
107 PreparedQueryObject pQuery = new PreparedQueryObject();
108 pQuery.appendQueryString(query);
110 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
111 } catch (Exception e1) {
112 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
114 ResultSet rs = MusicCore.get(pQuery);
115 Iterator<Row> it = rs.iterator();
116 Map<String, String> map = null;
117 while (it.hasNext()) {
119 String nameSpace = row.getString("keyspace_name");
120 String userId = row.getString(USERNAME);
121 String password = row.getString(PASSWORD);
122 String keySpace = row.getString("application_name");
124 userAttempts.put(nameSpace, 0);
125 boolean responseObj = triggerAAF(nameSpace, userId, password);
127 map = new HashMap<>();
128 map.put(userId, password);
129 musicValidateCache.put(nameSpace, map);
130 musicCache.put(keySpace, nameSpace);
131 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
134 } catch (Exception e) {
135 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
136 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
144 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
146 initializeAafCache();
147 } catch (MusicServiceException e) {
148 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
152 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
153 String keySpace) throws Exception {
155 if (musicValidateCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) {
156 if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
157 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
158 } else if (musicValidateCache.get(nameSpace).get(userId).equals(password)) {
159 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
160 // reset invalid attempts to 0
161 userAttempts.put(nameSpace, 0);
164 // call AAF update cache with new password
165 if (userAttempts.get(nameSpace) == null)
166 userAttempts.put(nameSpace, 0);
167 if ((Integer) userAttempts.get(nameSpace) >= 3) {
168 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
169 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
170 Calendar calendar = Calendar.getInstance();
171 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
172 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
173 if( delayTime > 120000) {
174 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
175 userAttempts.put(nameSpace, 0);
177 logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
178 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
181 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
182 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
186 boolean responseObj = false;
188 responseObj = triggerAAF(nameSpace, userId, password);
189 }catch (Exception ex) {
190 logger.info("Exception while trigger aaf");
191 logger.info("Exception: " + ex.getMessage());
192 throw new Exception("Exception raised while triggering AAF authentication" +ex.getMessage());
195 logger.info(EELFLoggerDelegate.applicationLogger,"Valid user. Cache is updated for "+nameSpace);
196 Map<String, String> map = new HashMap<>();
197 map.put(userId, password);
198 musicValidateCache.put(nameSpace, map);
199 musicCache.put(keySpace, nameSpace);
202 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
206 private static boolean triggerAAF(String nameSpace, String userId, String password)
208 logger.info(EELFLoggerDelegate.applicationLogger,"Inside AAF authorization");
209 if (MusicUtil.getAafEndpointUrl() == null) {
210 logger.error(EELFLoggerDelegate.errorLogger,"AAF endpoint is not set. Please specify in the properties file.",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
211 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
213 Client client = Client.create();
214 // WebResource webResource =
215 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
216 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
217 String plainCreds = userId + ":" + password;
218 byte[] plainCredsBytes = plainCreds.getBytes();
219 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
220 String base64Creds = new String(base64CredsBytes);
222 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
223 .header("Authorization", "Basic " + base64Creds)
224 .header("content-type", "application/json").get(ClientResponse.class);
225 logger.info(EELFLoggerDelegate.applicationLogger, "aaf response: "+response.toString());
226 if (response.getStatus() != 200) {
227 if (userAttempts.get(nameSpace) == null)
228 userAttempts.put(nameSpace, 0);
229 if ((Integer) userAttempts.get(nameSpace) >= 2) {
230 lastFailedTime.put(nameSpace, Calendar.getInstance());
231 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
233 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
235 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
237 "Unable to authenticate. Please check the AAF credentials against namespace.");
238 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
239 // for specific time.
241 /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
242 Arrays.asList(MediaType.APPLICATION_JSON));
243 // AAFResponse output = response.getEntity(AAFResponse.class);
244 response.bufferEntity();
245 String x = response.getEntity(String.class);
246 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
251 public static void updateMusicCache(String keyspace, String nameSpace) {
252 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
253 musicCache.put(keyspace, nameSpace);
256 public static void updateCadiCache(String user, String keyspace) {
257 musicCache.put(user, keyspace);
260 public static String getKSFromCadiCache(String user) {
261 return musicCache.get(user);
264 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
265 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
266 Map<String, String> map = new HashMap<>();
267 map.put(userId, password);
268 musicValidateCache.put(nameSpace, map);
271 public static void updateisAAFCache(String namespace, String isAAF) {
272 appNameCache.put(namespace, isAAF);
275 public static String isAAFApplication(String namespace) throws MusicServiceException {
276 String isAAF = appNameCache.get(namespace);
278 PreparedQueryObject pQuery = new PreparedQueryObject();
279 pQuery.appendQueryString(
280 "SELECT is_aaf from admin.keyspace_master where application_name = '"
281 + namespace + "' allow filtering");
284 rs = MusicCore.get(pQuery).one();
285 } catch(InvalidQueryException e) {
286 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
287 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
290 isAAF = String.valueOf(rs.getBool("is_aaf"));
292 appNameCache.put(namespace, isAAF);
293 } catch (Exception e) {
294 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
300 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
303 PreparedQueryObject pQuery = new PreparedQueryObject();
304 pQuery.appendQueryString(
305 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
306 + keyspace + "' allow filtering");
307 Row rs = MusicCore.get(pQuery).one();
309 uuid = rs.getUUID("uuid").toString();
310 } catch (Exception e) {
311 logger.error(EELFLoggerDelegate.errorLogger,"Exception occurred during uuid retrieval from DB."+e.getMessage());
317 public static String getAppName(String keyspace) throws MusicServiceException {
318 String appName = null;
319 PreparedQueryObject pQuery = new PreparedQueryObject();
320 pQuery.appendQueryString(
321 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
322 + keyspace + "' allow filtering");
323 Row rs = MusicCore.get(pQuery).one();
325 appName = rs.getString("application_name");
326 } catch (Exception e) {
327 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
333 public static Map<String, Object> validateRequest(String nameSpace, String userId,
334 String password, String keyspace, String aid, String operation) {
335 Map<String, Object> resultMap = new HashMap<>();
336 if (!"createKeySpace".equals(operation)) {
337 if (nameSpace == null) {
338 resultMap.put("Exception", "Application namespace is mandatory.");
344 public static Map<String, Object> validateRequest(String nameSpace, String userId,
345 String password, String keyspace, String aid, Operation operation) {
346 Map<String, Object> resultMap = new HashMap<>();
347 if (Operation.CREATE_KEYSPACE!=operation) {
348 if (nameSpace == null) {
349 resultMap.put("Exception", "Application namespace is mandatory.");
355 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
356 Map<String, Object> resultMap = new HashMap<>();
357 if (ns == null || userId == null || password == null) {
358 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
359 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
360 resultMap.put("Exception",
361 "One or more required headers appName(ns), userId, password is missing. Please check.");
364 PreparedQueryObject queryObject = new PreparedQueryObject();
365 queryObject.appendQueryString(
366 "select * from admin.keyspace_master where application_name = ? allow filtering");
368 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
369 } catch(Exception e) {
370 resultMap.put("Exception",
371 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
376 rs = MusicCore.get(queryObject).one();
377 } catch (MusicServiceException e) {
378 String errorMsg = "Unable to process operation. Error is "+e.getMessage();
379 logger.error(EELFLoggerDelegate.errorLogger, errorMsg);
380 resultMap.put("Exception", errorMsg);
382 } catch (InvalidQueryException e) {
383 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
384 resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
388 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
389 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
391 if(!(rs.getString(USERNAME).equals(userId)) || !(BCrypt.checkpw(password, rs.getString(PASSWORD)))) {
392 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
393 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
394 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
401 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
403 Map<String, Object> resultMap = new HashMap<>();
405 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
406 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
407 if(!musicCache.get(keyspace).equals(nameSpace)) {
408 resultMap.put("Exception", "Namespace and keyspace doesn't match");
411 if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
412 resultMap.put("Exception", "Namespace, userId and password doesn't match");
417 PreparedQueryObject queryObject = new PreparedQueryObject();
418 queryObject.appendQueryString(
419 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
421 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
422 } catch (Exception e) {
423 logger.error(EELFLoggerDelegate.errorLogger,"Adding value to query object failed: " + e.getMessage());
427 rs = MusicCore.get(queryObject).one();
428 } catch (MusicServiceException e) {
429 String errMsg = "Unable to process operation. Error is "+e.getMessage();
430 logger.error(EELFLoggerDelegate.errorLogger, errMsg);
431 resultMap.put("Exception", errMsg);
435 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
439 String user = rs.getString(USERNAME);
440 pwd = rs.getString(PASSWORD);
441 String ns = rs.getString("application_name");
442 if(!ns.equals(nameSpace)) {
443 resultMap.put("Exception", "Namespace and keyspace doesn't match");
446 if(!user.equals(userId)) {
447 resultMap.put("Exception", "Invalid userId :"+userId);
450 if(!BCrypt.checkpw(password, pwd)) {
451 resultMap.put("Exception", "Invalid password");
455 CachingUtil.updateMusicCache(keyspace, nameSpace);
456 CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);