4ba9b6cadf2da4f57e882fc4a5b41b876c62ba9a
[aai/babel.git] / src / main / java / org / onap / aai / auth / AAIMicroServiceAuthCore.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.auth;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import java.io.File;
27 import java.io.FileNotFoundException;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.Timer;
36 import java.util.TimerTask;
37 import java.util.concurrent.TimeUnit;
38 import org.onap.aai.babel.logging.ApplicationMsgs;
39 import org.onap.aai.babel.logging.LogHelper;
40
41 /** Authentication and authorization by user and role. */
42 public class AAIMicroServiceAuthCore {
43
44     private static LogHelper applicationLogger = LogHelper.INSTANCE;
45
46     public static final String CONFIG_HOME = "CONFIG_HOME";
47     public static final String FILESEP =
48             (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
49     public static final String APPCONFIG_DIR = (System.getProperty(CONFIG_HOME) == null)
50             ? System.getProperty("APP_HOME") + FILESEP + "appconfig" : System.getProperty(CONFIG_HOME);
51
52     private static String appConfigAuthDir = APPCONFIG_DIR + FILESEP + "auth";
53     private static String defaultAuthFileName = appConfigAuthDir + FILESEP + "auth_policy.json";
54
55     private static boolean usersInitialized = false;
56     private static HashMap<String, AAIAuthUser> users;
57     private static boolean timerSet = false;
58     private static Timer timer = null;
59     private static String policyAuthFileName;
60
61     public enum HTTP_METHODS {
62         GET,
63         PUT,
64         DELETE,
65         HEAD,
66         POST
67     }
68
69     // Don't instantiate
70     private AAIMicroServiceAuthCore() {}
71
72     public static String getDefaultAuthFileName() {
73         return defaultAuthFileName;
74     }
75
76     public static void setDefaultAuthFileName(String defaultAuthFileName) {
77         AAIMicroServiceAuthCore.defaultAuthFileName = defaultAuthFileName;
78     }
79
80     public static synchronized void init(String authPolicyFile) throws AAIAuthException {
81         try {
82             policyAuthFileName = AAIMicroServiceAuthCore.getConfigFile(authPolicyFile);
83         } catch (IOException e) {
84             applicationLogger.debug("Exception while retrieving policy file.");
85             applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
86             throw new AAIAuthException(e.getMessage());
87         }
88         if (policyAuthFileName == null) {
89             throw new AAIAuthException("Auth policy file could not be found" + System.getProperty(CONFIG_HOME) + APPCONFIG_DIR);
90         }
91         AAIMicroServiceAuthCore.reloadUsers();
92
93         TimerTask task = new FileWatcher(new File(policyAuthFileName)) {
94             @Override
95             protected void onChange(File file) {
96                 // here we implement the onChange
97                 applicationLogger.debug("File " + file.getName() + " has been changed!");
98                 try {
99                     AAIMicroServiceAuthCore.reloadUsers();
100                 } catch (AAIAuthException e) {
101                     applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
102                 }
103                 applicationLogger.debug("File " + file.getName() + " has been reloaded!");
104             }
105         };
106
107         if (!timerSet) {
108             timerSet = true;
109             timer = new Timer();
110             long period = TimeUnit.SECONDS.toMillis(1);
111             timer.schedule(task, new Date(), period);
112             applicationLogger.debug("Config Watcher Interval = " + period);
113         }
114     }
115
116     public static void cleanup() {
117         timer.cancel();
118     }
119
120     public static String getConfigFile(String authPolicyFile) throws IOException {
121         File authFile = new File(authPolicyFile);
122         if (authFile.exists()) {
123             return authFile.getCanonicalPath();
124         }
125         authFile = new File(appConfigAuthDir + FILESEP + authPolicyFile);
126         if (authFile.exists()) {
127             return authFile.getCanonicalPath();
128         }
129         if (defaultAuthFileName != null) {
130             authFile = new File(defaultAuthFileName);
131             if (authFile.exists()) {
132                 return defaultAuthFileName;
133             }
134         }
135         return null;
136     }
137
138     public static synchronized void reloadUsers() throws AAIAuthException {
139         users = new HashMap<>();
140
141         ObjectMapper mapper = new ObjectMapper();
142         try {
143             applicationLogger.debug("Reading from " + policyAuthFileName);
144             JsonNode rootNode = mapper.readTree(new File(policyAuthFileName));
145             for (JsonNode roleNode : rootNode.path("roles")) {
146                 String roleName = roleNode.path("name").asText();
147                 AAIAuthRole r = new AAIAuthRole();
148                 installFunctionOnRole(roleNode.path("functions"), roleName, r);
149                 assignRoleToUsers(roleNode.path("users"), roleName, r);
150             }
151         } catch (FileNotFoundException e) {
152             throw new AAIAuthException("Auth policy file could not be found", e);
153         } catch (JsonProcessingException e) {
154             throw new AAIAuthException("Error processing Auth policy file ", e);
155         } catch (IOException e) {
156             throw new AAIAuthException("Error reading Auth policy file", e);
157         }
158
159         usersInitialized = true;
160     }
161
162     private static void installFunctionOnRole(JsonNode functionsNode, String roleName, AAIAuthRole r) {
163         for (JsonNode functionNode : functionsNode) {
164             String function = functionNode.path("name").asText();
165             JsonNode methodsNode = functionNode.path("methods");
166             boolean hasMethods = false;
167             for (JsonNode method_node : methodsNode) {
168                 String methodName = method_node.path("name").asText();
169                 hasMethods = true;
170                 String func = methodName + ":" + function;
171                 applicationLogger.debug("Installing function " + func + " on role " + roleName);
172                 r.addAllowedFunction(func);
173             }
174
175             if (!hasMethods) {
176                 for (HTTP_METHODS meth : HTTP_METHODS.values()) {
177                     String func = meth.toString() + ":" + function;
178                     applicationLogger.debug("Installing (all methods) " + func + " on role " + roleName);
179                     r.addAllowedFunction(func);
180                 }
181             }
182         }
183     }
184
185     private static void assignRoleToUsers(JsonNode usersNode, String roleName, AAIAuthRole r) {
186         for (JsonNode userNode : usersNode) {
187             String name = userNode.path("username").asText().toLowerCase();
188             AAIAuthUser user;
189             if (users.containsKey(name)) {
190                 user = users.get(name);
191             } else {
192                 user = new AAIAuthUser();
193             }
194             applicationLogger.debug("Assigning " + roleName + " to user " + name);
195             user.setUser(name);
196             user.addRole(roleName, r);
197             users.put(name, user);
198         }
199     }
200
201     public static class AAIAuthUser {
202         private String username;
203         private HashMap<String, AAIAuthRole> roles;
204
205         public AAIAuthUser() {
206             this.roles = new HashMap<>();
207         }
208
209         public String getUser() {
210             return this.username;
211         }
212
213         public Map<String, AAIAuthRole> getRoles() {
214             return this.roles;
215         }
216
217         public void addRole(String roleName, AAIAuthRole r) {
218             this.roles.put(roleName, r);
219         }
220
221         public boolean checkAllowed(String checkFunc) {
222             for (Entry<String, AAIAuthRole> role_entry : roles.entrySet()) {
223                 AAIAuthRole role = role_entry.getValue();
224                 if (role.hasAllowedFunction(checkFunc)) {
225                     return true;
226                 }
227             }
228             return false;
229         }
230
231         public void setUser(String myuser) {
232             this.username = myuser;
233         }
234     }
235
236     public static class AAIAuthRole {
237
238         private List<String> allowedFunctions;
239
240         public AAIAuthRole() {
241             this.allowedFunctions = new ArrayList<>();
242         }
243
244         public void addAllowedFunction(String func) {
245             this.allowedFunctions.add(func);
246         }
247
248         public void delAllowedFunction(String delFunc) {
249             if (this.allowedFunctions.contains(delFunc)) {
250                 this.allowedFunctions.remove(delFunc);
251             }
252         }
253
254         public boolean hasAllowedFunction(String afunc) {
255             return this.allowedFunctions.contains(afunc) ? true : false;
256         }
257     }
258
259     public static boolean authorize(String username, String authFunction) throws AAIAuthException {
260         if (!usersInitialized || users == null) {
261             throw new AAIAuthException("Auth module not initialized");
262         }
263         if (users.containsKey(username)) {
264             if (users.get(username).checkAllowed(authFunction)) {
265                 logAuthenticationResult(username, authFunction, "AUTH ACCEPTED");
266                 return true;
267             } else {
268                 logAuthenticationResult(username, authFunction, "AUTH FAILED");
269                 return false;
270             }
271         } else {
272             logAuthenticationResult(username, authFunction, "User not found");
273             return false;
274         }
275     }
276
277     private static void logAuthenticationResult(String username, String authFunction, String result) {
278         applicationLogger.debug(result + ": " + username + " on function " + authFunction);
279     }
280 }