fix shiro logs looping issue
[aaf/cadi.git] / shiro / src / main / java / org / onap / aaf / cadi / shiro / AAFRealm.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 package org.onap.aaf.cadi.shiro;
22
23 import java.io.IOException;
24 import java.io.PrintStream;
25 import java.security.Principal;
26 import java.util.ArrayList;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.TreeMap;
32
33
34 import org.apache.log4j.PropertyConfigurator;
35 import org.apache.shiro.authc.AuthenticationException;
36 import org.apache.shiro.authc.AuthenticationInfo;
37 import org.apache.shiro.authc.AuthenticationToken;
38 import org.apache.shiro.authc.UsernamePasswordToken;
39 import org.apache.shiro.realm.AuthorizingRealm;
40 import org.apache.shiro.subject.PrincipalCollection;
41 import org.onap.aaf.cadi.Access.Level;
42 import org.onap.aaf.cadi.CadiException;
43 import org.onap.aaf.cadi.LocatorException;
44 import org.onap.aaf.cadi.Permission;
45 import org.onap.aaf.cadi.PropAccess;
46 import org.onap.aaf.cadi.Symm;
47 import org.onap.aaf.cadi.aaf.v2_0.AAFAuthn;
48 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
49 import org.onap.aaf.cadi.aaf.v2_0.AAFLurPerm;
50 import org.onap.aaf.cadi.config.Config;
51 import org.onap.aaf.cadi.filter.MapBathConverter;
52 import org.onap.aaf.cadi.util.CSV;
53 import org.onap.aaf.misc.env.APIException;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 public class AAFRealm extends AuthorizingRealm {
58         
59         final static  Logger logger =  LoggerFactory.getLogger(AAFRealm.class);
60         
61         public static final String AAF_REALM = "AAFRealm";
62         
63         private PropAccess access;
64         private AAFCon<?> acon;
65         private AAFAuthn<?> authn;
66         private HashSet<Class<? extends AuthenticationToken>> supports;
67         private AAFLurPerm authz;
68         private MapBathConverter mbc;
69         private Map<String,String> idMap;
70         
71
72         /**
73          * 
74          * There appears to be no configuration objects or references available for CADI to start with.
75          *  
76          */
77         public AAFRealm () {
78                 access = new PropAccess(); // pick up cadi_prop_files from VM_Args
79                 mbc = null;
80                 idMap = null;
81                 String cadi_prop_files = access.getProperty(Config.CADI_PROP_FILES);
82                 if(cadi_prop_files==null) {
83                         String msg = Config.CADI_PROP_FILES + " in VM Args is required to initialize AAFRealm.";
84                         logger.info(msg);
85                         throw new RuntimeException(msg);
86                 } else {
87                         try {
88                                 acon = AAFCon.newInstance(access);
89                                 authn = acon.newAuthn();
90                                 authz = acon.newLur(authn);
91                                 
92                                 final String csv = access.getProperty(Config.CADI_BATH_CONVERT);
93                                 if(csv!=null) {
94                                         try {
95                                                 mbc = new MapBathConverter(access, new CSV(csv));
96                                                 logger.info("MapBathConversion enabled with file "+csv);
97                                                 idMap = new TreeMap<String,String>();
98                                                 // Load 
99                                                 for(Entry<String, String> es : mbc.map().entrySet()) {
100                                                         String oldID = es.getKey();
101                                                         if(oldID.startsWith("Basic ")) {
102                                                                 oldID = Symm.base64noSplit.decode(oldID.substring(6));
103                                                                 int idx = oldID.indexOf(':');
104                                                                 if(idx>=0) {
105                                                                         oldID = oldID.substring(0, idx);
106                                                                 }
107                                                         }
108                                                         String newID = es.getValue();
109                                                         if(newID.startsWith("Basic ")) {
110                                                                 newID = Symm.base64noSplit.decode(newID.substring(6));
111                                                                 int idx = newID.indexOf(':');
112                                                                 if(idx>=0) {
113                                                                         newID = newID.substring(0, idx);
114                                                                 }
115                                                         }
116                                                         idMap.put(oldID,newID);
117                                                         
118                                                 }
119                                         } catch (IOException e) {
120                                                 logger.info(e.getMessage(), e);
121                                         }
122                                 }
123                         } catch (APIException | CadiException | LocatorException e) {
124                                 String msg = "Cannot initiate AAFRealm";
125                                 logger.info(msg + " "+ e.getMessage(), e);
126                                 throw new RuntimeException(msg,e);
127                         }
128                 }
129                 supports = new HashSet<Class<? extends AuthenticationToken>>();
130                 supports.add(UsernamePasswordToken.class);
131         }
132
133         @Override
134         protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
135                 logger.info("AAFRealm.doGetAuthenticationInfo :"+token);
136                 final UsernamePasswordToken upt = (UsernamePasswordToken)token;
137                 final String user = upt.getUsername();
138                 String authUser = user; 
139                 final String password=new String(upt.getPassword());
140                 String authPassword = password;
141                 if(mbc!=null) {
142                         try {
143                                 final String oldBath = "Basic " + Symm.base64noSplit.encode(user+':'+password);
144                                 String bath = mbc.convert(access, oldBath);
145                                 if(bath!=oldBath) {
146                                         bath = Symm.base64noSplit.decode(bath.substring(6));
147                                         int colon = bath.indexOf(':');
148                                         if(colon>=0) {
149                                                 authUser = bath.substring(0, colon);
150                                                 authPassword = bath.substring(colon+1); 
151                                         }
152                                 }
153                         } catch (IOException e) {
154
155                                 logger.info(e.getMessage(), e);
156
157                         } 
158                 }
159                 String err;
160                 try {
161                         err = authn.validate(authUser,authPassword);
162                 } catch (IOException e) {
163                         err = "Credential cannot be validated";
164                         logger.info(e.getMessage(), e);
165                 }
166                 
167                 if(err != null) {
168                         logger.info(err);
169                         throw new AuthenticationException(err);
170                 }
171
172             return new AAFAuthenticationInfo(
173                         access,
174                         user,
175                         password
176             );
177         }
178
179         @Override
180         protected void assertCredentialsMatch(AuthenticationToken atoken, AuthenticationInfo ai)throws AuthenticationException {
181                 
182                 if(ai instanceof AAFAuthenticationInfo) {
183                         if(!((AAFAuthenticationInfo)ai).matches(atoken)) {
184                                 throw new AuthenticationException("Credentials do not match");
185
186                         }
187                         
188                 } else {
189                         throw new AuthenticationException("AuthenticationInfo is not an AAFAuthenticationInfo");
190                 
191                 }
192         }
193
194
195
196
197         @Override
198         protected AAFAuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
199                 Principal bait = (Principal)principals.getPrimaryPrincipal();
200                 Principal newBait = bait;
201                 if(idMap!=null) {
202                         final String newID = idMap.get(bait.getName());
203                         logger.info("Successful authentication attempt by " +bait.getName()); 
204                         if(newID!=null) {
205                                 newBait = new Principal() {
206                                         @Override
207                                         public String getName() {
208                                                 return newID;
209                                         }
210                                 };
211                         }
212                 }
213                 List<Permission> pond = new ArrayList<>();
214                 authz.fishAll(newBait,pond);
215                 return new AAFAuthorizationInfo(access,bait,pond);
216        
217         }
218
219         @Override
220         public boolean supports(AuthenticationToken token) {
221                 return supports.contains(token.getClass());
222         }
223
224         @Override
225         public String getName() {
226                 return AAF_REALM;
227         }
228
229 }