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