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