Merge "add newly revealed ONAP IDs"
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / aaf / v2_0 / AAFLurPerm.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.lang.reflect.Constructor;
25 import java.lang.reflect.InvocationTargetException;
26 import java.net.ConnectException;
27 import java.net.URISyntaxException;
28 import java.security.Principal;
29 import java.util.Map;
30
31 import org.onap.aaf.cadi.AbsUserCache;
32 import org.onap.aaf.cadi.Access;
33 import org.onap.aaf.cadi.CadiException;
34 import org.onap.aaf.cadi.Lur;
35 import org.onap.aaf.cadi.Permission;
36 import org.onap.aaf.cadi.User;
37 import org.onap.aaf.cadi.Access.Level;
38 import org.onap.aaf.cadi.CachedPrincipal.Resp;
39 import org.onap.aaf.cadi.aaf.AAFPermission;
40 import org.onap.aaf.cadi.client.Future;
41 import org.onap.aaf.cadi.client.Rcli;
42 import org.onap.aaf.cadi.client.Retryable;
43 import org.onap.aaf.cadi.config.Config;
44 import org.onap.aaf.cadi.lur.LocalPermission;
45 import org.onap.aaf.misc.env.APIException;
46 import org.onap.aaf.misc.env.util.Split;
47
48 import aaf.v2_0.Perm;
49 import aaf.v2_0.Perms;
50
51 /**
52  * Use AAF Service as Permission Service.
53  * 
54  * This Lur goes after AAF Permissions, which are elements of Roles, not the Roles themselves.
55  * 
56  * If you want a simple Role Lur, use AAFRoleLur
57  * 
58  * @author Jonathan
59  *
60  */
61 public class AAFLurPerm extends AbsAAFLur<AAFPermission> {
62         private static final String ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR = "org.osaaf.cadi.oauth.OAuth2Lur";
63
64         /**
65          *  Need to be able to transmutate a Principal into either ATTUID or MechID, which are the only ones accepted at this
66          *  point by AAF.  There is no "domain", aka, no "@att.com" in "ab1234@att.com".  
67          *  
68          *  The only thing that matters here for AAF is that we don't waste calls with IDs that obviously aren't valid.
69          *  Thus, we validate that the ID portion follows the rules before we waste time accessing AAF remotely
70          * @throws APIException 
71          * @throws URISyntaxException 
72          * @throws DME2Exception 
73          */
74         // Package on purpose
75         AAFLurPerm(AAFCon<?> con) throws CadiException, APIException {
76                 super(con);
77                 attachOAuth2(con);
78         }
79
80         // Package on purpose
81         AAFLurPerm(AAFCon<?> con, AbsUserCache<AAFPermission> auc) throws APIException {
82                 super(con,auc);
83                 attachOAuth2(con);
84         }
85         
86         private void attachOAuth2(AAFCon<?> con) throws APIException {
87                 String oauth2_url;
88                 Class<?> tmcls = Config.loadClass(access,"org.osaaf.cadi.oauth.TokenMgr");
89                 if(tmcls!=null) {
90                         if((oauth2_url = con.access.getProperty(Config.CADI_OAUTH2_URL,null))!=null) {
91                                 try {
92                                         Constructor<?> tmconst = tmcls.getConstructor(AAFCon.class,String.class);
93                                         Object tokMangr = tmconst.newInstance(con,oauth2_url);
94                                         @SuppressWarnings("unchecked")
95                                         Class<Lur> oa2cls = (Class<Lur>)Config.loadClass(access,ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR);
96                                         Constructor<Lur> oa2const = oa2cls.getConstructor(tmcls);
97                                         Lur oa2 = oa2const.newInstance(tokMangr);
98                                         setPreemptiveLur(oa2);
99                                 } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
100                                         throw new APIException(e);
101                                 }
102                         } else {
103                                 access.log(Level.INIT, "Both cadi-oauth jar and Property",Config.CADI_OAUTH2_URL,"is required to initialize OAuth2");
104                         }
105                 }
106         }
107
108         protected User<AAFPermission> loadUser(final Principal principal)  {
109                 final String name = principal.getName();
110 //              // Note: The rules for AAF is that it only stores permissions for ATTUID and MechIDs, which don't 
111 //              // have domains.  We are going to make the Transitive Class (see this.transmutative) to convert
112 //              final Principal tp = principal; //transmutate.mutate(principal);
113 //              if(tp==null) {
114 //                      return null; // if not a valid Transmutated credential, don't bother calling...
115 //              }
116 //              TODO Create a dynamic way to declare domains supported.
117                 final long start = System.nanoTime();
118                 final boolean[] success = new boolean[]{false};
119                 
120 //              new Exception("loadUser").printStackTrace();
121                 try {
122                         return aaf.best(new Retryable<User<AAFPermission>>() {
123                                 @Override
124                                 public User<AAFPermission> code(Rcli<?> client) throws CadiException, ConnectException, APIException {
125                                         Future<Perms> fp = client.read("/authz/perms/user/"+name,aaf.permsDF);
126                                         
127                                         // In the meantime, lookup User, create if necessary
128                                         User<AAFPermission> user = getUser(principal);
129                                         Principal p;
130                                         if(user!=null && user.principal == null) {
131                                                 p = new Principal() {// Create a holder for lookups
132                                                         private String n = name;
133                                                         public String getName() {
134                                                                 return n;
135                                                         }
136                                                 };
137                                         } else {
138                                                 p = principal;
139                                         }
140                                         
141                                         if(user==null) {
142                                                 addUser(user = new User<AAFPermission>(p,aaf.userExpires)); // no password
143                                         }
144                                         
145                                         // OK, done all we can, now get content
146                                         if(fp.get(aaf.timeout)) {
147                                                 success[0]=true;
148                                                 Map<String, Permission> newMap = user.newMap();
149                                                 boolean willLog = aaf.access.willLog(Level.DEBUG);
150                                                 for(Perm perm : fp.value.getPerm()) {
151                                                         user.add(newMap,new AAFPermission(perm.getType(),perm.getInstance(),perm.getAction(),perm.getRoles()));
152                                                         if(willLog) {
153                                                                 aaf.access.log(Level.DEBUG, name,"has '",perm.getType(),'|',perm.getInstance(),'|',perm.getAction(),'\'');
154                                                         }
155                                                 }
156                                                 user.setMap(newMap);
157                                         } else {
158                                                 int code;
159                                                 switch(code=fp.code()) {
160                                                         case 401:
161                                                                 aaf.access.log(Access.Level.ERROR, code, "Unauthorized to make AAF calls");
162                                                                 break;
163                                                         case 404:
164                                                                 user.setNoPerms();
165                                                                 break;
166                                                         default:
167                                                                 aaf.access.log(Access.Level.ERROR, code, fp.body());
168                                                 }
169                                         }
170
171                                         return user;
172                                 }
173                         });
174                 } catch (Exception e) {
175                         aaf.access.log(e,"Calling","/authz/perms/user/"+name);
176                         success[0]=false;
177                         return null;
178                 } finally {
179                         float time = (System.nanoTime()-start)/1000000f;
180                         aaf.access.log(Level.INFO, success[0]?"Loaded":"Load Failure",name,"from AAF in",time,"ms");
181                 }
182         }
183
184         public Resp reload(User<AAFPermission> user) {
185                 final String name = user.name;
186                 long start = System.nanoTime();
187                 boolean success = false;
188                 try {
189                         Future<Perms> fp = aaf.client(Config.AAF_DEFAULT_VERSION).read(
190                                         "/authz/perms/user/"+name,
191                                         aaf.permsDF
192                                         );
193                         
194                         // OK, done all we can, now get content
195                         if(fp.get(aaf.timeout)) {
196                                 success = true;
197                                 Map<String,Permission> newMap = user.newMap(); 
198                                 boolean willLog = aaf.access.willLog(Level.DEBUG);
199                                 for(Perm perm : fp.value.getPerm()) {
200                                         user.add(newMap, new AAFPermission(perm.getType(),perm.getInstance(),perm.getAction(),perm.getRoles()));
201                                         if(willLog) {
202                                                 aaf.access.log(Level.DEBUG, name,"has",perm.getType(),perm.getInstance(),perm.getAction());
203                                         }
204                                 }
205                                 user.renewPerm();
206                                 return Resp.REVALIDATED;
207                         } else {
208                                 int code;
209                                 switch(code=fp.code()) {
210                                         case 401:
211                                                 aaf.access.log(Access.Level.ERROR, code, "Unauthorized to make AAF calls");
212                                                 break;
213                                         default:
214                                                 aaf.access.log(Access.Level.ERROR, code, fp.body());
215                                 }
216                                 return Resp.UNVALIDATED;
217                         }
218                 } catch (Exception e) {
219                         aaf.access.log(e,"Calling","/authz/perms/user/"+name);
220                         return Resp.INACCESSIBLE;
221                 } finally {
222                         float time = (System.nanoTime()-start)/1000000f;
223                         aaf.access.log(Level.AUDIT, success?"Reloaded":"Reload Failure",name,"from AAF in",time,"ms");
224                 }
225         }
226
227         @Override
228         protected boolean isCorrectPermType(Permission pond) {
229                 return pond instanceof AAFPermission;
230         }
231
232         /* (non-Javadoc)
233          * @see org.onap.aaf.cadi.Lur#createPerm(java.lang.String)
234          */
235         @Override
236         public Permission createPerm(String p) {
237                 String[] params = Split.split('|', p);
238                 if(params.length==3) {
239                         return new AAFPermission(params[0],params[1],params[2]);
240                 } else {
241                         return new LocalPermission(p);
242                 }
243         }
244         
245 }