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 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);
52 private static String appConfigAuthDir = APPCONFIG_DIR + FILESEP + "auth";
53 private static String defaultAuthFileName = appConfigAuthDir + FILESEP + "auth_policy.json";
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;
61 public enum HTTP_METHODS {
70 private AAIMicroServiceAuthCore() {}
72 public static String getDefaultAuthFileName() {
73 return defaultAuthFileName;
76 public static void setDefaultAuthFileName(String defaultAuthFileName) {
77 AAIMicroServiceAuthCore.defaultAuthFileName = defaultAuthFileName;
80 public static synchronized void init(String authPolicyFile) throws AAIAuthException {
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());
88 if (policyAuthFileName == null) {
89 throw new AAIAuthException("Auth policy file could not be found" + System.getProperty(CONFIG_HOME) + APPCONFIG_DIR);
91 AAIMicroServiceAuthCore.reloadUsers();
93 TimerTask task = new FileWatcher(new File(policyAuthFileName)) {
95 protected void onChange(File file) {
96 // here we implement the onChange
97 applicationLogger.debug("File " + file.getName() + " has been changed!");
99 AAIMicroServiceAuthCore.reloadUsers();
100 } catch (AAIAuthException e) {
101 applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
103 applicationLogger.debug("File " + file.getName() + " has been reloaded!");
110 long period = TimeUnit.SECONDS.toMillis(1);
111 timer.schedule(task, new Date(), period);
112 applicationLogger.debug("Config Watcher Interval = " + period);
116 public static void cleanup() {
120 public static String getConfigFile(String authPolicyFile) throws IOException {
121 File authFile = new File(authPolicyFile);
122 if (authFile.exists()) {
123 return authFile.getCanonicalPath();
125 authFile = new File(appConfigAuthDir + FILESEP + authPolicyFile);
126 if (authFile.exists()) {
127 return authFile.getCanonicalPath();
129 if (defaultAuthFileName != null) {
130 authFile = new File(defaultAuthFileName);
131 if (authFile.exists()) {
132 return defaultAuthFileName;
138 public static synchronized void reloadUsers() throws AAIAuthException {
139 users = new HashMap<>();
141 ObjectMapper mapper = new ObjectMapper();
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);
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);
159 usersInitialized = true;
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();
170 String func = methodName + ":" + function;
171 applicationLogger.debug("Installing function " + func + " on role " + roleName);
172 r.addAllowedFunction(func);
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);
185 private static void assignRoleToUsers(JsonNode usersNode, String roleName, AAIAuthRole r) {
186 for (JsonNode userNode : usersNode) {
187 String name = userNode.path("username").asText().toLowerCase();
189 if (users.containsKey(name)) {
190 user = users.get(name);
192 user = new AAIAuthUser();
194 applicationLogger.debug("Assigning " + roleName + " to user " + name);
196 user.addRole(roleName, r);
197 users.put(name, user);
201 public static class AAIAuthUser {
202 private String username;
203 private HashMap<String, AAIAuthRole> roles;
205 public AAIAuthUser() {
206 this.roles = new HashMap<>();
209 public String getUser() {
210 return this.username;
213 public Map<String, AAIAuthRole> getRoles() {
217 public void addRole(String roleName, AAIAuthRole r) {
218 this.roles.put(roleName, r);
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)) {
231 public void setUser(String myuser) {
232 this.username = myuser;
236 public static class AAIAuthRole {
238 private List<String> allowedFunctions;
240 public AAIAuthRole() {
241 this.allowedFunctions = new ArrayList<>();
244 public void addAllowedFunction(String func) {
245 this.allowedFunctions.add(func);
248 public void delAllowedFunction(String delFunc) {
249 if (this.allowedFunctions.contains(delFunc)) {
250 this.allowedFunctions.remove(delFunc);
254 public boolean hasAllowedFunction(String afunc) {
255 return this.allowedFunctions.contains(afunc) ? true : false;
259 public static boolean authorize(String username, String authFunction) throws AAIAuthException {
260 if (!usersInitialized || users == null) {
261 throw new AAIAuthException("Auth module not initialized");
263 if (users.containsKey(username)) {
264 if (users.get(username).checkAllowed(authFunction)) {
265 logAuthenticationResult(username, authFunction, "AUTH ACCEPTED");
268 logAuthenticationResult(username, authFunction, "AUTH FAILED");
272 logAuthenticationResult(username, authFunction, "User not found");
277 private static void logAuthenticationResult(String username, String authFunction, String result) {
278 applicationLogger.debug(result + ": " + username + " on function " + authFunction);