Code Coverage, Auth ID, Docker
[music.git] / src / main / java / org / onap / music / main / CachingUtil.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
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
10  * 
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  * 
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.
18  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22 package org.onap.music.main;
23
24 import java.util.Arrays;
25 import java.util.Calendar;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.Map;
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;
43
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;
52
53 /**
54  * All Caching related logic is handled by this class and a schedule cron runs to update cache.
55  * 
56  * @author Vikram
57  *
58  */
59 public class CachingUtil implements Runnable {
60
61     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
62
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<>();
69
70     public boolean isCacheRefreshNeeded() {
71         if (aafCache.get("initBlankMap") == null)
72             return true;
73         return false;
74     }
75
76     public void initializeMusicCache() {
77         logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
78         musicCache.put("isInitialized", "true");
79     }
80
81     public void initializeAafCache() throws MusicServiceException {
82         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
83
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);
87         try {
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);
91             e1.printStackTrace();
92         }
93         ResultSet rs = MusicCore.get(pQuery);
94         Iterator<Row> it = rs.iterator();
95         Map<String, String> map = null;
96         while (it.hasNext()) {
97             Row row = it.next();
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");
102             try {
103                 userAttempts.put(nameSpace, 0);
104                 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
105                 if (responseObj.getNs().size() > 0) {
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 "
111                                     + nameSpace);
112                 }
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. ");
116                 e.printStackTrace();
117             }
118         }
119
120     }
121
122     @Override
123     public void run() {
124         logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
125         try {
126                         initializeAafCache();
127                 } catch (MusicServiceException e) {
128                         logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
129                 }
130     }
131
132     public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
133                     String keySpace) throws Exception {
134
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);
142                 return true;
143             } else {
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);
156                     } else {
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.");
159                     }
160                 }
161                 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
162                 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
163             }
164         }
165
166         AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
167         if (responseObj.getNs().size() > 0) {
168             if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
169                 //Map<String, String> map = new HashMap<>();
170                 //map.put(userId, password);
171                 //aafCache.put(nameSpace, map);
172                 return true;
173             }
174         }
175         logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
176         return false;
177     }
178
179     private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
180                     throws Exception {
181         if (MusicUtil.getAafEndpointUrl() == null) {
182                 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
183             throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
184         }
185         Client client = Client.create();
186         // WebResource webResource =
187         // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
188         WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
189         String plainCreds = userId + ":" + password;
190         byte[] plainCredsBytes = plainCreds.getBytes();
191         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
192         String base64Creds = new String(base64CredsBytes);
193
194         ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
195                         .header("Authorization", "Basic " + base64Creds)
196                         .header("content-type", "application/json").get(ClientResponse.class);
197         if (response.getStatus() != 200) {
198             if (userAttempts.get(nameSpace) == null)
199                 userAttempts.put(nameSpace, 0);
200             if ((Integer) userAttempts.get(nameSpace) >= 2) {
201                 lastFailedTime.put(nameSpace, Calendar.getInstance());
202                 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
203                 throw new Exception(
204                                 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
205             }
206             userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
207             throw new Exception(
208                             "Unable to authenticate. Please check the AAF credentials against namespace.");
209             // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
210             // for specific time.
211         }
212         response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
213                         Arrays.asList(MediaType.APPLICATION_JSON));
214         // AAFResponse output = response.getEntity(AAFResponse.class);
215         response.bufferEntity();
216         String x = response.getEntity(String.class);
217         AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);
218         
219         return responseObj;
220     }
221
222     public static void updateMusicCache(String keyspace, String nameSpace) {
223         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
224         musicCache.put(keyspace, nameSpace);
225     }
226
227     public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
228         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
229         Map<String, String> map = new HashMap<>();
230         map.put(userId, password);
231         musicValidateCache.put(nameSpace, map);
232     }
233     
234     public static void updateisAAFCache(String namespace, String isAAF) {
235         appNameCache.put(namespace, isAAF);
236     }
237
238     public static String isAAFApplication(String namespace) throws MusicServiceException {
239         String isAAF = appNameCache.get(namespace);
240         if (isAAF == null) {
241             PreparedQueryObject pQuery = new PreparedQueryObject();
242             pQuery.appendQueryString(
243                             "SELECT is_aaf from admin.keyspace_master where application_name = '"
244                                             + namespace + "' allow filtering");
245             Row rs = null;
246             try {
247                 rs = MusicCore.get(pQuery).one();
248             } catch(InvalidQueryException e) {
249                 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
250                 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
251             }
252             try {
253                 isAAF = String.valueOf(rs.getBool("is_aaf"));
254                 if(isAAF != null)
255                     appNameCache.put(namespace, isAAF);
256             } catch (Exception e) {
257                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
258                 e.printStackTrace();
259             }
260         }
261         return isAAF;
262     }
263
264     public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
265         String uuid = null;
266         if (uuid == null) {
267             PreparedQueryObject pQuery = new PreparedQueryObject();
268             pQuery.appendQueryString(
269                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
270                                             + keyspace + "' allow filtering");
271             Row rs = MusicCore.get(pQuery).one();
272             try {
273                 uuid = rs.getUUID("uuid").toString();
274             } catch (Exception e) {
275                 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
276                 e.printStackTrace();
277             }
278         }
279         return uuid;
280     }
281
282     public static String getAppName(String keyspace) throws MusicServiceException {
283         String appName = null;
284         PreparedQueryObject pQuery = new PreparedQueryObject();
285         pQuery.appendQueryString(
286                         "SELECT application_name from admin.keyspace_master where keyspace_name = '"
287                                         + keyspace + "' allow filtering");
288         Row rs = MusicCore.get(pQuery).one();
289         try {
290             appName = rs.getString("application_name");
291         } catch (Exception e) {
292                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
293             e.printStackTrace();
294         }
295         return appName;
296     }
297
298     public static String generateUUID() {
299         String uuid = UUID.randomUUID().toString();
300         logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
301         return uuid;
302     }
303
304     public static Map<String, Object> validateRequest(String nameSpace, String userId,
305                     String password, String keyspace, String aid, String operation) {
306         Map<String, Object> resultMap = new HashMap<>();
307         if (!"createKeySpace".equals(operation)) {
308             if (nameSpace == null) {
309                 resultMap.put("Exception", "Application namespace is mandatory.");
310             }
311         }
312         return resultMap;
313
314     }
315
316     public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
317         Map<String, Object> resultMap = new HashMap<>();
318         if (ns == null || userId == null || password == null) {
319                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
320                 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
321             resultMap.put("Exception",
322                             "One or more required headers appName(ns), userId, password is missing. Please check.");
323             return resultMap;
324         }
325         PreparedQueryObject queryObject = new PreparedQueryObject();
326         queryObject.appendQueryString(
327                         "select * from admin.keyspace_master where application_name = ? allow filtering");
328         try {
329                 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
330         } catch(Exception e) {
331                 resultMap.put("Exception",
332                     "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
333                 return resultMap;
334         }
335         Row rs = null;
336                 try {
337                         rs = MusicCore.get(queryObject).one();
338                 } catch (MusicServiceException e) {
339                         // TODO Auto-generated catch block
340                         e.printStackTrace();
341                         resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
342                         return resultMap;
343         } catch (InvalidQueryException e) {
344             logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
345             resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
346             return resultMap;
347         }
348         if (rs == null) {
349             logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
350             resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
351         } else {
352             if(!(rs.getString("username").equals(userId)) || !(rs.getString("password").equals(password))) {
353                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
354                 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
355                 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
356                 return resultMap;
357             }
358         }
359         return resultMap;
360     }
361
362     public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
363            String keyspace) {
364         Map<String, Object> resultMap = new HashMap<>();
365         if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null) 
366                 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
367             if(!musicCache.get(keyspace).equals(nameSpace)) {
368                 resultMap.put("Exception", "Namespace and keyspace doesn't match");
369                 return resultMap;
370             }
371             if(!musicValidateCache.get(nameSpace).get(userId).equals(password)) {
372                 resultMap.put("Exception", "Namespace, userId and password doesn't match");
373                 return resultMap;
374             }
375             return resultMap;
376         }
377         PreparedQueryObject queryObject = new PreparedQueryObject();
378         queryObject.appendQueryString(
379                         "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
380         try {
381             queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
382         } catch (Exception e) {
383             e.printStackTrace();
384         }
385         Row rs = null;
386         try {
387             rs = MusicCore.get(queryObject).one();
388         } catch (MusicServiceException e) {
389             e.printStackTrace();
390             resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
391             return resultMap;
392         }
393         if(rs == null) {
394             resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
395             return resultMap;
396         }
397         else {
398             String user = rs.getString("username");
399             String pwd = rs.getString("password");
400             String ns = rs.getString("application_name");
401             if(!ns.equals(nameSpace)) {
402             resultMap.put("Exception", "Namespace and keyspace doesn't match");
403             return resultMap;
404             }
405             if(!user.equals(userId)) {
406                 resultMap.put("Exception", "Invalid userId :"+userId);
407                 return resultMap;
408             }
409             if(!pwd.equals(password)) {
410                 resultMap.put("Exception", "Invalid password");
411                 return resultMap;
412             }
413         }
414         CachingUtil.updateMusicCache(keyspace, nameSpace);
415         CachingUtil.updateMusicValidateCache(nameSpace, userId, password);
416         return resultMap;
417     }
418 }