[DMAAP-KAFKA] Fix sonar coverage etc
[dmaap/kafka11aaf.git] / src / main / java / org / onap / dmaap / commonauth / kafka / base / authorization / Cadi3AAFProvider.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  org.onap.dmaap
4  *  ================================================================================
5  *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  *  Modification copyright (C) 2021 Nordix Foundation.
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
11  *        http://www.apache.org/licenses/LICENSE-2.0
12 *  
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *  ============LICENSE_END=========================================================
19  *  
20  *  
21  *******************************************************************************/
22 package org.onap.dmaap.commonauth.kafka.base.authorization;
23
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.util.Map;
27 import java.util.Properties;
28 import javax.security.auth.login.AppConfigurationEntry;
29 import javax.security.auth.login.Configuration;
30 import org.onap.aaf.cadi.PropAccess;
31 import org.onap.aaf.cadi.aaf.AAFPermission;
32 import org.onap.aaf.cadi.aaf.v2_0.AAFAuthn;
33 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
34 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
35 import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLur;
36 import org.onap.aaf.cadi.principal.UnAuthPrincipal;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class Cadi3AAFProvider implements AuthorizationProvider {
41
42         private static PropAccess access;
43         private static AAFCon<?> aafcon;
44         private static final String CADI_PROPERTIES = "/etc/kafka/data/cadi.properties";
45         private static final String AAF_LOCATOR_ENV = "aaf_locate_url";
46         private static String apiKey = null;
47         private static String kafkaUsername = null;
48         private static AAFAuthn<?> aafAuthn;
49         private static AbsAAFLur<AAFPermission> aafLur;
50         private static boolean enableCadi = false;
51         private static final String ENABLE_CADI = "enableCadi";
52         private static final Logger logger = LoggerFactory.getLogger(Cadi3AAFProvider.class);
53
54         static {
55                 if (System.getProperty(ENABLE_CADI) != null) {
56                         if (System.getProperty(ENABLE_CADI).equals("true")) {
57                                 enableCadi = true;
58                         }
59                 }
60          else{
61                 if (System.getenv(ENABLE_CADI) != null && System.getenv(ENABLE_CADI).equals("true")) {
62                         enableCadi = true;
63                 }
64          }
65                 Configuration config = Configuration.getConfiguration();
66                 try {
67                         if (config == null) {
68                                 logger.error("CRITICAL ERROR|Check java.security.auth.login.config VM argument|");
69                         } else {
70                                 // read the section for KafkaServer
71                                 AppConfigurationEntry[] entries = config.getAppConfigurationEntry("KafkaServer");
72                                 if (entries == null) {
73                                         logger.error(
74                                                         "CRITICAL ERROR|Check config contents passed in java.security.auth.login.config VM argument|");
75                                         kafkaUsername = "kafkaUsername";
76                                         apiKey = "apiKey";
77
78                                 } else {
79                                         for (AppConfigurationEntry entry : entries) {
80                                                 Map<String, ?> optionsMap = entry.getOptions();
81                                                 kafkaUsername = (String) optionsMap.get("username");
82                                                 apiKey = (String) optionsMap.get("password");
83                                         }
84                                 }
85                         }
86                 } catch (Exception e) {
87                         logger.error("CRITICAL ERROR: JAAS configuration incorrectly set: {}", e.getMessage());
88                 }
89         }
90
91         public static String getKafkaUsername() {
92                 return kafkaUsername;
93         }
94
95         public static boolean isCadiEnabled() {
96
97                 return enableCadi;
98         }
99
100         public Cadi3AAFProvider() {
101                 setup();
102         }
103
104         private synchronized void setup() {
105                 if (access == null) {
106
107                         Properties props = new Properties();
108                         FileInputStream fis;
109                         try {
110                                 if (System.getProperty("CADI_PROPERTIES") != null) {
111                                         fis = new FileInputStream(System.getProperty("CADI_PROPERTIES"));
112                                 } else {
113                                         fis = new FileInputStream(CADI_PROPERTIES);
114                                 }
115                                 try {
116                                         props.load(fis);
117                                         if (System.getenv(AAF_LOCATOR_ENV) != null)
118                                                 props.setProperty(AAF_LOCATOR_ENV, System.getenv(AAF_LOCATOR_ENV));
119                                         access = new PropAccess(props);
120                                 } finally {
121                                         fis.close();
122                                 }
123                         } catch (IOException e) {
124                                 logger.error("Unable to load " + CADI_PROPERTIES);
125                                 logger.error("Error", e);
126                         }
127                 }
128
129                 if (aafAuthn == null) {
130                         try {
131                                 aafcon = new AAFConHttp(access);
132                                 aafAuthn = aafcon.newAuthn();
133                                 aafLur = aafcon.newLur(aafAuthn);
134                         } catch (final Exception e) {
135                                 aafAuthn = null;
136                                 if (access != null)
137                                         access.log(e, "Failed to initialize AAF");
138                         }
139                 }
140
141         }
142
143         /**
144          * Checks if a user has a particular permission
145          * <p/>
146          * Returns true if the permission in found
147          */
148         public boolean hasPermission(String userId, String permission, String instance, String action) {
149                 boolean hasPermission = false;
150                 try {
151                         logger.info("^ Event at hasPermission to validate userid {} with {} {} {}", userId, permission, instance, action);
152                         // AAF Style permissions are in the form
153                         // Resource Name, Resource Type, Action
154                         if (userId.equals("admin")) {
155                                 hasPermission = true;
156                                 return hasPermission;
157                         }
158                         AAFPermission perm = new AAFPermission(null, permission, instance, action);
159                         if (aafLur != null) {
160                                 hasPermission = aafLur.fish(new UnAuthPrincipal(userId), perm);
161                                 logger.trace("Permission: {}  for user : {}  found: {}" , perm.getKey(), userId, hasPermission);
162                         } else {
163                                 logger.error("AAF client not initialized. Not able to find permissions.");
164                         }
165                 } catch (Exception e) {
166                         logger.error("AAF client not initialized", e);
167                 }
168                 return hasPermission;
169         }
170
171         public String getId() {
172                 return "CADI_AAF_PROVIDER";
173         }
174
175         public String authenticate(String userId, String password) throws IOException {
176
177                 logger.info("^Event received  with username {}", userId);
178
179                 if (!enableCadi) {
180                         return null;
181                 } else {
182                         if (userId.equals(kafkaUsername)) {
183                                 if (password.equals(apiKey)) {
184                                         logger.info("by passes the authentication for the admin {}", kafkaUsername);
185                                         return null;
186                                 } else {
187                                         String errorMessage = "Authentication failed for user " + kafkaUsername;
188                                         logger.error(errorMessage);
189                                         return errorMessage;
190                                 }
191
192                         }
193
194                         String aafResponse = aafAuthn.validate(userId, password);
195                         logger.info("aafResponse = {} for {}", aafResponse, userId);
196
197                         if (aafResponse != null) {
198                                 logger.error("Authentication failed for user {}", userId);
199                         }
200                         return aafResponse;
201                 }
202
203         }
204
205 }