Commit includes ControlLoopPolicy API and bugfixes
[policy/engine.git] / ECOMP-PDP-REST / src / main / java / org / openecomp / policy / pdp / rest / config / PDPApiAuth.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PDP-REST
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 package org.openecomp.policy.pdp.rest.config;
21
22 import java.io.FileInputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Base64;
31 import java.util.HashMap;
32 import java.util.Map;
33 import java.util.Properties;
34 import java.util.StringTokenizer;
35
36 import org.openecomp.policy.api.PolicyEngineException;
37 import org.openecomp.policy.common.logging.eelf.MessageCodes;
38 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
39 import org.openecomp.policy.rest.XACMLRestProperties;
40 import org.openecomp.policy.utils.AAFPolicyClient;
41 import org.openecomp.policy.utils.AAFPolicyException;
42 import org.openecomp.policy.utils.PolicyUtils;
43 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
44
45 import com.att.research.xacml.util.XACMLProperties;
46
47 public class PDPApiAuth {
48          private static String environment = null;
49             private static Path clientPath = null;
50             private static Map<String,ArrayList<String>> clientMap = null;
51             private static Long oldModified = null;
52             private static AAFPolicyClient aafClient = null;
53             
54             /*
55              * Set Property by reading the properties File.
56              */
57             public static void setProperty() {
58                 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
59                 String clientFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PEP_IDFILE);
60                 if(clientFile!=null){
61                     clientPath = Paths.get(clientFile);
62                 }
63                 try {
64                     aafClient = AAFPolicyClient.getInstance(XACMLProperties.getProperties());
65                 } catch (AAFPolicyException | IOException e) {
66                     PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AAF Client Not instantiated properly.");
67                 }
68             }
69             
70             /*
71              * Return Environment value of the PDP servlet. 
72              */
73             public static String getEnvironment() {
74                 if(environment==null){
75                     setProperty();
76                 }
77                 return environment;
78             }
79
80             /*
81              * Security check for authentication and authorizations. 
82              */
83             public static boolean checkPermissions(String clientEncoding, String requestID,
84                     String resource) {
85                 try{
86                     String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding);
87                     if(userNamePass==null){
88                         String usernameAndPassword = null;
89                         byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding);
90                         usernameAndPassword = new String(decodedBytes, "UTF-8");
91                         StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
92                         String username = tokenizer.nextToken();
93                         String password = tokenizer.nextToken();
94                         userNamePass=  new String[]{username, password};
95                     }
96                     PolicyLogger.info("User " + userNamePass[0] + " is Accessing Policy Engine API.");
97                     Boolean result = false;
98                     // Check Backward Compatibility. 
99                     try{
100                         result = clientAuth(userNamePass);
101                     }catch(Exception e){
102                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, e, "");
103                     }
104                     if(!result){
105                         try{
106                                 String aafPolicyNameSpace = XACMLProperties.getProperty("policy.aaf.namespace");
107                                 String aafResource = XACMLProperties.getProperty("policy.aaf.resource");
108                             if(!userNamePass[0].contains("@") && aafPolicyNameSpace!= null){
109                                 userNamePass[0] = userNamePass[0] + "@" + aafPolicyNameSpace;
110                             }
111                             if(aafResource != null){
112                                  resource = aafResource + resource;
113                             }
114                             PolicyLogger.info("Contacting AAF in : "  + environment);
115                             result = aafClient.checkAuthPerm(userNamePass[0], userNamePass[1], resource, environment, ".*");
116                         }catch (NullPointerException e){
117                             result = false;
118                         }
119                     }
120                     return result;
121                 }catch(Exception e){
122                     PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, e, "");
123                     return false;
124                 }
125             }
126
127             private static Boolean clientAuth(String[] userNamePass) throws Exception{
128                 if(clientPath==null){
129                     setProperty();
130                 }
131                 if (Files.notExists(clientPath)) {
132                     return false;
133                 }else if(clientPath.toString().endsWith(".properties")) {
134                     try {
135                         readProps(clientPath);
136                         if (clientMap.containsKey(userNamePass[0]) && clientMap.get(userNamePass[0]).get(0).equals(userNamePass[1])) {
137                             return true;
138                         }
139                     }catch(PolicyEngineException e){
140                         return false;
141                     }
142                 }
143                 return false;
144             }
145             
146             private static Map<String, ArrayList<String>> readProps(Path clientPath) throws PolicyEngineException{
147                 if(oldModified!=null){
148                     Long newModified = clientPath.toFile().lastModified();
149                     if (newModified == oldModified) {
150                         return clientMap;
151                     }
152                 }
153                 InputStream in;
154                 Properties clientProp = new Properties();
155                 try {
156                     in = new FileInputStream(clientPath.toFile());
157                     clientProp.load(in);
158                 } catch (IOException e) {
159                     PolicyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
160                     throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e);
161                 }
162                 // Read the Properties and Load the Clients and their scopes.
163                 clientMap = new HashMap<>();
164                 // 
165                 for (Object propKey : clientProp.keySet()) {
166                     String clientID = (String)propKey; 
167                     String clientValue = clientProp.getProperty(clientID);
168                     if (clientValue != null) {
169                         if (clientValue.contains(",")) {
170                             ArrayList<String> clientValues = new ArrayList<String>(Arrays.asList(clientValue.split("\\s*,\\s*")));
171                             if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){
172                                 clientMap.put(clientID, clientValues);
173                             }
174                         } 
175                     }
176                 }
177                 if (clientMap.isEmpty()) {
178                     PolicyLogger.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!");
179                     throw new PolicyEngineException("Empty Client file");
180                 }
181                 oldModified = clientPath.toFile().lastModified();
182                 return clientMap;
183             }
184 }