aboutsummaryrefslogtreecommitdiffstats
path: root/aai-aaf-auth/src/main/java/org/onap/aai/aaf/auth/AAIAuthCore.java
blob: f591125c5b428f83d91dc2da56f71f3b5728fd4c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.aai.aaf.auth;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.eclipse.jetty.util.security.Password;
import org.onap.aai.aaf.auth.exceptions.AAIUnrecognizedFunctionException;
import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class AAIAuthCore.
 */
public final class AAIAuthCore {

    private static final Logger LOGGER = LoggerFactory.getLogger(AAIAuthCore.class);

    private static final String ERROR_CODE_AAI_4001 = "AAI_4001";

    private String globalAuthFileName = AAIConstants.AAI_AUTH_CONFIG_FILENAME;

    private final Pattern authPolicyPattern;
    private final Set<String> validFunctions = new HashSet<>();
    private Map<String, AAIUser> users;
    private boolean timerSet = false;
    private Timer timer = null;

    private String basePath;

    /**
     * Instantiates a new AAI auth core.
     */
    public AAIAuthCore(String basePath) {
        this(basePath, AAIConstants.AAI_AUTH_CONFIG_FILENAME);
    }

    public AAIAuthCore(String basePath, String filename) {
        this.basePath = basePath;
        this.globalAuthFileName = filename;
        authPolicyPattern = Pattern.compile("^" + this.basePath + "/v\\d+/([\\w\\-]*)");
        init();
    }

    public AAIAuthCore(String basePath, String filename, String pattern) {
        this.basePath = basePath;
        this.globalAuthFileName = filename;
        authPolicyPattern = Pattern.compile(pattern);
        init();
    }

    /**
     * Inits the.
     */
    private synchronized void init() {

        LOGGER.debug("Initializing Auth Policy Config");

        reloadUsers();

        /*
         * this timer code is setting up a recurring task that checks if the
         * auth config file has been updated and reloads the users if so to get
         * the most up to date info (that update check logic is within
         * FileWatcher)
         *
         * the timing this method uses is coarser than the frequency of requests
         * AI&I gets so we're looking at better ways of doing this (TODO)
         */
        TimerTask task = new FileWatcher(new File(globalAuthFileName)) {
            @Override
            protected void onChange(File file) {
                reloadUsers();
            }
        };

        if (!timerSet) {
            timerSet = true;
            timer = new Timer();

            // repeat the check every second
            timer.schedule(task, new Date(), 10000);
        }
        LOGGER.debug("Static Initializiation complete");
    }

    /**
     * Cleanup.
     */
    // just ends the auth config file update checking timer
    public void cleanup() {
        timer.cancel();
    }

    /**
     * Reload users.
     */
    /*
     * this essentially takes the data file, which is organized role-first with
     * users under each role and converts it to data organized user-first with
     * each user containing their role with its associated allowed functions
     * this data stored in the class field users
     */
    private synchronized void reloadUsers() {

        Map<String, AAIUser> tempUsers = new HashMap<>();

        try {
            LOGGER.debug("Reading from " + globalAuthFileName);
            String authFile = new String(Files.readAllBytes(Paths.get(globalAuthFileName)));

            JsonParser parser = new JsonParser();
            JsonObject authObject = parser.parse(authFile).getAsJsonObject();
            if (authObject.has("roles")) {
                JsonArray roles = authObject.getAsJsonArray("roles");
                for (JsonElement role : roles) {
                    if (role.isJsonObject()) {
                        JsonObject roleObject = role.getAsJsonObject();
                        String roleName = roleObject.get("name").getAsString();
                        Map<String, Boolean> usrs = this.getUsernamesFromRole(roleObject);
                        List<String> aaiFunctions = this.getAAIFunctions(roleObject);

                        usrs.forEach((key, value) -> {
                            final AAIUser au = tempUsers.getOrDefault(key, new AAIUser(key, value));
                            au.addRole(roleName);
                            aaiFunctions.forEach(f -> {
                                List<String> httpMethods = this.getRoleHttpMethods(f, roleObject);
                                httpMethods.forEach(hm -> au.setUserAccess(f, hm));
                                this.validFunctions.add(f);
                            });

                            tempUsers.put(key, au);

                        });
                    }
                }
                if (!tempUsers.isEmpty()) {
                    users = tempUsers;
                }
            }
        } catch (FileNotFoundException e) {
            ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Exception: " + e);
        } catch (JsonProcessingException e) {
            ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Not valid JSON: " + e);
        } catch (Exception e) {
            ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Exception caught: " + e);
        }
    }

    private List<String> getRoleHttpMethods(String aaiFunctionName, JsonObject roleObject) {
        List<String> httpMethods = new ArrayList<>();

        JsonArray ja = roleObject.getAsJsonArray("functions");
        for (JsonElement je : ja) {
            if (je.isJsonObject() && je.getAsJsonObject().has("name")
                    && je.getAsJsonObject().get("name").getAsString().equals(aaiFunctionName)) {
                JsonArray jaMeth = je.getAsJsonObject().getAsJsonArray("methods");
                for (JsonElement jeMeth : jaMeth) {
                    if (jeMeth.isJsonObject() && jeMeth.getAsJsonObject().has("name")) {
                        httpMethods.add(jeMeth.getAsJsonObject().get("name").getAsString());
                    }
                }
            }
        }

        return httpMethods;
    }

    private List<String> getAAIFunctions(JsonObject roleObject) {
        List<String> aaiFunctions = new ArrayList<>();

        JsonArray ja = roleObject.getAsJsonArray("functions");
        for (JsonElement je : ja) {
            if (je.isJsonObject() && je.getAsJsonObject().has("name")) {
                aaiFunctions.add(je.getAsJsonObject().get("name").getAsString());
            }
        }

        return aaiFunctions;
    }

    private Map<String, Boolean> getUsernamesFromRole(JsonObject roleObject) throws UnsupportedEncodingException {
        Map<String, Boolean> usernames = new HashMap<>();

        JsonArray uja = roleObject.getAsJsonArray("users");
        for (JsonElement je : uja) {
            if (je.isJsonObject()) {
                if (je.getAsJsonObject().has("username")) {
                    if (je.getAsJsonObject().has("is-wildcard-id")) {
                        usernames.put(je.getAsJsonObject().get("username").getAsString().toLowerCase(),
                                je.getAsJsonObject().get("is-wildcard-id").getAsBoolean());
                    } else {
                        usernames.put(je.getAsJsonObject().get("username").getAsString().toLowerCase(), false);
                    }
                } else if (je.getAsJsonObject().has("user")) {
                    String auth = je.getAsJsonObject().get("user").getAsString() + ":"
                            + Password.deobfuscate(je.getAsJsonObject().get("pass").getAsString());
                    String authorizationCode = new String(Base64.getEncoder().encode(auth.getBytes("utf-8")));
                    usernames.put(authorizationCode, false);
                }
            }
        }

        return usernames;
    }

    public String getAuthPolicyFunctName(String uri) {
        String authPolicyFunctionName = "";
        if (uri.startsWith(basePath + "/search")) {
            authPolicyFunctionName = "search";
        } else if (uri.startsWith(basePath + "/recents")) {
            authPolicyFunctionName = "recents";
        } else if (uri.startsWith(basePath + "/cq2gremlin")) {
            authPolicyFunctionName = "cq2gremlin";
        } else if (uri.startsWith(basePath + "/cq2gremlintest")) {
            authPolicyFunctionName = "cq2gremlintest";
        } else if (uri.startsWith(basePath + "/util/echo")) {
            authPolicyFunctionName = "util";
        } else if (uri.startsWith(basePath + "/tools")) {
            authPolicyFunctionName = "tools";
        } else {
            Matcher match = authPolicyPattern.matcher(uri);
            if (match.find()) {
                authPolicyFunctionName = match.group(1);
            }
        }
        return authPolicyFunctionName;
    }

    /**
     * for backwards compatibility
     *
     * @param username
     * @param uri
     * @param httpMethod
     * @param haProxyUser
     * @return
     * @throws AAIUnrecognizedFunctionException
     */
    public boolean authorize(String username, String uri, String httpMethod, String haProxyUser)
            throws AAIUnrecognizedFunctionException {
        return authorize(username, uri, httpMethod, haProxyUser, null);
    }

    /**
     *
     * @param username
     * @param uri
     * @param httpMethod
     * @param haProxyUser
     * @param issuer issuer of the cert
     * @return
     * @throws AAIUnrecognizedFunctionException
     */
    public boolean authorize(String username, String uri, String httpMethod, String haProxyUser, String issuer)
            throws AAIUnrecognizedFunctionException {
        String aaiMethod = this.getAuthPolicyFunctName(uri);
        if (!this.validFunctions.contains(aaiMethod) && !("info".equalsIgnoreCase(aaiMethod))) {
            throw new AAIUnrecognizedFunctionException(aaiMethod);
        }
        boolean wildcardCheck = isWildcardIssuer(issuer);
        boolean authorized;
        LOGGER.debug(
                "Authorizing the user for the request cert {}, haproxy header {}, aai method {}, httpMethod {}, cert issuer {}",
                username, haProxyUser, aaiMethod, httpMethod, issuer);
        Optional<AAIUser> oau = this.getUser(username, wildcardCheck);
        if (oau.isPresent()) {
            AAIUser au = oau.get();
            if (au.hasRole("HAProxy")) {
                LOGGER.debug("User has HAProxy role");
                if ("GET".equalsIgnoreCase(httpMethod) && "util".equalsIgnoreCase(aaiMethod) && haProxyUser.isEmpty()) {
                    LOGGER.debug("Authorized user has HAProxy role with echo request");
                    authorized = this.authorize(au, aaiMethod, httpMethod);
                } else {
                    authorized = this.authorize(haProxyUser, uri, httpMethod, "", issuer);
                }
            } else {
                LOGGER.debug("User doesn't have HAProxy role so assuming its a regular client");
                authorized = this.authorize(au, aaiMethod, httpMethod);
            }
        } else {
            LOGGER.debug("User not found: " + username + " on function " + aaiMethod + " request type " + httpMethod);
            authorized = false;
        }

        return authorized;
    }

    private boolean isWildcardIssuer(String issuer) {
        if (issuer != null && !issuer.isEmpty()) {
            List<String> validIssuers = Arrays
                    .asList(AAIConfig.get("aaf.valid.issuer.wildcard", UUID.randomUUID().toString()).split("\\|"));
            for (String validIssuer : validIssuers) {
                if (issuer.contains(validIssuer)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * returns aai user either matching the username or containing the wildcard.
     *
     * @param username
     * @return
     */
    public Optional<AAIUser> getUser(String username, boolean wildcardCheck) {
        if (users.containsKey(username)) {
            return Optional.of(users.get(username));
        } else if (wildcardCheck) {
            List<AAIUser> laus =
                    users.entrySet().stream().filter(e -> e.getValue().isWildcard() && username.contains(e.getKey()))
                            .map(Map.Entry::getValue).collect(Collectors.toList());
            if (!laus.isEmpty()) {
                return Optional.of(laus.get(0));
            }
        }
        return Optional.empty();
    }

    /**
     *
     * @param aaiUser
     *        aai user with the username
     * @param aaiMethod
     *        aai function the authorization is required on
     * @param httpMethod
     *        http action user is attempting
     * @return true, if successful
     */
    private boolean authorize(AAIUser aaiUser, String aaiMethod, String httpMethod) {
        if ("info".equalsIgnoreCase(aaiMethod) || aaiUser.hasAccess(aaiMethod, httpMethod)) {
            LOGGER.debug("AUTH ACCEPTED: " + aaiUser.getUsername() + " on function " + aaiMethod + " request type "
                    + httpMethod);
            return true;
        } else {
            LOGGER.debug("AUTH FAILED: " + aaiUser.getUsername() + " on function " + aaiMethod + " request type "
                    + httpMethod);
            return false;
        }
    }
}