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