2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.auth;
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
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;
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;
41 /** Authentication and authorization by user and role. */
42 public class AAIMicroServiceAuthCore {
44 private static LogHelper applicationLogger = LogHelper.INSTANCE;
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("APP_HOME") + FILESEP + "appconfig" : System.getProperty("CONFIG_HOME");
51 private static String appConfigAuthDir = APPCONFIG_DIR + FILESEP + "auth";
52 private static String defaultAuthFileName = appConfigAuthDir + FILESEP + "auth_policy.json";
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;
60 public enum HTTP_METHODS {
69 private AAIMicroServiceAuthCore() {}
71 public static String getDefaultAuthFileName() {
72 return defaultAuthFileName;
75 public static void setDefaultAuthFileName(String defaultAuthFileName) {
76 AAIMicroServiceAuthCore.defaultAuthFileName = defaultAuthFileName;
79 public static synchronized void init(String authPolicyFile) throws AAIAuthException {
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());
87 if (policyAuthFileName == null) {
88 throw new AAIAuthException("Auth policy file could not be found" + System.getProperty("CONFIG_HOME") + APPCONFIG_DIR);
90 AAIMicroServiceAuthCore.reloadUsers();
92 TimerTask task = new FileWatcher(new File(policyAuthFileName)) {
94 protected void onChange(File file) {
95 // here we implement the onChange
96 applicationLogger.debug("File " + file.getName() + " has been changed!");
98 AAIMicroServiceAuthCore.reloadUsers();
99 } catch (AAIAuthException e) {
100 applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
102 applicationLogger.debug("File " + file.getName() + " has been reloaded!");
109 long period = TimeUnit.SECONDS.toMillis(1);
110 timer.schedule(task, new Date(), period);
111 applicationLogger.debug("Config Watcher Interval = " + period);
115 public static void cleanup() {
119 public static String getConfigFile(String authPolicyFile) throws IOException {
120 File authFile = new File(authPolicyFile);
121 if (authFile.exists()) {
122 return authFile.getCanonicalPath();
124 authFile = new File(appConfigAuthDir + FILESEP + authPolicyFile);
125 if (authFile.exists()) {
126 return authFile.getCanonicalPath();
128 if (defaultAuthFileName != null) {
129 authFile = new File(defaultAuthFileName);
130 if (authFile.exists()) {
131 return defaultAuthFileName;
137 public static synchronized void reloadUsers() throws AAIAuthException {
138 users = new HashMap<>();
140 ObjectMapper mapper = new ObjectMapper();
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);
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);
158 usersInitialized = true;
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();
169 String func = methodName + ":" + function;
170 applicationLogger.debug("Installing function " + func + " on role " + roleName);
171 r.addAllowedFunction(func);
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);
184 private static void assignRoleToUsers(JsonNode usersNode, String roleName, AAIAuthRole r) {
185 for (JsonNode userNode : usersNode) {
186 String name = userNode.path("username").asText().toLowerCase();
188 if (users.containsKey(name)) {
189 user = users.get(name);
191 user = new AAIAuthUser();
193 applicationLogger.debug("Assigning " + roleName + " to user " + name);
195 user.addRole(roleName, r);
196 users.put(name, user);
200 public static class AAIAuthUser {
201 private String username;
202 private HashMap<String, AAIAuthRole> roles;
204 public AAIAuthUser() {
205 this.roles = new HashMap<>();
208 public String getUser() {
209 return this.username;
212 public Map<String, AAIAuthRole> getRoles() {
216 public void addRole(String roleName, AAIAuthRole r) {
217 this.roles.put(roleName, r);
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)) {
230 public void setUser(String myuser) {
231 this.username = myuser;
235 public static class AAIAuthRole {
237 private List<String> allowedFunctions;
239 public AAIAuthRole() {
240 this.allowedFunctions = new ArrayList<>();
243 public void addAllowedFunction(String func) {
244 this.allowedFunctions.add(func);
247 public void delAllowedFunction(String delFunc) {
248 if (this.allowedFunctions.contains(delFunc)) {
249 this.allowedFunctions.remove(delFunc);
253 public boolean hasAllowedFunction(String afunc) {
254 return this.allowedFunctions.contains(afunc) ? true : false;
258 public static boolean authorize(String username, String authFunction) throws AAIAuthException {
259 if (!usersInitialized || users == null) {
260 throw new AAIAuthException("Auth module not initialized");
262 if (users.containsKey(username)) {
263 if (users.get(username).checkAllowed(authFunction)) {
264 logAuthenticationResult(username, authFunction, "AUTH ACCEPTED");
267 logAuthenticationResult(username, authFunction, "AUTH FAILED");
271 logAuthenticationResult(username, authFunction, "User not found");
276 private static void logAuthenticationResult(String username, String authFunction, String result) {
277 applicationLogger.debug(result + ": " + username + " on function " + authFunction);