Refactor auth classes and add tests
[aai/babel.git] / src / main / java / org / onap / aai / auth / AAIMicroServiceAuthCore.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Copyright (c) 2017-2019 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
22 package org.onap.aai.auth;
23
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.JsonNode;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import java.io.File;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.ArrayList;
33 import java.util.Date;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Optional;
38 import java.util.Timer;
39 import java.util.TimerTask;
40 import java.util.concurrent.TimeUnit;
41 import org.onap.aai.babel.logging.ApplicationMsgs;
42 import org.onap.aai.babel.logging.LogHelper;
43
44 /** Authentication and authorization by user and role. */
45 public class AAIMicroServiceAuthCore {
46
47     private static LogHelper applicationLogger = LogHelper.INSTANCE;
48
49     /**
50      * The default policy file is expected to be located in either one of
51      * <ul>
52      * <li><code>$CONFIG_HOME/auth_policy.json</code></li>
53      * <li><code>$CONFIG_HOME/auth/auth_policy.json</code></li>
54      * <p>
55      * Note that if <code>CONFIG_HOME</code> is not set then assume it has a value of <code>$APP_HOME/appconfig</code>
56      */
57     private static String defaultAuthFileName = "auth_policy.json";
58
59     private static boolean usersInitialized = false;
60     private static HashMap<String, AAIAuthUser> users;
61     private static boolean timerSet = false;
62     private static Timer timer = null;
63     private static String policyAuthFileName;
64
65     public enum HTTP_METHODS {
66         GET, PUT, DELETE, HEAD, 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
89         if (policyAuthFileName == null) {
90             throw new AAIAuthException("Auth policy file could not be found");
91         }
92         AAIMicroServiceAuthCore.reloadUsers();
93
94         TimerTask task = new FileWatcher(new File(policyAuthFileName)) {
95             @Override
96             protected void onChange(File file) {
97                 // here we implement the onChange
98                 applicationLogger.debug("File " + file.getName() + " has been changed!");
99                 try {
100                     AAIMicroServiceAuthCore.reloadUsers();
101                 } catch (AAIAuthException e) {
102                     applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
103                 }
104                 applicationLogger.debug("File " + file.getName() + " has been reloaded!");
105             }
106         };
107
108         if (!timerSet) {
109             timerSet = true;
110             timer = new Timer();
111             long period = TimeUnit.SECONDS.toMillis(1);
112             timer.schedule(task, new Date(), period);
113             applicationLogger.debug("Config Watcher Interval = " + period);
114         }
115     }
116
117     public static void cleanup() {
118         timer.cancel();
119     }
120
121     public static String getConfigFile(String authPolicyFile) throws IOException {
122         return locateConfigFile(authPolicyFile).orElse(locateConfigFile(defaultAuthFileName).orElse(null));
123     }
124
125     /**
126      * Locate the auth policy file by its name or path.
127      * <ul>
128      * <li>First try to use the absolute path to the file (if provided), or instead locate the path relative to the
129      * current (or user) dir.</li>
130      * <li>If this fails, try resolving the path relative to the configuration home location (either
131      * <code>$CONFIG_HOME</code> or <code>$APP_HOME/appconfig</code>).</li>
132      * <li>If this fails try resolving relative to the <code>auth</code> folder under configuration home.</li>
133      * 
134      * @param authPolicyFile
135      *            filename or path
136      * @return the Optional canonical path to the located policy file
137      * @throws IOException
138      *             if the construction of the canonical pathname requires filesystem queries which cause I/O error(s)
139      */
140     private static Optional<String> locateConfigFile(String authPolicyFile) throws IOException {
141         if (authPolicyFile != null) {
142             List<Path> paths = new ArrayList<>();
143             paths.add(Paths.get("."));
144
145             String configHome = System.getProperty("CONFIG_HOME");
146             if (configHome == null) {
147                 configHome = System.getProperty("APP_HOME") + "/appconfig";
148             }
149
150             paths.add(Paths.get(configHome));
151             paths.add(Paths.get(configHome).resolve("auth"));
152
153             for (Path path : paths) {
154                 File authFile = path.resolve(authPolicyFile).toFile();
155                 if (authFile.exists()) {
156                     return Optional.of(authFile.getCanonicalPath());
157                 }
158             }
159         }
160
161         return Optional.empty();
162     }
163
164     public static synchronized void reloadUsers() throws AAIAuthException {
165         users = new HashMap<>();
166
167         ObjectMapper mapper = new ObjectMapper();
168         try {
169             applicationLogger.debug("Reading from " + policyAuthFileName);
170             JsonNode rootNode = mapper.readTree(new File(policyAuthFileName));
171             for (JsonNode roleNode : rootNode.path("roles")) {
172                 String roleName = roleNode.path("name").asText();
173                 AAIAuthRole r = new AAIAuthRole();
174                 installFunctionOnRole(roleNode.path("functions"), roleName, r);
175                 assignRoleToUsers(roleNode.path("users"), roleName, r);
176             }
177         } catch (FileNotFoundException e) {
178             throw new AAIAuthException("Auth policy file could not be found", e);
179         } catch (JsonProcessingException e) {
180             throw new AAIAuthException("Error processing Auth policy file ", e);
181         } catch (IOException e) {
182             throw new AAIAuthException("Error reading Auth policy file", e);
183         }
184
185         usersInitialized = true;
186     }
187
188     private static void installFunctionOnRole(JsonNode functionsNode, String roleName, AAIAuthRole r) {
189         for (JsonNode functionNode : functionsNode) {
190             String function = functionNode.path("name").asText();
191             JsonNode methodsNode = functionNode.path("methods");
192             boolean hasMethods = false;
193             for (JsonNode method_node : methodsNode) {
194                 String methodName = method_node.path("name").asText();
195                 hasMethods = true;
196                 String func = methodName + ":" + function;
197                 applicationLogger.debug("Installing function " + func + " on role " + roleName);
198                 r.addAllowedFunction(func);
199             }
200
201             if (!hasMethods) {
202                 for (HTTP_METHODS meth : HTTP_METHODS.values()) {
203                     String func = meth.toString() + ":" + function;
204                     applicationLogger.debug("Installing (all methods) " + func + " on role " + roleName);
205                     r.addAllowedFunction(func);
206                 }
207             }
208         }
209     }
210
211     private static void assignRoleToUsers(JsonNode usersNode, String roleName, AAIAuthRole r) {
212         for (JsonNode userNode : usersNode) {
213             String name = userNode.path("username").asText().toLowerCase();
214             AAIAuthUser user;
215             if (users.containsKey(name)) {
216                 user = users.get(name);
217             } else {
218                 user = new AAIAuthUser();
219             }
220             applicationLogger.debug("Assigning " + roleName + " to user " + name);
221             user.addRole(roleName, r);
222             users.put(name, user);
223         }
224     }
225
226     public static class AAIAuthUser {
227         private HashMap<String, AAIAuthRole> roles;
228
229         public AAIAuthUser() {
230             this.roles = new HashMap<>();
231         }
232
233         public void addRole(String roleName, AAIAuthRole r) {
234             this.roles.put(roleName, r);
235         }
236
237         public boolean checkAllowed(String checkFunc) {
238             for (Entry<String, AAIAuthRole> role_entry : roles.entrySet()) {
239                 AAIAuthRole role = role_entry.getValue();
240                 if (role.hasAllowedFunction(checkFunc)) {
241                     return true;
242                 }
243             }
244             return false;
245         }
246     }
247
248     public static class AAIAuthRole {
249
250         private List<String> allowedFunctions;
251
252         public AAIAuthRole() {
253             this.allowedFunctions = new ArrayList<>();
254         }
255
256         public void addAllowedFunction(String func) {
257             this.allowedFunctions.add(func);
258         }
259
260         public boolean hasAllowedFunction(String afunc) {
261             return this.allowedFunctions.contains(afunc);
262         }
263     }
264
265     public static boolean authorize(String username, String authFunction) throws AAIAuthException {
266         if (!usersInitialized || users == null) {
267             throw new AAIAuthException("Auth module not initialized");
268         }
269         if (users.containsKey(username)) {
270             if (users.get(username).checkAllowed(authFunction)) {
271                 logAuthenticationResult(username, authFunction, "AUTH ACCEPTED");
272                 return true;
273             } else {
274                 logAuthenticationResult(username, authFunction, "AUTH FAILED");
275                 return false;
276             }
277         } else {
278             logAuthenticationResult(username, authFunction, "User not found");
279             return false;
280         }
281     }
282
283     private static void logAuthenticationResult(String username, String authFunction, String result) {
284         applicationLogger.debug(result + ": " + username + " on function " + authFunction);
285     }
286 }