2 * ============LICENSE_START====================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
21 package org.onap.aaf.cadi.shiro;
23 import java.io.IOException;
24 import java.security.Principal;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.TreeMap;
32 import org.apache.shiro.authc.AuthenticationException;
33 import org.apache.shiro.authc.AuthenticationInfo;
34 import org.apache.shiro.authc.AuthenticationToken;
35 import org.apache.shiro.authc.UsernamePasswordToken;
36 import org.apache.shiro.authz.AuthorizationInfo;
37 import org.apache.shiro.realm.AuthorizingRealm;
38 import org.apache.shiro.subject.PrincipalCollection;
39 import org.onap.aaf.cadi.Access.Level;
40 import org.onap.aaf.cadi.CadiException;
41 import org.onap.aaf.cadi.LocatorException;
42 import org.onap.aaf.cadi.Permission;
43 import org.onap.aaf.cadi.PropAccess;
44 import org.onap.aaf.cadi.Symm;
45 import org.onap.aaf.cadi.aaf.AAFPermission;
46 import org.onap.aaf.cadi.aaf.v2_0.AAFAuthn;
47 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
48 import org.onap.aaf.cadi.aaf.v2_0.AAFLurPerm;
49 import org.onap.aaf.cadi.config.Config;
50 import org.onap.aaf.cadi.filter.MapBathConverter;
51 import org.onap.aaf.cadi.util.CSV;
52 import org.onap.aaf.cadi.util.Split;
53 import org.onap.aaf.misc.env.APIException;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * Note: Shiro Realm document
59 * https://shiro.apache.org/realm.html
62 public class AAFRealm extends AuthorizingRealm {
63 public static final String AAF_REALM = "AAFRealm";
64 private static final Logger logger = LoggerFactory.getLogger(AAFRealm.class);
67 static Singleton singleton = Singleton.singleton();
69 public static class Singleton {
70 public AAFCon<?> acon;
71 public AAFAuthn<?> authn;
72 public AAFLurPerm authz;
73 // private Set<Class<? extends AuthenticationToken>> supports;
75 private MapBathConverter mbc;
76 private Map<String,String> idMap;
78 logger.info("Creating AAFRealm.Singleton");
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 access.log(Level.INFO,msg);
85 throw new RuntimeException(msg);
88 acon = AAFCon.newInstance(access);
89 authn = acon.newAuthn();
90 authz = acon.newLur(authn);
92 final String csv = access.getProperty(Config.CADI_BATH_CONVERT);
95 mbc = new MapBathConverter(access, new CSV(access,csv));
96 access.log(Level.INFO, "MapBathConversion enabled with file ",csv);
97 idMap = Collections.synchronizedMap(new TreeMap<String,String>());
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(':');
105 oldID = oldID.substring(0, idx);
108 String newID = es.getValue();
109 if(newID.startsWith("Basic ")) {
110 newID = Symm.base64noSplit.decode(newID.substring(6));
111 int idx = newID.indexOf(':');
113 newID = newID.substring(0, idx);
116 idMap.put(oldID,newID);
118 } catch (IOException e) {
122 } catch (APIException | CadiException | LocatorException e) {
123 String msg = "Cannot initiate AAFRealm";
124 access.log(Level.ERROR,e,msg);
125 throw new RuntimeException(msg,e);
129 // There is only one of these. If there are more, put back
130 // supports = Collections.synchronizedSet(new HashSet<>());
131 // supports.add(UsernamePasswordToken.class);
134 public static synchronized Singleton singleton() {
135 if(singleton==null) {
136 singleton = new Singleton();
141 // pick up cadi_prop_files from VM_Args
142 private final PropAccess access = new PropAccess() {
144 public void log(Exception e, Object... elements) {
145 logger.error(buildMsg(Level.ERROR, elements).toString(),e);
149 public void log(Level level, Object... elements) {
151 String str = buildMsg(level, elements).toString();
177 public void printf(Level level, String fmt, Object... elements) {
179 String str = String.format(fmt, elements);
205 public boolean willLog(Level level) {
206 if(super.willLog(level)) {
210 return logger.isWarnEnabled();
212 return logger.isDebugEnabled();
214 return logger.isErrorEnabled();
217 return logger.isInfoEnabled();
221 return logger.isTraceEnabled();
231 * There appears to be no configuration objects or references available for CADI to start with.
236 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
237 logger.debug("AAFRealm.doGetAuthenticationInfo");
238 final UsernamePasswordToken upt = (UsernamePasswordToken)token;
239 final String user = upt.getUsername();
240 String authUser = user;
241 final String password=new String(upt.getPassword());
242 String authPassword = password;
243 if(singleton.mbc!=null) {
245 final String oldBath = "Basic " + Symm.base64noSplit.encode(user+':'+password);
246 String bath = singleton.mbc.convert(singleton.access, oldBath);
248 bath = Symm.base64noSplit.decode(bath.substring(6));
249 int colon = bath.indexOf(':');
251 authUser = bath.substring(0, colon);
252 authPassword = bath.substring(colon+1);
255 } catch (IOException e) {
256 singleton.access.log(e);
261 err = singleton.authn.validate(authUser,authPassword);
263 singleton.access.log(Level.INFO, err);
264 throw new AuthenticationException(err);
267 } catch (IOException e) {
268 singleton.access.log(e,"Credential cannot be validated");
271 return new AAFAuthenticationInfo(
279 protected void assertCredentialsMatch(AuthenticationToken atoken, AuthenticationInfo ai)throws AuthenticationException {
280 logger.debug("AAFRealm.assertCredentialsMatch");
281 if(ai instanceof AAFAuthenticationInfo) {
282 if(!((AAFAuthenticationInfo)ai).matches(atoken)) {
283 throw new AuthenticationException("Credentials do not match");
286 throw new AuthenticationException("AuthenticationInfo is not an AAFAuthenticationInfo");
291 protected AAFAuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
292 logger.debug("AAFRealm.doGetAuthorizationInfo");
293 Principal bait = (Principal)principals.getPrimaryPrincipal();
294 Principal newBait = bait;
295 if(singleton.idMap!=null) {
296 final String newID = singleton.idMap.get(bait.getName());
298 singleton.access.printf(Level.INFO,"Successful authentication Translation %s to %s",bait.getName(), newID);
299 newBait = new Principal() {
301 public String getName() {
307 List<Permission> pond = new ArrayList<>();
308 singleton.authz.fishAll(newBait,pond);
309 return new AAFAuthorizationInfo(singleton.access,bait,pond);
313 public boolean supports(AuthenticationToken token) {
314 // Only one was being loaded. If more are needed uncomment the multi-class mode
315 return token instanceof UsernamePasswordToken;
316 // return singleton.supports.contains(token.getClass());
320 public String getName() {
324 private AAFPermission aafPerm(String permission) {
325 String[] pa = Split.splitTrim('|', permission);
328 return new AAFPermission(null,pa[0],pa[1],pa[2]);
330 return new AAFPermission(pa[0],pa[1],pa[2],pa[3]);
337 public boolean isPermitted(PrincipalCollection principals, String permission) {
338 logger.debug("AAFRealm.isPermitted(principals,permission<String>)");
339 AAFPermission ap = aafPerm(permission);
341 return singleton.authz.fish((Principal)principals.getPrimaryPrincipal(), ap);
347 protected boolean isPermitted(org.apache.shiro.authz.Permission permission, AuthorizationInfo info) {
348 logger.debug("AAFRealm.isPermitted(shiro.Permission,AuthorizationInfo)");
349 if(info instanceof AAFAuthorizationInfo) {
350 AAFPermission ap = aafPerm(permission.toString());
352 return singleton.authz.fish(((AAFAuthorizationInfo)info).principal(), ap);
356 return super.isPermitted(permission, info);
360 protected boolean[] isPermitted(List<org.apache.shiro.authz.Permission> permissions, AuthorizationInfo info) {
361 logger.debug("AAFRealm.isPermitted(List<shiro.Permission>,AuthorizationInfo)");
362 if(info instanceof AAFAuthorizationInfo) {
363 boolean rv[] = new boolean[permissions.size()];
365 for(org.apache.shiro.authz.Permission sp : permissions) {
366 AAFPermission ap = aafPerm(sp.toString());
368 rv[i++]=singleton.authz.fish(((AAFAuthorizationInfo)info).principal(), ap);
375 return super.isPermitted(permissions, info);