Initial OpenECOMP policy/engine commit
[policy/engine.git] / PyPDPServer / src / main / java / org / openecomp / policy / pypdp / authorization / AuthenticationService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.pypdp.authorization;
22
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.nio.file.Files;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Base64;
32 import java.util.HashMap;
33 import java.util.Properties;
34 import java.util.StringTokenizer;
35
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.openecomp.policy.common.logging.eelf.MessageCodes;
39 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
40
41 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
42
43 public class AuthenticationService {
44         private String pyPDPID = Config.getPYPDPID();
45         private String pyPDPPass = Config.getPYPDPPass();
46         private static Path clientPath = null;
47         private static HashMap<String, ArrayList<String>> clientMap = null;
48         private static Long oldModified = null;
49         private static Long newModified = null;
50         private static final Log logger = LogFactory.getLog(AuthenticationService.class);
51         
52         public boolean authenticate(String authCredentials) {
53
54                 if (null == authCredentials)
55                         return false;
56                 // header value format will be "Basic encodedstring" for Basic authentication. 
57                 final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
58                 String usernameAndPassword = null;
59                 try {
60                         byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
61                         usernameAndPassword = new String(decodedBytes, "UTF-8");
62                 } catch (Exception e) {
63                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
64                         // TODO:EELF Cleanup - Remove logger
65                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "");
66                         return false;
67                 }
68                 try {
69                         final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
70                         final String username = tokenizer.nextToken();
71                         final String password = tokenizer.nextToken();
72
73                         boolean authenticationStatus = pyPDPID.equals(username) && pyPDPPass.equals(password);
74                         return authenticationStatus;
75                 } catch (Exception e){
76                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
77                         // TODO:EELF Cleanup - Remove logger
78                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
79                         return false;
80                 }
81         }
82         
83         public static boolean clientAuth(String clientCredentials) {
84                 if(clientCredentials == null){
85                         return false; 
86                 }
87                 // Decode the encoded Client Credentials. 
88                 String usernameAndPassword = null;
89                 try {
90                         byte[] decodedBytes = Base64.getDecoder().decode(clientCredentials);
91                         usernameAndPassword = new String(decodedBytes, "UTF-8");
92                 } catch (Exception e) {
93                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
94                         // TODO:EELF Cleanup - Remove logger
95                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "");
96                         return false;
97                 }
98                 try {
99                         final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
100                         final String username = tokenizer.nextToken();
101                         final String password = tokenizer.nextToken(); 
102                         return checkClient(username,password);
103                 } catch(Exception e){
104                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
105                         // TODO:EELF Cleanup - Remove logger
106                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "");
107                         return false;
108                 }
109         }
110         
111         public static boolean checkClientScope(String clientCredentials, String scope) {
112                 if(clientCredentials == null){
113                         return false; 
114                 }
115                 // Decode the encoded Client Credentials. 
116                 String usernameAndPassword = null;
117                 try {
118                         byte[] decodedBytes = Base64.getDecoder().decode(clientCredentials);
119                         usernameAndPassword = new String(decodedBytes, "UTF-8");
120                 } catch (Exception e) {
121                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
122                         // TODO:EELF Cleanup - Remove logger
123                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "");
124                         return false;
125                 }
126                 final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
127                 final String username = tokenizer.nextToken();
128                 // Read the properties and compare.
129                 try{
130                         readFile();
131                 }catch(Exception e){
132                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
133                         // TODO:EELF Cleanup - Remove logger
134                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
135                         return false;
136                 }
137                 // Check ID, Scope
138                 if (clientMap.containsKey(username) && (clientMap.get(username).get(1).equals(scope) || clientMap.get(username).get(1).equals("MASTER"))) {
139                         return true;
140                 }
141                 return false;
142         }
143         
144         private static boolean checkClient(String username, String password) {
145                 // Read the properties and compare.
146                 try{
147                         readFile();
148                 }catch(Exception e){
149                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
150                         // TODO:EELF Cleanup - Remove logger
151                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
152                         return false;
153                 }
154                 // Check ID, Key
155                 if (clientMap.containsKey(username) && clientMap.get(username).get(0).equals(password)) {
156                         return true;
157                 }
158                 return false;
159         }       
160         
161         private static void readFile() throws Exception {
162                 String clientFile =  Config.getClientFile();
163                 if (clientFile == null) {
164                         Config.setProperty();
165                         if(clientFile == null){
166                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Missing CLIENT_FILE property value: " + clientFile);
167                                 // TODO:EELF Cleanup - Remove logger
168                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Missing CLIENT_FILE property value: " + clientFile);
169                                 throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Missing CLIENT_FILE property value: " + clientFile);
170                         }
171                 }
172                 if (clientPath == null) {
173                         clientPath = Paths.get(clientFile);
174                         if (Files.notExists(clientPath)) {
175                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : "     + clientPath.toString());
176                                 // TODO:EELF Cleanup - Remove logger
177                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "File doesn't exist in the specified Path : "       + clientPath.toString());
178                                 throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ clientPath.toString());
179                         } 
180                         if (clientPath.toString().endsWith(".properties")) {
181                                 readProps();
182                         } else {
183                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + clientFile);
184                                 // TODO:EELF Cleanup - Remove logger
185                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Not a .properties file " + clientFile);
186                                 throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file " + clientFile);
187                         }
188                 }
189                 // Check if File is updated recently
190                 else {
191                         newModified = clientPath.toFile().lastModified();
192                         if (newModified != oldModified) {
193                                 // File has been updated.
194                                 readProps();
195                         }
196                 }
197         }
198
199         private static void readProps() throws Exception{
200                 InputStream in;
201                 Properties clientProp = new Properties();
202                 try {
203                         in = new FileInputStream(clientPath.toFile());
204                         oldModified = clientPath.toFile().lastModified();
205                         clientProp.load(in);
206                 } catch (IOException e) {
207                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
208                         // TODO:EELF Cleanup - Remove logger
209                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
210                         throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e);
211                         
212                 }
213                 // Read the Properties and Load the PDPs and encoding.
214                 clientMap = new HashMap<String, ArrayList<String>>();
215                 // 
216                 for (Object propKey : clientProp.keySet()) {
217                         String clientID = (String)propKey; 
218                         String clientValue = clientProp.getProperty(clientID);
219                         if (clientValue != null) {
220                                 if (clientValue.contains(",")) {
221                                         ArrayList<String> clientValues = new ArrayList<String>(Arrays.asList(clientValue.split("\\s*,\\s*")));
222                                         if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){
223                                                 clientMap.put(clientID, clientValues);
224                                         }
225                                 } 
226                         }
227                 }
228                 if (clientMap == null || clientMap.isEmpty()) {
229                         logger.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!");
230                 }
231         }
232 }