fix new openssl, data, etc
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / aaf / v2_0 / AAFCon.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.aaf.v2_0;
23
24 import java.net.URI;
25 import java.net.UnknownHostException;
26 import java.util.Map;
27 import java.util.concurrent.ConcurrentHashMap;
28
29 import org.onap.aaf.cadi.AbsUserCache;
30 import org.onap.aaf.cadi.Access;
31 import org.onap.aaf.cadi.CadiException;
32 import org.onap.aaf.cadi.CadiWrap;
33 import org.onap.aaf.cadi.Connector;
34 import org.onap.aaf.cadi.Locator;
35 import org.onap.aaf.cadi.LocatorException;
36 import org.onap.aaf.cadi.Lur;
37 import org.onap.aaf.cadi.PropAccess;
38 import org.onap.aaf.cadi.SecuritySetter;
39 import org.onap.aaf.cadi.Access.Level;
40 import org.onap.aaf.cadi.aaf.AAFPermission;
41 import org.onap.aaf.cadi.aaf.marshal.CertsMarshal;
42 import org.onap.aaf.cadi.client.Future;
43 import org.onap.aaf.cadi.client.Rcli;
44 import org.onap.aaf.cadi.client.Retryable;
45 import org.onap.aaf.cadi.config.Config;
46 import org.onap.aaf.cadi.config.RegistrationPropHolder;
47 import org.onap.aaf.cadi.config.SecurityInfoC;
48 import org.onap.aaf.cadi.lur.EpiLur;
49 import org.onap.aaf.cadi.principal.BasicPrincipal;
50 import org.onap.aaf.cadi.principal.TaggedPrincipal;
51 import org.onap.aaf.cadi.util.FQI;
52 import org.onap.aaf.cadi.util.Vars;
53 import org.onap.aaf.misc.env.APIException;
54 import org.onap.aaf.misc.env.Data.TYPE;
55 import org.onap.aaf.misc.rosetta.env.RosettaDF;
56 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
57
58 import aaf.v2_0.Certs;
59 import aaf.v2_0.Error;
60 import aaf.v2_0.Perms;
61 import aaf.v2_0.Users;
62
63 public abstract class AAFCon<CLIENT> implements Connector {
64     final public Access access;
65     // Package access
66     final public int timeout, cleanInterval, connTimeout;
67     final public int highCount, userExpires, usageRefreshTriggerCount;
68     private Map<String,Rcli<CLIENT>> clients = new ConcurrentHashMap<>();
69     final public RosettaDF<Perms> permsDF;
70     final public RosettaDF<Certs> certsDF;
71     final public RosettaDF<Users> usersDF;
72     final public RosettaDF<Error> errDF;
73     private String realm;
74     public final String app;
75     protected final String apiVersion;
76     protected SecurityInfoC<CLIENT> si;
77
78     private AAFLurPerm lur;
79
80     final public RosettaEnv env;
81     protected AAFCon(AAFCon<CLIENT> copy) {
82             access = copy.access;
83             apiVersion = access.getProperty(Config.AAF_API_VERSION, Config.AAF_DEFAULT_API_VERSION);
84             timeout = copy.timeout;
85             cleanInterval = copy.cleanInterval;
86             connTimeout = copy.connTimeout;
87             highCount = copy.highCount;
88             userExpires = copy.userExpires;
89             usageRefreshTriggerCount = copy.usageRefreshTriggerCount;
90             permsDF = copy.permsDF;
91             certsDF = copy.certsDF;
92             usersDF = copy.usersDF;
93             errDF = copy.errDF;
94             app = copy.app;
95             si = copy.si;
96             env = copy.env;
97             realm = copy.realm;
98         }
99         protected AAFCon(Access access, String tag, SecurityInfoC<CLIENT> si) throws CadiException{
100             apiVersion = access.getProperty(Config.AAF_API_VERSION, Config.AAF_DEFAULT_API_VERSION);
101             if (tag==null) {
102                 throw new CadiException("AAFCon cannot be constructed without a property tag or URL");
103             } else {
104                 String str = access.getProperty(tag,null);
105                 if (str==null) {
106                     if (tag.contains("://")) { // assume a URL
107                         str = tag;
108                     } else {
109                         throw new CadiException("A URL or " + tag + " property is required.");
110                     }
111                 }
112                 try {
113                                 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
114                                 str = rph.replacements(str, null,null);
115                         } catch (UnknownHostException e) {
116                                 throw new CadiException(e);
117                         }
118                 access.printf(Level.INFO, "AAFCon has URL of %s",str);
119                 setInitURI(str);
120             }
121             try {
122                 this.access = access;
123                 this.si = si;
124                 if (si.defSS.getID().equals(SecurityInfoC.DEF_ID)) { // it's the Preliminary SS, try to get a better one
125                     String mechid = access.getProperty(Config.AAF_APPID, null);
126                     if (mechid==null) {
127                         mechid=access.getProperty(Config.OAUTH_CLIENT_ID,null);
128                     }
129                     String encpass = access.getProperty(Config.AAF_APPPASS, null);
130                     if (encpass==null) {
131                         encpass = access.getProperty(Config.OAUTH_CLIENT_SECRET,null);
132                     }
133                     if (encpass==null) {
134                         String alias = access.getProperty(Config.CADI_ALIAS, mechid);
135                         if (alias==null) {
136                             access.printf(Access.Level.WARN,"%s, %s or %s required before use.", Config.CADI_ALIAS, Config.AAF_APPID, Config.OAUTH_CLIENT_ID);
137                             set(si.defSS);
138                         } else {
139                             si.defSS=x509Alias(alias);
140                             set(si.defSS);
141                         }
142                     } else {
143                         if (mechid!=null) {
144                             si.defSS=basicAuth(mechid, encpass);
145                             set(si.defSS);
146                         } else {
147                             si.defSS=new SecuritySetter<CLIENT>() {
148         
149                                 @Override
150                                 public String getID() {
151                                     return "";
152                                 }
153         
154                                 @Override
155                                 public void setSecurity(CLIENT client) throws CadiException {
156                                     throw new CadiException("AAFCon has not been initialized with Credentials (SecuritySetter)");
157                                 }
158         
159                                 @Override
160                                 public int setLastResponse(int respCode) {
161                                     return 0;
162                                 }
163                             };
164                             set(si.defSS);
165                         }
166                     }
167                 }
168                 
169                 timeout = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT, Config.AAF_CALL_TIMEOUT_DEF));
170                 cleanInterval = Integer.parseInt(access.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF));
171                 highCount = Integer.parseInt(access.getProperty(Config.AAF_HIGH_COUNT, Config.AAF_HIGH_COUNT_DEF).trim());
172                 connTimeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF).trim());
173                 userExpires = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim());
174                 usageRefreshTriggerCount = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim())-1; // zero based
175         
176                 app=FQI.reverseDomain(si.defSS.getID());
177                 //TODO Get Realm from AAF
178                 realm="people.osaaf.org";
179         
180                 env = new RosettaEnv();
181                 permsDF = env.newDataFactory(Perms.class);
182                 usersDF = env.newDataFactory(Users.class);
183                 certsDF = env.newDataFactory(Certs.class);
184                 certsDF.rootMarshal(new CertsMarshal()); // Speedier Marshaling
185                 errDF = env.newDataFactory(Error.class);
186             } catch (APIException e) {
187                 throw new CadiException("AAFCon cannot be configured",e);
188             }
189         }
190         protected abstract URI initURI();
191     protected abstract void setInitURI(String uriString) throws CadiException;
192
193     public final String aafVersion() {
194         return apiVersion;
195     }
196     
197     /**
198      * Use this call to get the appropriate client based on configuration (HTTP, future)
199      * using default AAF API Version
200      * 
201      * @param apiVersion
202      * @return
203      * @throws CadiException
204      */
205     public Rcli<CLIENT> client() throws CadiException {
206         return client(apiVersion);
207     }           
208
209     /**
210      * Use this call to get the appropriate client based on configuration (HTTP, future)
211      * 
212      * @param apiVersion
213      * @return
214      * @throws CadiException
215      */
216     public Rcli<CLIENT> client(final String apiVersion) throws CadiException {
217         Rcli<CLIENT> client = clients.get(apiVersion);
218         if (client==null) {
219             client = rclient(initURI(),si.defSS);
220             client.apiVersion(apiVersion)
221                   .readTimeout(connTimeout);
222             clients.put(apiVersion, client);
223         } 
224         return client;
225     }
226
227     public Rcli<CLIENT> client(URI uri) throws CadiException {
228         return rclient(uri,si.defSS).readTimeout(connTimeout);
229     }
230     
231     /**
232      * Use this API when you have permission to have your call act as the end client's ID.
233      * 
234      *  Your calls will get 403 errors if you do not have this permission.  it is a special setup, rarely given.
235      * 
236      * @param apiVersion
237      * @param req
238      * @return
239      * @throws CadiException
240      */
241     public Rcli<CLIENT> clientAs(TaggedPrincipal p) throws CadiException {
242        return clientAs(apiVersion,p);
243     }
244     
245     /**
246      * Use this API when you have permission to have your call act as the end client's ID.
247      * 
248      *  Your calls will get 403 errors if you do not have this permission.  it is a special setup, rarely given.
249      * 
250      * @param apiVersion
251      * @param req
252      * @return
253      * @throws CadiException
254      */
255     public Rcli<CLIENT> clientAs(String apiVersion, TaggedPrincipal p) throws CadiException {
256         Rcli<CLIENT> cl = client(apiVersion);
257         return cl.forUser(transferSS(p));
258     }
259
260     
261     public RosettaEnv env() {
262         return env;
263     }
264     
265     /**
266      * Return the backing AAFCon, if there is a Lur Setup that is AAF.
267      * 
268      * If there is no AAFLur setup, it will return "null"
269      * @param servletRequest
270      * @return
271      */
272     public static final AAFCon<?> obtain(Object servletRequest) {
273         if (servletRequest instanceof CadiWrap) {
274             Lur lur = ((CadiWrap)servletRequest).getLur();
275             if (lur != null) {
276                 if (lur instanceof EpiLur) {
277                     AbsAAFLur<?> aal = (AbsAAFLur<?>) ((EpiLur)lur).subLur(AbsAAFLur.class);
278                     if (aal!=null) {
279                         return aal.aaf;
280                     }
281                 } else {
282                     if (lur instanceof AbsAAFLur) {
283                         return ((AbsAAFLur<?>)lur).aaf;
284                     }
285                 }
286             }
287         }
288         return null;
289     }
290     
291     public abstract AAFCon<CLIENT> clone(String url) throws CadiException, LocatorException;
292     
293     public AAFAuthn<CLIENT> newAuthn() throws APIException {
294         try {
295             return new AAFAuthn<>(this);
296         } catch (Exception e) {
297             throw new APIException(e);
298         }
299     }
300
301     public AAFAuthn<CLIENT> newAuthn(AbsUserCache<AAFPermission> c) {
302         return new AAFAuthn<>(this, c);
303     }
304
305     public AAFLurPerm newLur() throws CadiException {
306         try {
307             if (lur==null) {
308                 lur = new AAFLurPerm(this);
309                 return lur;
310             } else {
311                 return new AAFLurPerm(this,lur);
312             }
313         } catch (CadiException e) {
314             throw e;
315         } catch (Exception e) {
316             throw new CadiException(e);
317         }
318     }
319     
320     public AAFLurPerm newLur(AbsUserCache<AAFPermission> c) throws APIException {
321         try {
322             return new AAFLurPerm(this,c);
323         } catch (APIException e) {
324             throw e;
325         } catch (Exception e) {
326             throw new APIException(e);
327         }
328     }
329
330     protected abstract Rcli<CLIENT> rclient(URI uri, SecuritySetter<CLIENT> ss) throws CadiException;
331     
332     public abstract Rcli<CLIENT> rclient(Locator<URI> loc, SecuritySetter<CLIENT> ss) throws CadiException;
333
334     public Rcli<CLIENT> client(Locator<URI> locator) throws CadiException {
335         return rclient(locator,si.defSS);
336     }
337     
338     public abstract<RET> RET best(Retryable<RET> retryable) throws LocatorException, CadiException, APIException;
339
340     public abstract<RET> RET bestForUser(GetSetter get, Retryable<RET> retryable) throws LocatorException, CadiException, APIException;
341
342     public abstract SecuritySetter<CLIENT> basicAuth(String user, String password) throws CadiException;
343     
344     public abstract SecuritySetter<CLIENT> transferSS(TaggedPrincipal principal) throws CadiException;
345     
346     public abstract SecuritySetter<CLIENT> basicAuthSS(BasicPrincipal principal) throws CadiException;
347     
348     public abstract SecuritySetter<CLIENT> tokenSS(final String client_id, final String accessToken) throws CadiException;
349     
350     public abstract SecuritySetter<CLIENT> x509Alias(String alias) throws APIException, CadiException;
351     
352
353     public String getRealm() {
354         return realm;
355
356     }
357     
358     /**
359      * This interface allows the AAFCon, even though generic, to pass in correctly typed values based on the above SS commands.
360      * @author Jonathan
361      *
362      */
363     public interface GetSetter {
364         public<CLIENT> SecuritySetter<CLIENT> get(AAFCon<CLIENT> con) throws CadiException;
365     }
366
367     public SecuritySetter<CLIENT> set(final SecuritySetter<CLIENT> ss) {
368         si.set(ss);
369         for (Rcli<CLIENT> client : clients.values()) {
370             client.setSecuritySetter(ss);
371         }
372         return ss;
373     }
374     
375     public SecurityInfoC<CLIENT> securityInfo() {
376         return si;
377     }
378
379     public String defID() {
380         if (si!=null) {
381             return si.defSS.getID();
382         }
383         return "unknown";
384     }
385     
386     public void invalidate() throws CadiException {
387         for (Rcli<CLIENT> client : clients.values()) {
388             client.invalidate();
389         }
390         clients.clear();
391     }
392
393     public String readableErrMsg(Future<?> f) {
394         String text = f.body();
395         if (text==null || text.length()==0) {
396             text = f.code() + ": **No Message**";
397         } else if (text.contains("%")) {
398             try {
399                 Error err = errDF.newData().in(TYPE.JSON).load(f.body()).asObject();
400                 return Vars.convert(err.getText(),err.getVariables());
401             } catch (APIException e){
402                 access.log(e);
403             }
404         }
405         return text;
406     }
407     
408     public static AAFCon<?> newInstance(PropAccess pa) throws CadiException, LocatorException {
409         // Potentially add plugin for other kinds of Access
410         return new AAFConHttp(pa);
411     }
412 }