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