Merge "Add identities for DMaap"
[aaf/authz.git] / cadi / core / src / main / java / org / onap / aaf / cadi / config / Config.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 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  * 
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.aaf.cadi.config;
23
24 import java.io.IOException;
25 import java.lang.reflect.Constructor;
26 import java.lang.reflect.Field;
27 import java.lang.reflect.InvocationTargetException;
28 import java.lang.reflect.Method;
29 import java.net.HttpURLConnection;
30 import java.net.InetAddress;
31 import java.net.URI;
32 import java.net.UnknownHostException;
33 import java.security.NoSuchAlgorithmException;
34 import java.security.cert.CertificateException;
35 import java.util.ArrayList;
36 import java.util.List;
37
38 import org.onap.aaf.cadi.AbsUserCache;
39 import org.onap.aaf.cadi.Access;
40 import org.onap.aaf.cadi.Access.Level;
41 import org.onap.aaf.cadi.CachingLur;
42 import org.onap.aaf.cadi.CadiException;
43 import org.onap.aaf.cadi.Connector;
44 import org.onap.aaf.cadi.CredVal;
45 import org.onap.aaf.cadi.CredValDomain;
46 import org.onap.aaf.cadi.Locator;
47 import org.onap.aaf.cadi.LocatorException;
48 import org.onap.aaf.cadi.Lur;
49 import org.onap.aaf.cadi.PropAccess;
50 import org.onap.aaf.cadi.Symm;
51 import org.onap.aaf.cadi.TrustChecker;
52 import org.onap.aaf.cadi.lur.EpiLur;
53 import org.onap.aaf.cadi.lur.LocalLur;
54 import org.onap.aaf.cadi.lur.NullLur;
55 import org.onap.aaf.cadi.taf.HttpEpiTaf;
56 import org.onap.aaf.cadi.taf.HttpTaf;
57 import org.onap.aaf.cadi.taf.basic.BasicHttpTaf;
58 import org.onap.aaf.cadi.taf.cert.X509Taf;
59 import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf;
60
61 /**
62  * Create a Consistent Configuration mechanism, even when configuration styles are as vastly different as
63  * Properties vs JavaBeans vs FilterConfigs...
64  * 
65  * @author Jonathan
66  *
67  */
68 public class Config {
69
70     private static final String AAF_V2_0 = "org.onap.aaf.cadi.aaf.v2_0";
71     private static final String AAF_V2_0_AAFCON = AAF_V2_0+".AAFCon";
72     private static final String AAF_V2_0_AAF_LUR_PERM = AAF_V2_0+".AAFLurPerm";
73     private static final String OAUTH = "org.onap.auth.oauth";
74     private static final String OAUTH_TOKEN_MGR = OAUTH+".TokenMgr";
75     private static final String OAUTH_HTTP_TAF = OAUTH+".OAuth2HttpTaf";
76     private static final String OAUTH_DIRECT_TAF = OAUTH+".OAuthDirectTAF";
77     public static final String UTF_8 = "UTF-8";
78
79     // Property Names associated with configurations.
80     // As of 1.0.2, these have had the dots removed so as to be compatible with JavaBean style
81     // configurations as well as property list style.
82     public static final String HOSTNAME = "hostname";
83     public static final String CADI_PROP_FILES = "cadi_prop_files"; // Additional Properties files (separate with ;)
84     public static final String CADI_LOGLEVEL = "cadi_loglevel";
85     public static final String CADI_LOGDIR = "cadi_log_dir";
86     public static final String CADI_ETCDIR = "cadi_etc_dir";
87     public static final String CADI_LOGNAME = "cadi_logname";
88     public static final String CADI_KEYFILE = "cadi_keyfile";
89     public static final String CADI_KEYSTORE = "cadi_keystore";
90     public static final String CADI_KEYSTORE_PASSWORD = "cadi_keystore_password";
91     public static final String CADI_ALIAS = "cadi_alias";
92     public static final String CADI_LOGINPAGE_URL = "cadi_loginpage_url";
93     public static final String CADI_LATITUDE = "cadi_latitude";
94     public static final String CADI_LONGITUDE = "cadi_longitude";
95
96
97     public static final String CADI_KEY_PASSWORD = "cadi_key_password";
98     public static final String CADI_TRUSTSTORE = "cadi_truststore";
99     public static final String CADI_TRUSTSTORE_PASSWORD = "cadi_truststore_password";
100     public static final String CADI_X509_ISSUERS = "cadi_x509_issuers";
101     public static final String CADI_TRUST_MASKS="cadi_trust_masks";
102     public static final String CADI_TRUST_PERM="cadi_trust_perm"; //  IDs with this perm can utilize the "AS " user concept
103     public static final String CADI_PROTOCOLS = "cadi_protocols";
104     public static final String CADI_NOAUTHN = "cadi_noauthn";
105     public static final String CADI_LOC_LIST = "cadi_loc_list";
106     
107     // Special Behaviors
108     public static final String CADI_BATH_CONVERT = "cadi_bath_convert";
109     public static final String CADI_API_ENFORCEMENT = "cadi_api_enforcement";
110     
111     public static final String CADI_USER_CHAIN_TAG = "cadi_user_chain";
112     public static final String CADI_USER_CHAIN = "USER_CHAIN";
113     
114     public static final String CADI_OAUTH2_URL="cadi_oauth2_url";
115     public static final String CADI_TOKEN_DIR = "cadi_token_dir";
116
117     public static final String HTTPS_PROTOCOLS = "https.protocols";
118     public static final String HTTPS_CIPHER_SUITES = "https.cipherSuites";
119     public static final String HTTPS_CLIENT_PROTOCOLS="jdk.tls.client.protocols";
120     public static final String HTTPS_CIPHER_SUITES_DEFAULT="TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,"
121             + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,"
122             + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,"
123             + "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA,TLS_ECDH_ECDSA_WITH_RC4_128_SHA,"
124             + "TLS_ECDH_RSA_WITH_RC4_128_SHA,TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,"
125             + "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
126              
127
128     public static final String LOCALHOST_ALLOW = "localhost_allow";
129     public static final String LOCALHOST_DENY = "localhost_deny";
130     
131     public static final String BASIC_REALM = "basic_realm";  // what is sent to the client 
132     public static final String BASIC_WARN = "basic_warn";  // Warning of insecure channel 
133     public static final String USERS = "local_users";
134     public static final String GROUPS = "local_groups";
135     public static final String WRITE_TO = "local_writeto"; // dump RBAC to local file in Tomcat Style (some apps use)
136     
137     public static final String OAUTH_CLIENT_ID="client_id";
138     public static final String OAUTH_CLIENT_SECRET="client_secret";
139     
140     public static final String AAF_ENV = "aaf_env";
141     public static final String AAF_ROOT_NS = "aaf_root_ns";
142     public static final String AAF_ROOT_NS_DEF = "org.osaaf.aaf";
143     public static final String AAF_ROOT_COMPANY = "aaf_root_company";
144     public static final String AAF_LOCATE_URL = "aaf_locate_url"; //URL for AAF locator
145     private static final String AAF_LOCATE_URL_TAG = "AAF_LOCATE_URL"; // Name of Above for use in Config Variables.
146     public static final String AAF_DEFAULT_API_VERSION = "2.1";
147     public static final String AAF_API_VERSION = "aaf_api_version";
148     public static final String AAF_URL = "aaf_url"; //URL for AAF... Use to trigger AAF configuration
149     public static final String AAF_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.service:" + AAF_DEFAULT_API_VERSION;
150     public static final String GUI_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.gui:" + AAF_DEFAULT_API_VERSION;
151     public static final String CM_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.cm:" + AAF_DEFAULT_API_VERSION;
152     public static final String FS_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.fs:" + AAF_DEFAULT_API_VERSION;
153     public static final String HELLO_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.hello:" + AAF_DEFAULT_API_VERSION;
154     public static final String OAUTH2_TOKEN_URL = "https://AAF_LOCATE_URL/AAF_NS.token:" + AAF_DEFAULT_API_VERSION;
155     public static final String OAUTH2_INTROSPECT_URL = "https://AAF_LOCATE_URL/AAF_NS.introspect:" + AAF_DEFAULT_API_VERSION;
156
157     public static final String AAF_REGISTER_AS = "aaf_register_as";
158     public static final String AAF_APPID = "aaf_id";
159     public static final String AAF_APPPASS = "aaf_password";
160     public static final String AAF_LUR_CLASS = "aaf_lur_class";
161     public static final String AAF_TAF_CLASS = "aaf_taf_class";
162     public static final String AAF_CONNECTOR_CLASS = "aaf_connector_class";
163     public static final String AAF_LOCATOR_CLASS = "aaf_locator_class";
164     public static final String AAF_CONN_TIMEOUT = "aaf_conn_timeout";
165     public static final String AAF_CONN_TIMEOUT_DEF = "3000";
166     public static final String AAF_CONN_IDLE_TIMEOUT = "aaf_conn_idle_timeout"; // only for Direct Jetty Access.
167     public static final String AAF_CONN_IDLE_TIMEOUT_DEF = "10000"; // only for Direct Jetty Access.
168      
169     // Default Classes: These are for Class loading to avoid direct compile links
170     public static final String AAF_TAF_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFTaf";
171     public static final String AAF_LOCATOR_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFLocator";
172     public static final String CADI_OLUR_CLASS_DEF = "org.onap.aaf.cadi.olur.OLur";
173     public static final String CADI_OBASIC_HTTP_TAF_DEF = "org.onap.aaf.cadi.obasic.OBasicHttpTaf";
174     public static final String CADI_AAF_CON_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFCon";
175
176     public static final String AAF_CALL_TIMEOUT = "aaf_timeout";
177     public static final String AAF_CALL_TIMEOUT_DEF = "5000";
178     public static final String AAF_USER_EXPIRES = "aaf_user_expires";
179     public static final String AAF_USER_EXPIRES_DEF = "600000"; // Default is 10 mins
180     public static final String AAF_CLEAN_INTERVAL = "aaf_clean_interval";
181     public static final String AAF_CLEAN_INTERVAL_DEF = "30000"; // Default is 30 seconds
182     public static final String AAF_REFRESH_TRIGGER_COUNT = "aaf_refresh_trigger_count";
183     public static final String AAF_REFRESH_TRIGGER_COUNT_DEF = "3"; // Default is 10 mins
184     
185     public static final String AAF_HIGH_COUNT = "aaf_high_count";
186     public static final String AAF_HIGH_COUNT_DEF = "1000"; // Default is 1000 entries
187     public static final String AAF_PERM_MAP = "aaf_perm_map";
188     public static final String AAF_COMPONENT = "aaf_component";
189     public static final String AAF_CERT_IDS = "aaf_cert_ids";
190     public static final String AAF_DEBUG_IDS = "aaf_debug_ids"; // comma delimited
191     public static final String AAF_DATA_DIR = "aaf_data_dir"; // AAF processes and Components only.
192     public static final String AAF_RELEASE = "aaf_release";
193
194     public static final String GW_URL = "gw_url";
195     public static final String CM_URL = "cm_url";
196     public static final String CM_TRUSTED_CAS = "cm_trusted_cas";
197
198     public static final String PATHFILTER_URLPATTERN = "pathfilter_urlpattern";
199     public static final String PATHFILTER_STACK = "pathfilter_stack";
200     public static final String PATHFILTER_NS = "pathfilter_ns";
201     public static final String PATHFILTER_NOT_AUTHORIZED_MSG = "pathfilter_not_authorized_msg";
202
203     // This one should go unpublic
204     public static final String AAF_DEFAULT_REALM = "aaf_default_realm";
205     private static String defaultRealm="none";
206
207     public static final String AAF_DOMAIN_SUPPORT = "aaf_domain_support";
208     public static final String AAF_DOMAIN_SUPPORT_DEF = ".com:.org";
209
210     // OAUTH2
211     public static final String AAF_OAUTH2_TOKEN_URL = "aaf_oauth2_token_url";
212     public static final String AAF_OAUTH2_INTROSPECT_URL = "aaf_oauth2_introspect_url";
213     public static final String AAF_ALT_OAUTH2_TOKEN_URL = "aaf_alt_oauth2_token_url";
214     public static final String AAF_ALT_OAUTH2_INTROSPECT_URL = "aaf_alt_oauth2_introspect_url";
215     public static final String AAF_ALT_OAUTH2_DOMAIN = "aaf_alt_oauth2_domain"; 
216     public static final String AAF_ALT_CLIENT_ID = "aaf_alt_oauth2_client_id";
217     public static final String AAF_ALT_CLIENT_SECRET = "aaf_alt_oauth2_client_secret";
218     public static final String AAF_OAUTH2_HELLO_URL = "aaf_oauth2_hello_url";
219
220     private static final String AAF_V2_0_AAF_CON_HTTP = "org.onap.aaf.cadi.aaf.v2_0.AAFConHttp";
221
222
223     public static void setDefaultRealm(Access access) {
224         try {
225             defaultRealm = logProp(access,Config.AAF_DEFAULT_REALM,
226                 logProp(access,Config.BASIC_REALM,
227                     logProp(access,HOSTNAME,InetAddress.getLocalHost().getHostName())
228                     )
229                 );
230         } catch (UnknownHostException e) {
231             access.log(Level.INIT, "Unable to determine Hostname",e);
232         }
233     }
234
235     public static HttpTaf configHttpTaf(Connector con, SecurityInfoC<HttpURLConnection> si, TrustChecker tc, CredVal up, Lur lur, Object ... additionalTafLurs) throws CadiException, LocatorException {
236         Access access = si.access;
237         /////////////////////////////////////////////////////
238         // Setup AAFCon for any following
239         /////////////////////////////////////////////////////
240         Class<?> aafConClass = loadClass(access,CADI_AAF_CON_DEF);
241         Object aafcon = null;
242         if (con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) {
243             aafcon = con;
244         } else if (lur != null) {
245             Field f;
246             try {
247                 f = lur.getClass().getField("aaf");
248                 aafcon = f.get(lur);
249             } catch (Exception e) {
250                 access.log(Level.INIT, e);
251             }
252         }
253
254         boolean hasDirectAAF = hasDirect("DirectAAFLur",additionalTafLurs);
255         // IMPORTANT!  Don't attempt to load AAF Connector if there is no AAF URL
256         String aafURL = access.getProperty(AAF_URL,null);
257         if (!hasDirectAAF && aafcon==null && aafURL!=null) {
258             aafcon = loadAAFConnector(si, aafURL);    
259         }
260         
261         HttpTaf taf;
262         // Setup Host, in case Network reports an unusable Hostname (i.e. VTiers, VPNs, etc)
263         String hostname = logProp(access, HOSTNAME,null);
264         if (hostname==null) {
265             try {
266                 hostname = InetAddress.getLocalHost().getHostName();
267             } catch (UnknownHostException e1) {
268                 throw new CadiException("Unable to determine Hostname",e1);
269             }
270         }
271         
272         access.log(Level.INIT, "Hostname set to",hostname);
273         // Get appropriate TAFs
274         ArrayList<HttpTaf> htlist = new ArrayList<>();
275
276         /////////////////////////////////////////////////////
277         // Add a Denial of Service TAF
278         // Note: how IPs and IDs are added are up to service type.
279         // They call "DenialOfServiceTaf.denyIP(String) or denyID(String)
280         /////////////////////////////////////////////////////
281         htlist.add(new DenialOfServiceTaf(access));
282
283         /////////////////////////////////////////////////////
284         // Configure Client Cert TAF
285         /////////////////////////////////////////////////////
286         X509Taf x509TAF = null;
287         String truststore = logProp(access, CADI_TRUSTSTORE,null);
288         if (truststore!=null) {
289             String truststorePwd = access.getProperty(CADI_TRUSTSTORE_PASSWORD,null);
290             if (truststorePwd!=null) {
291                 if (truststorePwd.startsWith(Symm.ENC)) {
292                     try {
293                         access.decrypt(truststorePwd,false);
294                     } catch (IOException e) {
295                         throw new CadiException(CADI_TRUSTSTORE_PASSWORD + " cannot be decrypted",e);
296                     }
297                 }
298                 try {
299                     x509TAF=new X509Taf(access,lur);
300                     htlist.add(x509TAF);
301                     access.log(Level.INIT,"Certificate Authorization enabled");
302                 } catch (SecurityException | IllegalArgumentException e) {
303                     access.log(Level.INIT,"AAFListedCertIdentity cannot be instantiated. Certificate Authorization is now disabled",e);
304                 } catch (CertificateException e) {
305                     access.log(Level.INIT,"Certificate Authorization failed, it is disabled",e);
306                 } catch (NoSuchAlgorithmException e) {
307                     access.log(Level.INIT,"Certificate Authorization failed, wrong Security Algorithm",e);
308                 }
309             }
310         } else {
311             access.log(Level.INIT,"Certificate Authorization not enabled");
312         }
313         
314         /////////////////////////////////////////////////////
315         // Configure Basic Auth (local content)
316         /////////////////////////////////////////////////////
317         boolean hasOAuthDirectTAF = hasDirect("DirectOAuthTAF", additionalTafLurs);
318         String basicRealm = logProp(access, BASIC_REALM,null);
319         String aafCleanup = logProp(access, AAF_USER_EXPIRES,AAF_USER_EXPIRES_DEF); // Default is 10 mins
320         long userExp = Long.parseLong(aafCleanup);
321         boolean basicWarn = "TRUE".equals(access.getProperty(BASIC_WARN,"FALSE"));
322
323         if (!hasDirectAAF) {
324             HttpTaf aaftaf=null;
325             if (!hasOAuthDirectTAF) {
326                 if (basicRealm!=null) {
327                     @SuppressWarnings("unchecked")
328                     Class<HttpTaf> obasicCls = (Class<HttpTaf>)loadClass(access,CADI_OBASIC_HTTP_TAF_DEF);
329                     if (obasicCls!=null) {
330                         try {
331                             String tokenurl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL, null);
332                             String introspecturl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL, null);
333                             if (tokenurl==null || introspecturl==null) {
334                                 access.log(Level.INIT,"Both tokenurl and introspecturl are required. Oauth Authorization is disabled.");
335                             }
336                             Constructor<HttpTaf> obasicConst = obasicCls.getConstructor(PropAccess.class,String.class, String.class, String.class);
337                             htlist.add(obasicConst.newInstance(access,basicRealm,tokenurl,introspecturl));
338                             access.log(Level.INIT,"Oauth supported Basic Authorization is enabled");
339                         } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
340                             access.log(Level.INIT, e);
341                         }
342                     } else if (up!=null) {
343                         access.log(Level.INIT,"Basic Authorization is enabled using realm",basicRealm);
344                         // Allow warning about insecure channel to be turned off
345                         if (!basicWarn) {
346                             access.log(Level.INIT, "WARNING! The basicWarn property has been set to false.",
347                                 " There will be no additional warning if Basic Auth is used on an insecure channel");
348                         }
349                         BasicHttpTaf bht = new BasicHttpTaf(access, up, basicRealm, userExp, basicWarn);
350                         for (Object o : additionalTafLurs) {
351                             if (o instanceof CredValDomain) {
352                                 bht.add((CredValDomain)o);
353                             }
354                         }
355                         if (x509TAF!=null) {
356                             x509TAF.add(bht);
357                         }
358                         htlist.add(bht);
359                         access.log(Level.INIT,"Basic Authorization is enabled");
360                     }
361                 } else {
362                     access.log(Level.INIT,"Local Basic Authorization is disabled.  Enable by setting basicRealm=<appropriate realm, i.e. my.att.com>");
363                 }
364             
365                 /////////////////////////////////////////////////////
366                 // Configure AAF Driven Basic Auth
367                 /////////////////////////////////////////////////////
368                 if (aafcon==null) {
369                     access.log(Level.INIT,"AAF Connection (AAFcon) is null.  Cannot create an AAF TAF");
370                 } else if (aafURL==null) {
371                     access.log(Level.INIT,"No AAF URL in properties, Cannot create an AAF TAF");
372                 } else {// There's an AAF_URL... try to configure an AAF 
373                     String aafTafClassName = logProp(access, AAF_TAF_CLASS,AAF_TAF_CLASS_DEF);
374                     // Only 2.0 available at this time
375                     if (AAF_TAF_CLASS_DEF.equals(aafTafClassName)) { 
376                         try {
377                             Class<?> aafTafClass = loadClass(access,aafTafClassName);
378                             if (aafTafClass!=null) {
379                                 Constructor<?> cstr = aafTafClass.getConstructor(Connector.class,boolean.class,AbsUserCache.class);
380                                 if (cstr!=null) {
381                                     if (lur instanceof AbsUserCache) {
382                                         aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn,lur);
383                                     } else {
384                                         cstr = aafTafClass.getConstructor(Connector.class,boolean.class);
385                                         if (cstr!=null) {
386                                             aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn);
387                                         }
388                                     }
389                                     if (aaftaf==null) {
390                                         access.log(Level.INIT,"ERROR! AAF TAF Failed construction.  NOT Configured");
391                                     } else {
392                                         access.log(Level.INIT,"AAF TAF Configured to ",aafURL);
393                                         // Note: will add later, after all others configured
394                                     }
395                                 }
396                             } else {
397                                 access.log(Level.INIT, "There is no AAF TAF class available: %s. AAF TAF not configured.",aafTafClassName);
398                             }
399                         } catch (Exception e) {
400                             access.log(Level.INIT,"ERROR! AAF TAF Failed construction.  NOT Configured",e);
401                         }
402                     }
403                 }
404             }
405             
406             /////////////////////////////////////////////////////
407             // Configure OAuth TAF
408             /////////////////////////////////////////////////////
409             if (!hasOAuthDirectTAF) {
410                 String oauthTokenUrl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL,null);
411                 Class<?> oadtClss;
412                 try {
413                     oadtClss = Class.forName(OAUTH_DIRECT_TAF);
414                 } catch (ClassNotFoundException e1) {
415                     oadtClss = null;
416                     access.log(Level.DEBUG, e1);
417                 }
418                 if (additionalTafLurs!=null && additionalTafLurs.length>0 && (oadtClss!=null && additionalTafLurs[0].getClass().isAssignableFrom(oadtClss))) {
419                     htlist.add((HttpTaf)additionalTafLurs[0]);
420                     String[] array= new String[additionalTafLurs.length-1];
421                     if (array.length>0) {
422                         System.arraycopy(htlist, 1, array, 0, array.length);
423                     }
424                     additionalTafLurs = array;
425                     access.log(Level.INIT,"OAuth2 Direct is enabled");
426                 } else if (oauthTokenUrl!=null) {
427                     String oauthIntrospectUrl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL,null);
428                     @SuppressWarnings("unchecked")
429                     Class<HttpTaf> oaTCls = (Class<HttpTaf>)loadClass(access,OAUTH_HTTP_TAF);
430                     if (oaTCls!=null) {
431                         Class<?> oaTTmgrCls = loadClass(access, OAUTH_TOKEN_MGR);
432                         if (oaTTmgrCls!=null) {
433                             try {
434                                 Method oaTTmgrGI = oaTTmgrCls.getMethod("getInstance",PropAccess.class,String.class,String.class);
435                                 Object oaTTmgr = oaTTmgrGI.invoke(null /*this is static method*/,access,oauthTokenUrl,oauthIntrospectUrl);
436                                 Constructor<HttpTaf> oaTConst = oaTCls.getConstructor(Access.class,oaTTmgrCls);
437                                 htlist.add(oaTConst.newInstance(access,oaTTmgr));
438                                 access.log(Level.INIT,"OAuth2 TAF is enabled");
439                             } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
440                                 access.log(Level.INIT,"OAuth2HttpTaf cannot be instantiated. OAuth2 is disabled",e);
441                             }
442                         }
443                     }
444                 } else {
445                     access.log(Level.INIT,"OAuth TAF is not configured");
446                 }
447             }
448     
449             /////////////////////////////////////////////////////
450             // Adding BasicAuth (AAF) last, after other primary Cookie Based
451             // Needs to be before Cert... see below
452             /////////////////////////////////////////////////////
453             if (aaftaf!=null) {
454                 htlist.add(aaftaf);
455             }
456         }    
457
458         /////////////////////////////////////////////////////
459         // Any Additional Lurs passed in Constructor
460         /////////////////////////////////////////////////////
461         if (additionalTafLurs!=null) {
462             for (Object additional : additionalTafLurs) {
463                 if (additional instanceof BasicHttpTaf) {
464                     BasicHttpTaf ht = (BasicHttpTaf)additional;
465                     for (Object cv : additionalTafLurs) {
466                         if (cv instanceof CredValDomain) {
467                             ht.add((CredValDomain)cv);
468                             access.printf(Level.INIT,"%s Authentication is enabled",cv);
469                         }
470                     }
471                     htlist.add(ht);
472                 } else if (additional instanceof HttpTaf) {
473                     HttpTaf ht = (HttpTaf)additional;
474                     htlist.add(ht);
475                     access.printf(Level.INIT,"%s Authentication is enabled",additional.getClass().getSimpleName());
476                 } else if (hasOAuthDirectTAF) {
477                     Class<?> daupCls;
478                     try {
479                         daupCls = Class.forName("org.onap.aaf.auth.direct.DirectAAFUserPass");
480                     } catch (ClassNotFoundException e) {
481                         daupCls = null;
482                         access.log(Level.INIT, e);
483                     }
484                     if (daupCls != null && additional.getClass().isAssignableFrom(daupCls)) {
485                         htlist.add(new BasicHttpTaf(access, (CredVal)additional , basicRealm, userExp, basicWarn));
486                         access.printf(Level.INIT,"Direct BasicAuth Authentication is enabled",additional.getClass().getSimpleName());
487                     }
488                 }
489             }
490         }
491         
492         // Add BasicAuth, if any, to x509Taf
493         if (x509TAF!=null) {
494             for ( HttpTaf ht : htlist) {
495                 if (ht instanceof BasicHttpTaf) {
496                     x509TAF.add((BasicHttpTaf)ht);
497                 }
498             }
499         }
500         /////////////////////////////////////////////////////
501         // Create EpiTaf from configured TAFs
502         /////////////////////////////////////////////////////
503         if (htlist.size()==1) {
504             // just return the one
505             taf = htlist.get(0);
506         } else {
507             HttpTaf[] htarray = new HttpTaf[htlist.size()];
508             htlist.toArray(htarray);
509             Locator<URI> locator = loadLocator(si, logProp(access, AAF_LOCATE_URL, null));
510             
511             taf = new HttpEpiTaf(access,locator, tc, htarray); // ok to pass locator == null
512             String level = logProp(access, CADI_LOGLEVEL, null);
513             if (level!=null) {
514                 access.setLogLevel(Level.valueOf(level));
515             }
516         }
517         
518         return taf;
519     }
520     
521     public static String logProp(Access access,String tag, String def) {
522         String rv = access.getProperty(tag, def);
523         if (rv == null) {
524             access.log(Level.INIT,tag,"is not explicitly set");
525         } else {
526             access.log(Level.INIT,tag,"is set to",rv);
527         }
528         return rv;
529     }
530     
531     public static Lur configLur(SecurityInfoC<HttpURLConnection> si, Connector con, Object ... additionalTafLurs) throws CadiException {
532         Access access = si.access;
533         List<Lur> lurs = new ArrayList<>();
534         
535         /////////////////////////////////////////////////////
536         // Configure a Local Property Based RBAC/LUR
537         /////////////////////////////////////////////////////
538         try {
539             String users = access.getProperty(USERS,null);
540             String groups = access.getProperty(GROUPS,null);
541
542             if (groups!=null || users!=null) {
543                 LocalLur ll = new LocalLur(access, users, groups);  // note b64==null is ok.. just means no encryption.
544                 lurs.add(ll);
545                 
546                 String writeto = access.getProperty(WRITE_TO,null);
547                 if (writeto!=null) {
548                     String msg = UsersDump.updateUsers(writeto, ll);
549                     if (msg!=null) {
550                         access.log(Level.INIT,"ERROR! Error Updating ",writeto,"with roles and users:",msg);
551                     }
552                 }
553             }
554         } catch (IOException e) {
555             throw new CadiException(e);
556         }
557
558         /////////////////////////////////////////////////////
559         // Configure the OAuth Lur (if any)
560         /////////////////////////////////////////////////////
561         String tokenUrl = logProp(access,AAF_OAUTH2_TOKEN_URL, null);
562         String introspectUrl = logProp(access,AAF_OAUTH2_INTROSPECT_URL, null);
563         if (tokenUrl!=null && introspectUrl !=null) {
564             try {
565                 Class<?> olurCls = loadClass(access, CADI_OLUR_CLASS_DEF);
566                 if (olurCls!=null) {
567                     Constructor<?> olurCnst = olurCls.getConstructor(PropAccess.class,String.class,String.class);
568                     Lur olur = (Lur)olurCnst.newInstance(access,tokenUrl,introspectUrl);
569                     lurs.add(olur);
570                     access.log(Level.INIT, "OAuth2 LUR enabled");
571                 } else {
572                     access.log(Level.INIT,"AAF/OAuth LUR plugin is not available.");
573                 }
574             } catch (NoSuchMethodException| SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
575                 String msg = e.getMessage();
576                 if (msg==null && e.getCause()!=null) {
577                     msg = e.getCause().getMessage();
578                 }
579                 access.log(Level.INIT,"AAF/OAuth LUR is not instantiated.",msg,e);
580             } 
581         } else {
582             access.log(Level.INIT, "OAuth2 Lur disabled");
583         }
584
585         if (con!=null) { // try to reutilize connector
586             lurs.add(con.newLur());
587         } else { 
588             /////////////////////////////////////////////////////
589             // Configure the AAF Lur (if any)
590             /////////////////////////////////////////////////////
591             String aafURL = logProp(access,AAF_URL,null); // Trigger Property
592             String aafEnv = access.getProperty(AAF_ENV,null);
593             if (aafEnv == null && aafURL!=null && access instanceof PropAccess) { // set AAF_ENV from AAF_URL
594                 int ec = aafURL.indexOf("envContext=");
595                 if (ec>0) {
596                     ec += 11; // length of envContext=
597                     int slash = aafURL.indexOf('/', ec);
598                     if (slash>0) {
599                         aafEnv = aafURL.substring(ec, slash);
600                         ((PropAccess)access).setProperty(AAF_ENV, aafEnv);
601                         access.printf(Level.INIT, "Setting aafEnv to %s from aaf_url value",aafEnv);
602                     }
603                 }
604             }
605
606             // Don't configure AAF if it is using DirectAccess
607             if (!hasDirect("DirectAAFLur",additionalTafLurs)) {
608                 if (aafURL==null) {
609                     access.log(Level.INIT,"No AAF LUR properties, AAF will not be loaded");
610                 } else {// There's an AAF_URL... try to configure an AAF
611                     String aafLurClassStr = logProp(access,AAF_LUR_CLASS,AAF_V2_0_AAF_LUR_PERM);
612                     ////////////AAF Lur 2.0 /////////////
613                     if (aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) { 
614                         try {
615                             Object aafcon = loadAAFConnector(si, aafURL);
616                             if (aafcon==null) {
617                                 access.log(Level.INIT,"AAF LUR class,",aafLurClassStr,"cannot be constructed without valid AAFCon object.");
618                             } else {
619                                 Class<?> aafAbsAAFCon = loadClass(access, AAF_V2_0_AAFCON);
620                                 if (aafAbsAAFCon!=null) {
621                                     Method mNewLur = aafAbsAAFCon.getMethod("newLur");
622                                     Object aaflur = mNewLur.invoke(aafcon);
623                 
624                                     if (aaflur==null) {
625                                         access.log(Level.INIT,"ERROR! AAF LUR Failed construction.  NOT Configured");
626                                     } else {
627                                         access.log(Level.INIT,"AAF LUR Configured to ",aafURL);
628                                         lurs.add((Lur)aaflur);
629                                         String debugIDs = logProp(access,Config.AAF_DEBUG_IDS, null);
630                                         if (debugIDs !=null && aaflur instanceof CachingLur) {
631                                             ((CachingLur<?>)aaflur).setDebug(debugIDs);
632                                         }
633                                     }
634                                 }
635                             }
636                         } catch (Exception e) {
637                             access.log(e,"AAF LUR class,",aafLurClassStr,"could not be constructed with given Constructors.");
638                         }
639                     } 
640                 }
641             }
642         }
643
644         /////////////////////////////////////////////////////
645         // Any Additional passed in Constructor
646         /////////////////////////////////////////////////////
647         if (additionalTafLurs!=null) {
648             for (Object additional : additionalTafLurs) {
649                 if (additional instanceof Lur) {
650                     lurs.add((Lur)additional);
651                     access.log(Level.INIT, additional);
652                 }
653             }
654         }
655
656         /////////////////////////////////////////////////////
657         // Return a Lur based on how many there are... 
658         /////////////////////////////////////////////////////
659         switch(lurs.size()) {
660             case 0: 
661                 access.log(Level.INIT,"WARNING! No CADI LURs configured");
662                 // Return a NULL Lur that does nothing.
663                 return new NullLur();
664             case 1:
665                 return lurs.get(0); // Only one, just return it, save processing
666             default:
667                 // Multiple Lurs, use EpiLUR to handle
668                 Lur[] la = new Lur[lurs.size()];
669                 lurs.toArray(la);
670                 return new EpiLur(la);
671         }
672     }
673     
674     private static boolean hasDirect(String simpleClassName, Object[] additionalTafLurs) {
675         if (additionalTafLurs!=null) {
676             for (Object tf : additionalTafLurs) {
677                 if (tf.getClass().getSimpleName().equals(simpleClassName)) {
678                     return true;
679                 }
680             }
681         }
682         return false;
683     }
684
685     public static Object loadAAFConnector(SecurityInfoC<HttpURLConnection> si, String aafURL) {
686         Access access = si.access;
687         Object aafcon = null;
688         Class<?> aafConClass = null;
689
690         try {
691             if (aafURL!=null) {
692                 String aafConnector = access.getProperty(AAF_CONNECTOR_CLASS, AAF_V2_0_AAF_CON_HTTP);
693                 if (AAF_V2_0_AAF_CON_HTTP.equals(aafConnector)) {
694                     aafConClass = loadClass(access, AAF_V2_0_AAF_CON_HTTP);
695                     if (aafConClass != null) {
696                         for (Constructor<?> c : aafConClass.getConstructors()) {
697                             List<Object> lo = new ArrayList<>();
698                             for (Class<?> pc : c.getParameterTypes()) {
699                                 if (pc.equals(Access.class)) {
700                                     lo.add(access);
701                                 } else if (pc.equals(Locator.class)) {
702                                     lo.add(loadLocator(si, aafURL));
703                                 }
704                             }
705                             if (c.getParameterTypes().length != lo.size()) {
706                                 continue; // back to another Constructor
707                             } else {
708                                 aafcon = c.newInstance(lo.toArray());
709                             }
710                             break;
711                         }
712                     }
713                 }
714                 if (aafcon != null) {
715                     String mechid = logProp(access, Config.AAF_APPID, null);
716                     String pass = access.getProperty(Config.AAF_APPPASS, null);
717                     if (mechid != null && pass != null) {
718                         try {
719                             Method basicAuth = aafConClass.getMethod("basicAuth", String.class, String.class);
720                             basicAuth.invoke(aafcon, mechid, pass);
721                         } catch (NoSuchMethodException nsme) {
722                             access.log(Level.NONE, nsme);
723                             // it's ok, don't use
724                         }
725                     }
726                 }
727             }
728         } catch (Exception e) {
729             access.log(e, "AAF Connector could not be constructed with given Constructors.");
730         }
731
732         return aafcon;
733     }
734
735     public static Class<?> loadClass(Access access, String className) {
736         Class<?> cls=null;
737         try {
738             cls = access.classLoader().loadClass(className);
739         } catch (ClassNotFoundException cnfe) {
740             access.log(Level.NONE, cnfe);
741             try {
742                 cls = access.getClass().getClassLoader().loadClass(className);
743             } catch (ClassNotFoundException cnfe2) {
744                 access.log(Level.NONE, cnfe2);
745                 // just return null
746             }
747         }
748         return cls;
749     }
750
751     @SuppressWarnings("unchecked")
752     public static Locator<URI> loadLocator(SecurityInfoC<HttpURLConnection> si, final String _url) throws LocatorException {
753         Access access = si.access;
754         Locator<URI> locator = null;
755         if (_url==null) {
756             access.log(Level.INIT,"No URL passed to 'loadLocator'. Disabled");
757         } else {
758             String url = _url;
759             String replacement;
760             int idxAAFLocateUrl;
761             if ((idxAAFLocateUrl=_url.indexOf(AAF_LOCATE_URL_TAG))>0 && ((replacement=access.getProperty(AAF_LOCATE_URL, null))!=null)) {
762                 StringBuilder sb = new StringBuilder(replacement);
763                 if (!replacement.endsWith("/locate")) {
764                     sb.append("/locate");
765                 } 
766                 sb.append(_url,idxAAFLocateUrl+AAF_LOCATE_URL_TAG.length(),_url.length());
767                 url = sb.toString();
768             }
769     
770             try {
771                 Class<?> lcls = loadClass(access,AAF_LOCATOR_CLASS_DEF);
772                 if (lcls==null) {
773                     throw new CadiException("Need to include aaf-cadi-aaf jar for AAFLocator");
774                 }
775                 // First check for preloaded
776                 try {
777                     Method meth = lcls.getMethod("create",String.class);
778                     locator = (Locator<URI>)meth.invoke(null,url);
779                 } catch (Exception e) {
780                     access.log(Level.DEBUG, "(Not fatal) Cannot load by create(String)", e);
781                 }
782                 if (locator==null) {
783                     URI locatorURI = new URI(url);
784                     Constructor<?> cnst = lcls.getConstructor(SecurityInfoC.class,URI.class);
785                     locator = (Locator<URI>)cnst.newInstance(new Object[] {si,locatorURI});
786                     int port = locatorURI.getPort();
787                     String portS = port<0?"":(":"+locatorURI.getPort());
788                     
789                     access.log(Level.INFO, "AAFLocator enabled using " + locatorURI.getScheme() +"://"+locatorURI.getHost() + portS);
790                 } else {
791                     access.log(Level.INFO, "AAFLocator enabled using preloaded " + locator.getClass().getSimpleName());
792                 }
793             } catch (InvocationTargetException e) {
794                 if (e.getTargetException() instanceof LocatorException) {
795                     throw (LocatorException)e.getTargetException();
796                 }
797                 access.log(Level.INIT,e.getTargetException().getMessage(),"AAFLocator for",url,"could not be created.",e);
798             } catch (Exception e) {
799                 access.log(Level.INIT,"AAFLocator for",url,"could not be created.",e);
800             }
801         }
802         return locator;
803     }
804
805     // Set by CSP, or is hostname.
806     public static String getDefaultRealm() {
807         return defaultRealm;
808     }
809
810 }
811