2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Copyright (c) 2017-2019 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=========================================================
22 package org.onap.aai.auth;
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.JsonNode;
26 import com.fasterxml.jackson.databind.ObjectMapper;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.ArrayList;
33 import java.util.Date;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Optional;
38 import java.util.Timer;
39 import java.util.TimerTask;
40 import java.util.concurrent.TimeUnit;
41 import org.onap.aai.babel.logging.ApplicationMsgs;
42 import org.onap.aai.babel.logging.LogHelper;
44 /** Authentication and authorization by user and role. */
45 public class AAIMicroServiceAuthCore {
47 private static LogHelper applicationLogger = LogHelper.INSTANCE;
50 * The default policy file is expected to be located in either one of
52 * <li><code>$CONFIG_HOME/auth_policy.json</code></li>
53 * <li><code>$CONFIG_HOME/auth/auth_policy.json</code></li>
55 * Note that if <code>CONFIG_HOME</code> is not set then assume it has a value of <code>$APP_HOME/appconfig</code>
57 private static String defaultAuthFileName = "auth_policy.json";
59 private static boolean usersInitialized = false;
60 private static HashMap<String, AAIAuthUser> users;
61 private static boolean timerSet = false;
62 private static Timer timer = null;
63 private static String policyAuthFileName;
65 public enum HTTP_METHODS {
66 GET, PUT, DELETE, HEAD, POST
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());
89 if (policyAuthFileName == null) {
90 throw new AAIAuthException("Auth policy file could not be found");
92 AAIMicroServiceAuthCore.reloadUsers();
94 TimerTask task = new FileWatcher(new File(policyAuthFileName)) {
96 protected void onChange(File file) {
97 // here we implement the onChange
98 applicationLogger.debug("File " + file.getName() + " has been changed!");
100 AAIMicroServiceAuthCore.reloadUsers();
101 } catch (AAIAuthException e) {
102 applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
104 applicationLogger.debug("File " + file.getName() + " has been reloaded!");
111 long period = TimeUnit.SECONDS.toMillis(1);
112 timer.schedule(task, new Date(), period);
113 applicationLogger.debug("Config Watcher Interval = " + period);
117 public static void cleanup() {
121 public static String getConfigFile(String authPolicyFile) throws IOException {
122 return locateConfigFile(authPolicyFile).orElse(locateConfigFile(defaultAuthFileName).orElse(null));
126 * Locate the auth policy file by its name or path.
128 * <li>First try to use the absolute path to the file (if provided), or instead locate the path relative to the
129 * current (or user) dir.</li>
130 * <li>If this fails, try resolving the path relative to the configuration home location (either
131 * <code>$CONFIG_HOME</code> or <code>$APP_HOME/appconfig</code>).</li>
132 * <li>If this fails try resolving relative to the <code>auth</code> folder under configuration home.</li>
134 * @param authPolicyFile
136 * @return the Optional canonical path to the located policy file
137 * @throws IOException
138 * if the construction of the canonical pathname requires filesystem queries which cause I/O error(s)
140 private static Optional<String> locateConfigFile(String authPolicyFile) throws IOException {
141 if (authPolicyFile != null) {
142 List<Path> paths = new ArrayList<>();
143 paths.add(Paths.get("."));
145 String configHome = System.getProperty("CONFIG_HOME");
146 if (configHome == null) {
147 configHome = System.getProperty("APP_HOME") + "/appconfig";
150 paths.add(Paths.get(configHome));
151 paths.add(Paths.get(configHome).resolve("auth"));
153 for (Path path : paths) {
154 File authFile = path.resolve(authPolicyFile).toFile();
155 if (authFile.exists()) {
156 return Optional.of(authFile.getCanonicalPath());
161 return Optional.empty();
164 public static synchronized void reloadUsers() throws AAIAuthException {
165 users = new HashMap<>();
167 ObjectMapper mapper = new ObjectMapper();
169 applicationLogger.debug("Reading from " + policyAuthFileName);
170 JsonNode rootNode = mapper.readTree(new File(policyAuthFileName));
171 for (JsonNode roleNode : rootNode.path("roles")) {
172 String roleName = roleNode.path("name").asText();
173 AAIAuthRole r = new AAIAuthRole();
174 installFunctionOnRole(roleNode.path("functions"), roleName, r);
175 assignRoleToUsers(roleNode.path("users"), roleName, r);
177 } catch (FileNotFoundException e) {
178 throw new AAIAuthException("Auth policy file could not be found", e);
179 } catch (JsonProcessingException e) {
180 throw new AAIAuthException("Error processing Auth policy file ", e);
181 } catch (IOException e) {
182 throw new AAIAuthException("Error reading Auth policy file", e);
185 usersInitialized = true;
188 private static void installFunctionOnRole(JsonNode functionsNode, String roleName, AAIAuthRole r) {
189 for (JsonNode functionNode : functionsNode) {
190 String function = functionNode.path("name").asText();
191 JsonNode methodsNode = functionNode.path("methods");
192 boolean hasMethods = false;
193 for (JsonNode method_node : methodsNode) {
194 String methodName = method_node.path("name").asText();
196 String func = methodName + ":" + function;
197 applicationLogger.debug("Installing function " + func + " on role " + roleName);
198 r.addAllowedFunction(func);
202 for (HTTP_METHODS meth : HTTP_METHODS.values()) {
203 String func = meth.toString() + ":" + function;
204 applicationLogger.debug("Installing (all methods) " + func + " on role " + roleName);
205 r.addAllowedFunction(func);
211 private static void assignRoleToUsers(JsonNode usersNode, String roleName, AAIAuthRole r) {
212 for (JsonNode userNode : usersNode) {
213 String name = userNode.path("username").asText().toLowerCase();
215 if (users.containsKey(name)) {
216 user = users.get(name);
218 user = new AAIAuthUser();
220 applicationLogger.debug("Assigning " + roleName + " to user " + name);
221 user.addRole(roleName, r);
222 users.put(name, user);
226 public static class AAIAuthUser {
227 private HashMap<String, AAIAuthRole> roles;
229 public AAIAuthUser() {
230 this.roles = new HashMap<>();
233 public void addRole(String roleName, AAIAuthRole r) {
234 this.roles.put(roleName, r);
237 public boolean checkAllowed(String checkFunc) {
238 for (Entry<String, AAIAuthRole> role_entry : roles.entrySet()) {
239 AAIAuthRole role = role_entry.getValue();
240 if (role.hasAllowedFunction(checkFunc)) {
248 public static class AAIAuthRole {
250 private List<String> allowedFunctions;
252 public AAIAuthRole() {
253 this.allowedFunctions = new ArrayList<>();
256 public void addAllowedFunction(String func) {
257 this.allowedFunctions.add(func);
260 public boolean hasAllowedFunction(String afunc) {
261 return this.allowedFunctions.contains(afunc);
265 public static boolean authorize(String username, String authFunction) throws AAIAuthException {
266 if (!usersInitialized || users == null) {
267 throw new AAIAuthException("Auth module not initialized");
269 if (users.containsKey(username)) {
270 if (users.get(username).checkAllowed(authFunction)) {
271 logAuthenticationResult(username, authFunction, "AUTH ACCEPTED");
274 logAuthenticationResult(username, authFunction, "AUTH FAILED");
278 logAuthenticationResult(username, authFunction, "User not found");
283 private static void logAuthenticationResult(String username, String authFunction, String result) {
284 applicationLogger.debug(result + ": " + username + " on function " + authFunction);