2 * ============LICENSE_START=======================================================
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
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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.onap.aai.auth;
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.fasterxml.jackson.databind.ObjectMapper;
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;
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;
45 * Authentication and authorization by user and role.
48 public class AAIMicroServiceAuthCore {
50 private static Logger applicationLogger = LoggerFactory.getInstance().getLogger(AAIMicroServiceAuthCore.class);
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");
57 private static String appConfigAuthDir = APPCONFIG_DIR + FILESEP + "auth";
58 private static String defaultAuthFileName = appConfigAuthDir + FILESEP + "auth_policy.json";
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;
66 public enum HTTP_METHODS {
75 private AAIMicroServiceAuthCore() {}
77 public static String getDefaultAuthFileName() {
78 return defaultAuthFileName;
81 public static void setDefaultAuthFileName(String defaultAuthFileName) {
82 AAIMicroServiceAuthCore.defaultAuthFileName = defaultAuthFileName;
85 public static synchronized void init(String authPolicyFile) throws AAIAuthException {
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());
94 if (policyAuthFileName == null) {
95 throw new AAIAuthException("Auth policy file could not be found");
97 AAIMicroServiceAuthCore.reloadUsers();
99 TimerTask task = new FileWatcher(new File(policyAuthFileName)) {
101 protected void onChange(File file) {
102 // here we implement the onChange
103 applicationLogger.debug("File " + file.getName() + " has been changed!");
105 AAIMicroServiceAuthCore.reloadUsers();
106 } catch (AAIAuthException e) {
107 applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
109 applicationLogger.debug("File " + file.getName() + " has been reloaded!");
116 long period = TimeUnit.SECONDS.toMillis(1);
117 timer.schedule(task, new Date(), period);
118 applicationLogger.debug("Config Watcher Interval = " + period);
122 public static void cleanup() {
126 public static String getConfigFile(String authPolicyFile) throws IOException {
127 File authFile = new File(authPolicyFile);
128 if (authFile.exists()) {
129 return authFile.getCanonicalPath();
131 authFile = new File(appConfigAuthDir + FILESEP + authPolicyFile);
132 if (authFile.exists()) {
133 return authFile.getCanonicalPath();
135 if (defaultAuthFileName != null) {
136 authFile = new File(defaultAuthFileName);
137 if (authFile.exists()) {
138 return defaultAuthFileName;
144 public static synchronized void reloadUsers() throws AAIAuthException {
145 users = new HashMap<>();
147 ObjectMapper mapper = new ObjectMapper();
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);
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);
165 usersInitialized = true;
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();
176 String func = methodName + ":" + function;
177 applicationLogger.debug("Installing function " + func + " on role " + roleName);
178 r.addAllowedFunction(func);
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);
191 private static void assignRoleToUsers(JsonNode usersNode, String roleName, AAIAuthRole r) {
192 for (JsonNode userNode : usersNode) {
193 String name = userNode.path("username").asText().toLowerCase();
195 if (users.containsKey(name)) {
196 user = users.get(name);
198 user = new AAIAuthUser();
200 applicationLogger.debug("Assigning " + roleName + " to user " + name);
202 user.addRole(roleName, r);
203 users.put(name, user);
207 public static class AAIAuthUser {
208 private String username;
209 private HashMap<String, AAIAuthRole> roles;
211 public AAIAuthUser() {
212 this.roles = new HashMap<>();
215 public String getUser() {
216 return this.username;
219 public Map<String, AAIAuthRole> getRoles() {
223 public void addRole(String roleName, AAIAuthRole r) {
224 this.roles.put(roleName, r);
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)) {
237 public void setUser(String myuser) {
238 this.username = myuser;
243 public static class AAIAuthRole {
245 private List<String> allowedFunctions;
247 public AAIAuthRole() {
248 this.allowedFunctions = new ArrayList<>();
251 public void addAllowedFunction(String func) {
252 this.allowedFunctions.add(func);
255 public void delAllowedFunction(String delFunc) {
256 if (this.allowedFunctions.contains(delFunc)) {
257 this.allowedFunctions.remove(delFunc);
261 public boolean hasAllowedFunction(String afunc) {
262 return this.allowedFunctions.contains(afunc) ? true : false;
266 public static boolean authorize(String username, String authFunction) throws AAIAuthException {
267 if (!usersInitialized || users == null) {
268 throw new AAIAuthException("Auth module not initialized");
270 if (users.containsKey(username)) {
271 if (users.get(username).checkAllowed(authFunction)) {
272 logAuthenticationResult(username, authFunction, "AUTH ACCEPTED");
275 logAuthenticationResult(username, authFunction, "AUTH FAILED");
279 logAuthenticationResult(username, authFunction, "User not found");
284 private static void logAuthenticationResult(String username, String authFunction, String result) {
285 applicationLogger.debug(result + ": " + username + " on function " + authFunction);