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