changed to unmaintained
[aaf/authz.git] / auth / auth-cass / src / main / java / org / onap / aaf / auth / dao / hl / Question.java
index 3abad1a..2e8e55f 100644 (file)
@@ -7,9 +7,9 @@
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -26,13 +26,13 @@ import java.nio.ByteBuffer;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
 import java.util.ArrayList;
-import java.util.Collections;
+import java.util.Collection;
 import java.util.Date;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
-import java.util.Random;
 import java.util.Set;
+import java.util.TreeMap;
 import java.util.TreeSet;
 
 import org.onap.aaf.auth.common.Define;
@@ -45,6 +45,7 @@ import org.onap.aaf.auth.dao.cached.CachedNSDAO;
 import org.onap.aaf.auth.dao.cached.CachedPermDAO;
 import org.onap.aaf.auth.dao.cached.CachedRoleDAO;
 import org.onap.aaf.auth.dao.cached.CachedUserRoleDAO;
+import org.onap.aaf.auth.dao.cached.FileGetter;
 import org.onap.aaf.auth.dao.cass.ApprovalDAO;
 import org.onap.aaf.auth.dao.cass.CacheInfoDAO;
 import org.onap.aaf.auth.dao.cass.CertDAO;
@@ -80,9 +81,9 @@ import com.datastax.driver.core.Cluster;
 
 /**
  * Question HL DAO
- * 
+ *
  * A Data Access Combination Object which asks Security and other Questions
- * 
+ *
  * @author Jonathan
  *
  */
@@ -124,7 +125,7 @@ public class Question {
     static Slot PERMS;
 
     private static Set<String> specialLog = null;
-    public static final Random random = new SecureRandom();
+    public static final SecureRandom random = new SecureRandom();
     private static long traceID = random.nextLong();
     private static Slot specialLogSlot = null;
     private static Slot transIDSlot = null;
@@ -132,62 +133,62 @@ public class Question {
 
     private final HistoryDAO historyDAO;
     public HistoryDAO historyDAO() {
-       return historyDAO;
+        return historyDAO;
     }
-    
+
     private final CachedNSDAO nsDAO;
     public CachedNSDAO nsDAO() {
-       return nsDAO;
+        return nsDAO;
     }
-    
+
     private final CachedRoleDAO roleDAO;
     public CachedRoleDAO roleDAO() {
-       return roleDAO;
+        return roleDAO;
     }
-    
+
     private final CachedPermDAO permDAO;
     public CachedPermDAO permDAO() {
-       return permDAO;
+        return permDAO;
     }
-    
+
     private final CachedUserRoleDAO userRoleDAO;
     public CachedUserRoleDAO userRoleDAO() {
-       return userRoleDAO;
+        return userRoleDAO;
     }
-    
+
     private final CachedCredDAO credDAO;
     public CachedCredDAO credDAO() {
-       return credDAO;
+        return credDAO;
     }
-    
+
     private final CachedCertDAO certDAO;
     public CachedCertDAO certDAO() {
-       return certDAO;
+        return certDAO;
     }
-    
+
     private final DelegateDAO delegateDAO;
     public DelegateDAO delegateDAO() {
-       return delegateDAO;
+        return delegateDAO;
     }
-    
+
     private final FutureDAO futureDAO;
     public FutureDAO futureDAO() {
-       return futureDAO;
+        return futureDAO;
     }
-    
+
     private final ApprovalDAO approvalDAO;
     public ApprovalDAO approvalDAO() {
-       return approvalDAO;
+        return approvalDAO;
     }
-    
+
     public final LocateDAO locateDAO;
     public LocateDAO locateDAO() {
-       return locateDAO;
+        return locateDAO;
     }
-    
+
     private final CacheInfoDAO cacheInfoDAO;
-       private final int cldays;
-       private final boolean alwaysSpecial;
+    private final int cldays;
+    private final boolean alwaysSpecial;
 
     public Question(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException {
         PERMS = trans.slot("USER_PERMS");
@@ -202,6 +203,8 @@ public class Question {
         permDAO = new CachedPermDAO(new PermDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn);
         roleDAO = new CachedRoleDAO(new RoleDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn);
         userRoleDAO = new CachedUserRoleDAO(new UserRoleDAO(trans, historyDAO,cacheInfoDAO), cacheInfoDAO, expiresIn);
+        // Create if aaf_file_cred exists with file
+        FileGetter.singleton(trans.env().access());
         credDAO = new CachedCredDAO(new CredDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn);
         certDAO = new CachedCertDAO(new CertDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn);
 
@@ -213,15 +216,40 @@ public class Question {
         if (specialLogSlot==null) {
             specialLogSlot = trans.slot(AuthzTransFilter.SPECIAL_LOG_SLOT);
         }
-        
+
         if (transIDSlot==null) {
             transIDSlot = trans.slot(AuthzTransFilter.TRANS_ID_SLOT);
         }
-        
+
         AbsCassDAO.primePSIs(trans);
-        
+
+        cldays = Integer.parseInt(trans.getProperty(Config.AAF_CRED_WARN_DAYS, Config.AAF_CRED_WARN_DAYS_DFT));
+
+        alwaysSpecial = Boolean.parseBoolean(trans.getProperty("aaf_always_special", Boolean.FALSE.toString()));
+    }
+
+    /**
+     * Note: This Constructor created for JUNIT Purposes.  Do not use otherwise.
+     */
+    public Question(AuthzTrans trans, HistoryDAO historyDAO, CacheInfoDAO cacheInfoDAO,
+            CachedNSDAO nsDAO, CachedPermDAO permDAO, CachedRoleDAO roleDAO,
+            CachedUserRoleDAO userRoleDAO, CachedCredDAO credDAO, CachedCertDAO certDAO,
+            LocateDAO locateDAO,FutureDAO futureDAO, DelegateDAO delegateDAO,
+            ApprovalDAO approvalDAO ) {
+        this.historyDAO = historyDAO;
+        this.cacheInfoDAO = cacheInfoDAO;
+        this.nsDAO = nsDAO;
+        this.permDAO = permDAO;
+        this.roleDAO = roleDAO;
+        this.userRoleDAO = userRoleDAO;
+        this.credDAO = credDAO;
+        this.certDAO = certDAO;
+        this.locateDAO = locateDAO;
+        this.futureDAO = futureDAO;
+        this.delegateDAO = delegateDAO;
+        this.approvalDAO = approvalDAO;
+
         cldays = Integer.parseInt(trans.getProperty(Config.AAF_CRED_WARN_DAYS, Config.AAF_CRED_WARN_DAYS_DFT));
-        
         alwaysSpecial = Boolean.parseBoolean(trans.getProperty("aaf_always_special", Boolean.FALSE.toString()));
     }
 
@@ -231,7 +259,7 @@ public class Question {
         CachedDAO.startCleansing(env, credDAO, userRoleDAO);
         CachedDAO.startRefresh(env, cacheInfoDAO);
     }
-    
+
     public void close(AuthzTrans trans) {
         historyDAO.close(trans);
         cacheInfoDAO.close(trans);
@@ -246,23 +274,37 @@ public class Question {
         approvalDAO.close(trans);
     }
 
-    public Result<PermDAO.Data> permFrom(AuthzTrans trans, String type,
-            String instance, String action) {
-        Result<NsDAO.Data> rnd = deriveNs(trans, type);
-        if (rnd.isOK()) {
-            return Result.ok(new PermDAO.Data(new NsSplit(rnd.value, type),
-                    instance, action));
+    public Result<PermDAO.Data> permFrom(AuthzTrans trans, String type, String instance, String action) {
+        if(type.indexOf('@') >= 0) {
+            int colon = type.indexOf(':');
+            if(colon>=0) {
+                PermDAO.Data pdd = new PermDAO.Data();
+                pdd.ns = type.substring(0, colon);
+                pdd.type = type.substring(colon+1);
+                pdd.instance = instance;
+                pdd.action = action;
+
+                return Result.ok(pdd);
+            } else {
+                return Result.err(Result.ERR_BadData,"Could not extract ns and type from " + type);
+            }
         } else {
-            return Result.err(rnd);
+            Result<NsDAO.Data> rnd = deriveNs(trans, type);
+            if (rnd.isOK()) {
+                return Result.ok(new PermDAO.Data(new NsSplit(rnd.value, type),
+                        instance, action));
+            } else {
+                return Result.err(rnd);
+            }
         }
     }
 
     /**
      * getPermsByUser
-     * 
+     *
      * Because this call is frequently called internally, AND because we already
      * look for it in the initial Call, we cache within the Transaction
-     * 
+     *
      * @param trans
      * @param user
      * @return
@@ -270,26 +312,26 @@ public class Question {
     public Result<List<PermDAO.Data>> getPermsByUser(AuthzTrans trans, String user, boolean lookup) {
         return PermLookup.get(trans, this, user).getPerms(lookup);
     }
-    
+
     public Result<List<PermDAO.Data>> getPermsByUserFromRolesFilter(AuthzTrans trans, String user, String forUser) {
         PermLookup plUser = PermLookup.get(trans, this, user);
         Result<Set<String>> plPermNames = plUser.getPermNames();
         if (plPermNames.notOK()) {
             return Result.err(plPermNames);
         }
-        
+
         Set<String> nss;
         if (forUser.equals(user)) {
             nss = null;
         } else {
-            // Setup a TreeSet to check on Namespaces to 
+            // Setup a TreeSet to check on Namespaces to
             nss = new TreeSet<>();
             PermLookup fUser = PermLookup.get(trans, this, forUser);
             Result<Set<String>> forUpn = fUser.getPermNames();
             if (forUpn.notOK()) {
                 return Result.err(forUpn);
             }
-            
+
             for (String pn : forUpn.value) {
                 Result<String[]> decoded = PermDAO.Data.decodeToArray(trans, this, pn);
                 if (decoded.isOKhasData()) {
@@ -314,33 +356,42 @@ public class Question {
                 trans.error().log(pn,", derived from a Role, is invalid.  Run Data Cleanup:",rpdd.errorString());
             }
         }
-        return Result.ok(rlpUser); 
+        return Result.ok(rlpUser);
     }
 
-    public Result<List<PermDAO.Data>> getPermsByType(AuthzTrans trans, String perm) {
-        Result<NsSplit> nss = deriveNsSplit(trans, perm);
-        if (nss.notOK()) {
-            return Result.err(nss);
+    public Result<List<PermDAO.Data>> getPermsByType(AuthzTrans trans, String type) {
+        if(type.indexOf('@') >= 0) {
+            int colon = type.indexOf(':');
+            if(colon>=0) {
+                return permDAO.readByType(trans, type.substring(0, colon),type.substring(colon+1));
+            } else {
+                return Result.err(Result.ERR_BadData, "%s is malformed",type);
+            }
+        } else {
+            Result<NsSplit> nss = deriveNsSplit(trans, type);
+            if (nss.notOK()) {
+                return Result.err(nss);
+            }
+            return permDAO.readByType(trans, nss.value.ns, nss.value.name);
         }
-        return permDAO.readByType(trans, nss.value.ns, nss.value.name);
     }
 
     public Result<List<PermDAO.Data>> getPermsByName(AuthzTrans trans, String type, String instance, String action) {
-       if(type.indexOf('@') >= 0) {
-               int colon = type.indexOf(':');
-               if(colon>=0) {
-                       return permDAO.read(trans, type.substring(0, colon),type.substring(colon+1), instance,action);
-               } else {
-                       return Result.err(Result.ERR_BadData, "%s is malformed",type);
-               }
-       } else {
-               Result<NsSplit> nss = deriveNsSplit(trans, type);
-               if (nss.notOK()) {
-                   return Result.err(nss);
-               }
-               
-               return permDAO.read(trans, nss.value.ns, nss.value.name, instance,action);
-       }
+        if(type.indexOf('@') >= 0) {
+            int colon = type.indexOf(':');
+            if(colon>=0) {
+                return permDAO.read(trans, type.substring(0, colon),type.substring(colon+1), instance,action);
+            } else {
+                return Result.err(Result.ERR_BadData, "%s is malformed",type);
+            }
+        } else {
+            Result<NsSplit> nss = deriveNsSplit(trans, type);
+            if (nss.notOK()) {
+                return Result.err(nss);
+            }
+
+            return permDAO.read(trans, nss.value.ns, nss.value.name, instance,action);
+        }
     }
 
     public Result<List<PermDAO.Data>> getPermsByRole(AuthzTrans trans, String role, boolean lookup) {
@@ -387,13 +438,13 @@ public class Question {
     }
 
     public Result<List<RoleDAO.Data>> getRolesByName(AuthzTrans trans, String role) {
-       if(role.startsWith(trans.user()) ) {
-               if(role.endsWith(":user")) {
-                       return roleDAO.read(trans,trans.user(), "user");
-               } else {
-                       return Result.err(Result.ERR_BadData,"%s is a badly formatted role",role);
-               }
-       }
+        if(role.startsWith(trans.user()) ) {
+            if(role.endsWith(":user")) {
+                return roleDAO.read(trans,trans.user(), "user");
+            } else {
+                return Result.err(Result.ERR_BadData,"%s is a badly formatted role",role);
+            }
+        }
         Result<NsSplit> nss = deriveNsSplit(trans, role);
         if (nss.notOK()) {
             return Result.err(nss);
@@ -411,22 +462,22 @@ public class Question {
 
     /**
      * Derive NS
-     * 
+     *
      * Given a Child Namespace, figure out what the best Namespace parent is.
-     * 
+     *
      * For instance, if in the NS table, the parent "org.osaaf" exists, but not
      * "org.osaaf.child" or "org.osaaf.a.b.c", then passing in either
      * "org.osaaf.child" or "org.osaaf.a.b.c" will return "org.osaaf"
-     * 
+     *
      * Uses recursive search on Cached DAO data
-     * 
+     *
      * @param trans
      * @param child
      * @return
      */
     public Result<NsDAO.Data> deriveNs(AuthzTrans trans, String child) {
         Result<List<NsDAO.Data>> r = nsDAO.read(trans, child);
-        
+
         if (r.isOKhasData()) {
             return Result.ok(r.value.get(0));
         } else {
@@ -451,7 +502,7 @@ public class Question {
                     return Result.ok(nsd);
                 } else {
                     int dot = str.lastIndexOf('.');
-                    
+
                     if (dot < 0) {
                         return Result.err(Status.ERR_NsNotFound, "No Namespace for [%s]", str);
                     } else {
@@ -460,7 +511,7 @@ public class Question {
                 }
             } else {
                 int dot = str.lastIndexOf('.');
-                
+
                 if (dot < 0) {
                     return Result.err(Status.ERR_NsNotFound,"There is no valid Company Namespace for %s",str);
                 } else {
@@ -488,9 +539,9 @@ public class Question {
 
     /**
      * Translate an ID into it's domain
-     * 
+     *
      * i.e. myid1234@aaf.att.com results in domain of com.att.aaf
-     * 
+     *
      * @param id
      * @return
      */
@@ -517,9 +568,9 @@ public class Question {
 
     /**
      * Validate Namespace of ID@Domain
-     * 
+     *
      * Namespace is reverse order of Domain.
-     * 
+     *
      * @param trans
      * @param id
      * @return
@@ -533,7 +584,7 @@ public class Question {
             ns = domain2ns(id);
         }
         if (ns.length() > 0) {
-            if (!trans.org().getDomain().equals(ns)) { 
+            if (!trans.org().getDomain().equals(ns)) {
                 Result<List<NsDAO.Data>> rlnsd = nsDAO.read(trans, ns);
                 if (rlnsd.isOKhasData()) {
                     return Result.ok(rlnsd.value.get(0));
@@ -547,33 +598,41 @@ public class Question {
     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, Access access) {
         // <ns>.access|:role:<role name>|<read|write>
         String ns = ndd.name;
+        boolean isRoot = ns.startsWith(Define.ROOT_NS());
         int last;
         do {
             if (isGranted(trans, user, ns, ACCESS, ":ns", access.name())) {
                 return Result.ok(ndd);
             }
+            if(isRoot) {
+                break;
+            }
             if ((last = ns.lastIndexOf('.')) >= 0) {
                 ns = ns.substring(0, last);
             }
         } while (last >= 0);
-        // com.att.aaf.ns|:<client ns>:ns|<access>
-        // AAF-724 - Make consistent response for May User", and not take the
-        // last check... too confusing.
-        Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":"    + ndd.name + ":ns", access.name());
-        if (rv.isOK()) {
-            return rv;
-        } else if (rv.status==Result.ERR_Backend) {
-            return Result.err(rv);
-        } else {
-            return Result.err(Status.ERR_Denied, "[%s] may not %s in NS [%s]",
-                    user, access.name(), ndd.name);
-        }
+
+        // SAFETY - Do not allow these when NS is Root
+        if(!isRoot) {
+            // com.att.aaf.ns|:<client ns>:ns|<access>
+            // AAF-724 - Make consistent response for May User", and not take the
+            // last check... too confusing.
+            Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":"    + ndd.name + ":ns", access.name());
+                if (rv.isOK()) {
+                    return rv;
+                } else if (rv.status==Result.ERR_Backend) {
+                    return Result.err(rv);
+                }
+            }
+        return Result.err(Status.ERR_Denied, "[%s] may not %s in NS [%s]",
+                user, access.name(), ndd.name);
+
     }
 
     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, RoleDAO.Data rdd, Access access) {
-       if(trans.user().equals(rdd.ns)) {
-               return Result.ok((NsDAO.Data)null);
-       }
+        if(trans.user().equals(rdd.ns)) {
+            return Result.ok((NsDAO.Data)null);
+        }
         Result<NsDAO.Data> rnsd = deriveNs(trans, rdd.ns);
         if (rnsd.isOK()) {
             return mayUser(trans, user, rnsd.value, rdd, access);
@@ -582,63 +641,70 @@ public class Question {
     }
 
     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, NsDAO.Data ndd, RoleDAO.Data rdd, Access access) {
-        // 1) Is User in the Role?
-        Result<List<UserRoleDAO.Data>> rurd = userRoleDAO.readUserInRole(trans, user, rdd.fullName());
-        if (rurd.isOKhasData()) {
-            return Result.ok(ndd);
+        // 1) For "read", Is User in the Role is enough
+        if(Access.read.equals(access)) {
+            Result<List<UserRoleDAO.Data>> rurd = userRoleDAO.readUserInRole(trans, user, rdd.fullName());
+            if (rurd.isOKhasData()) {
+                return Result.ok(ndd);
+            }
         }
 
         String roleInst = ":role:" + rdd.name;
         // <ns>.access|:role:<role name>|<read|write>
         String ns = rdd.ns;
+        boolean isRoot = ns.startsWith(Define.ROOT_NS());
         int last;
         do {
             if (isGranted(trans, user, ns,ACCESS, roleInst, access.name())) {
                 return Result.ok(ndd);
             }
+            if(isRoot) {
+                break;
+            }
             if ((last = ns.lastIndexOf('.')) >= 0) {
                 ns = ns.substring(0, last);
             }
         } while (last >= 0);
 
-        // Check if Access by Global Role perm
-        // com.att.aaf.ns|:<client ns>:role:name|<access>
-        Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":"
-                + rdd.ns + roleInst, access.name());
-        if (rnsd.isOK()) {
-            return rnsd;
-        } else if (rnsd.status==Result.ERR_Backend) {
-            return Result.err(rnsd);
-        }
+        // SAFETY - Do not allow these when NS is Root
+        if(!isRoot) {
+            // Check if Access by Global Role perm
+            // com.att.aaf.ns|:<client ns>:role:name|<access>
+            Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":"
+                    + rdd.ns + roleInst, access.name());
+            if (rnsd.isOK()) {
+                return rnsd;
+            } else if (rnsd.status==Result.ERR_Backend) {
+                return Result.err(rnsd);
+            }
 
-        // Check if Access to Whole NS
-        // AAF-724 - Make consistent response for May User", and not take the
-        // last check... too confusing.
-        Result<org.onap.aaf.auth.dao.cass.NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, 
-                ":" + rdd.ns + ":ns", access.name());
-        if (rv.isOK()) {
-            return rv;
-        } else if (rnsd.status==Result.ERR_Backend) {
-            return Result.err(rnsd);
-        } else {
-            return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]",
-                    user, access.name(), rdd.fullName());
+            // Check if Access to Whole NS
+            // AAF-724 - Make consistent response for May User", and not take the
+            // last check... too confusing.
+            Result<org.onap.aaf.auth.dao.cass.NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd,
+                    ":" + rdd.ns + ":ns", access.name());
+            if (rv.isOK()) {
+                return rv;
+            } else if (rnsd.status==Result.ERR_Backend) {
+                return Result.err(rnsd);
+            }
         }
-
+        return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]",
+                    user, access.name(), rdd.fullName());
     }
 
     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,PermDAO.Data pdd, Access access) {
-       if(pdd.ns.indexOf('@')>-1) {
-               if(user.equals(pdd.ns) || isGranted(trans,user,Define.ROOT_NS(),"access",pdd.instance,READ)) {
-                       NsDAO.Data ndd = new NsDAO.Data();
-                       ndd.name = user;
-                       ndd.type = NsDAO.USER;
-                       ndd.parent = "";
-                       return Result.ok(ndd);
-               } else {
-                       return Result.err(Result.ERR_Security,"Only a User may modify User");
-               }
-       }
+        if(pdd.ns.indexOf('@')>-1) {
+            if(user.equals(pdd.ns) || isGranted(trans,user,Define.ROOT_NS(),"access",pdd.instance,READ)) {
+                NsDAO.Data ndd = new NsDAO.Data();
+                ndd.name = user;
+                ndd.type = NsDAO.USER;
+                ndd.parent = "";
+                return Result.ok(ndd);
+            } else {
+                return Result.err(Result.ERR_Security,"Only a User may modify User");
+            }
+        }
         Result<NsDAO.Data> rnsd = deriveNs(trans, pdd.ns);
         if (rnsd.isOK()) {
             return mayUser(trans, user, rnsd.value, pdd, access);
@@ -647,43 +713,50 @@ public class Question {
     }
 
     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, PermDAO.Data pdd, Access access) {
+        // Most common occurrence... if granted Permission
         if (isGranted(trans, user, pdd.ns, pdd.type, pdd.instance, pdd.action)) {
             return Result.ok(ndd);
         }
+
         String permInst = ":perm:" + pdd.type + ':' + pdd.instance + ':' + pdd.action;
         // <ns>.access|:role:<role name>|<read|write>
         String ns = ndd.name;
+        boolean isRoot = ns.startsWith(Define.ROOT_NS());
         int last;
         do {
             if (isGranted(trans, user, ns, ACCESS, permInst, access.name())) {
                 return Result.ok(ndd);
             }
+            if(isRoot) {
+                break;
+            }
             if ((last = ns.lastIndexOf('.')) >= 0) {
                 ns = ns.substring(0, last);
             }
         } while (last >= 0);
 
-        // Check if Access by NS perm
-        // com.att.aaf.ns|:<client ns>:role:name|<access>
-        Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + permInst, access.name());
-        if (rnsd.isOK()) {
-            return rnsd;
-        } else if (rnsd.status==Result.ERR_Backend) {
-            return Result.err(rnsd);
-        }
+        // SAFETY - Do not allow these when NS is Root
+        if(!isRoot) {
+            // Check if Access by NS perm
+            // com.att.aaf.ns|:<client ns>:role:name|<access>
+            Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + permInst, access.name());
+            if (rnsd.isOK()) {
+                return rnsd;
+            } else if (rnsd.status==Result.ERR_Backend) {
+                return Result.err(rnsd);
+            }
 
-        // Check if Access to Whole NS
-        // AAF-724 - Make consistent response for May User", and not take the
-        // last check... too confusing.
-        Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":"    + pdd.ns + ":ns", access.name());
-        if (rv.isOK()) {
-            return rv;
-        } else {
-            return Result.err(Status.ERR_Denied,
-                    "[%s] may not %s Perm [%s|%s|%s]", user, access.name(),
-                    pdd.fullType(), pdd.instance, pdd.action);
+            // Check if Access to Whole NS
+            // AAF-724 - Make consistent response for May User", and not take the
+            // last check... too confusing.
+            Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":"    + pdd.ns + ":ns", access.name());
+            if (rv.isOK()) {
+                return rv;
+            }
         }
-
+        return Result.err(Status.ERR_Denied,
+                "[%s] may not %s Perm [%s|%s|%s]", user, access.name(),
+                pdd.fullType(), pdd.instance, pdd.action);
     }
 
     public Result<Void> mayUser(AuthzTrans trans, DelegateDAO.Data dd, Access access) {
@@ -713,16 +786,22 @@ public class Question {
                     return Result.err(Status.ERR_BadData,
                             "[%s] cannot be a delegate for self", dd.user);
                 }
-                if (!isUser    && !isGranted(trans, trans.user(), ROOT_NS,DELG,
-                                org.getDomain(), Question.CREATE)) {
-                    return Result.err(Status.ERR_Denied,
+                if (!isUser) {
+                       String supportedDomain = org.supportedDomain(dd.user);
+                       if(supportedDomain==null) {
+                        return Result.err(Status.ERR_Denied,
+                                "[%s] may not create a delegate for the domain for [%s]",
+                                trans.user(), dd.user);
+                       } else if(!isGranted(trans, trans.user(), ROOT_NS,DELG,supportedDomain,Question.CREATE)) {
+                               return Result.err(Status.ERR_Denied,
                             "[%s] may not create a delegate for [%s]",
                             trans.user(), dd.user);
+                       }
                 }
                 break;
             case read:
             case write:
-                if (!isUser    && !isDelegate && 
+                if (!isUser    && !isDelegate &&
                         !isGranted(trans, trans.user(), ROOT_NS,DELG,org.getDomain(), access.name())) {
                     return Result.err(Status.ERR_Denied,
                             "[%s] may not %s delegates for [%s]", trans.user(),
@@ -745,14 +824,14 @@ public class Question {
         String ns = nsd.name;
 
         // If an ADMIN of the Namespace, then allow
-        
+
         Result<List<UserRoleDAO.Data>> rurd;
         if ((rurd = userRoleDAO.readUserInRole(trans, user, ns+DOT_ADMIN)).isOKhasData()) {
             return Result.ok(nsd);
         } else if (rurd.status==Result.ERR_Backend) {
             return Result.err(rurd);
         }
-        
+
         // If Specially granted Global Permission
         if (isGranted(trans, user, ROOT_NS,NS, ns_and_type, access)) {
             return Result.ok(nsd);
@@ -778,13 +857,13 @@ public class Question {
                 ns_and_type);
     }
 
-    
+
     /**
      * isGranted
-     * 
+     *
      * Important function - Check internal Permission Schemes for Permission to
      * do things
-     * 
+     *
      * @param trans
      * @param type
      * @param instance
@@ -798,7 +877,7 @@ public class Question {
                 if (ns.equals(pd.ns)) {
                     if (type.equals(pd.type)) {
                         if (PermEval.evalInstance(pd.instance, instance)) {
-                            if (PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action 
+                            if (PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action
                                 return true;
                             }
                         }
@@ -813,7 +892,7 @@ public class Question {
         Result<List<CredDAO.Data>> result;
         TimeTaken tt = trans.start("Read DB Cred", Env.REMOTE);
         try {
-            result = credDAO.readID(trans, user);
+            result = credDAO.readIDBAth(trans, user);
         } finally {
             tt.done();
         }
@@ -827,31 +906,41 @@ public class Question {
                 }
             } else {
                 Date now = new Date();
-                // Bug noticed 6/22. Sorting on the result can cause Concurrency Issues.     
-                List<CredDAO.Data> cddl;
+                // Bug noticed 6/22. Sorting on the result can cause Concurrency Issues.
+                // 9/14/2019. Use TreeSet for sorting, and using only the LAST of a Tagged entry
+                Collection<CredDAO.Data> cddl;
                 if (result.value.size() > 1) {
-                    cddl = new ArrayList<>(result.value.size());
-                    for (CredDAO.Data old : result.value) {
-                        if (old.type==CredDAO.BASIC_AUTH || old.type==CredDAO.BASIC_AUTH_SHA256) {
-                            cddl.add(old);
+                    Map<String,CredDAO.Data> mcdd = new TreeMap<>();
+                    CredDAO.Data cdd;
+                    String tag;
+                    int pseudoTag = 0;
+                    for (CredDAO.Data rcdd : result.value) {
+                        if (rcdd.type==CredDAO.BASIC_AUTH || rcdd.type==CredDAO.BASIC_AUTH_SHA256) {
+                            if(rcdd.tag==null) {
+                                mcdd.put(Integer.toString(++pseudoTag),rcdd);
+                            } else {
+                                tag = rcdd.tag;
+                                cdd = mcdd.get(tag);
+                                if(cdd==null || cdd.expires.before(rcdd.expires)) {
+                                    mcdd.put(tag,rcdd);
+                                }
+                            }
                         }
                     }
-                    if (cddl.size()>1) {
-                       Collections.sort(cddl, (a, b) -> b.expires.compareTo(a.expires));
-                    }
+                    cddl = mcdd.values();
                 } else {
                     cddl = result.value;
                 }
-    
+
                 Date expired = null;
                 StringBuilder debug = willSpecialLog(trans,user)?new StringBuilder():null;
                 for (CredDAO.Data cdd : cddl) {
                     if (!cdd.id.equals(user)) {
                         trans.error().log("doesUserCredMatch DB call does not match for user: " + user);
                     }
-                    if (cdd.expires.after(now)) {
+                    if (cdd.expires.after(now) || trans.org().isUserExpireExempt(cdd.id, cdd.expires)) {
                         byte[] dbcred = cdd.cred.array();
-                        
+
                         try {
                             switch(cdd.type) {
                                 case CredDAO.BASIC_AUTH:
@@ -869,7 +958,7 @@ public class Question {
                                     bb.putInt(cdd.other);
                                     bb.put(cred);
                                     byte[] hash = Hash.hashSHA256(bb.array());
-    
+
                                     if (Hash.compareTo(hash,dbcred)==0) {
                                         checkLessThanDays(trans,cldays,now,cdd);
                                         trans.setTag(cdd.tag);
@@ -891,19 +980,19 @@ public class Question {
                         }
                     }
                 } // end for each
-                
+
                 if (expired!=null) {
                     // Note: this is only returned if there are no good Credentials
                     rv = Result.err(Status.ERR_Security,
                             "Credentials expired %s",Chrono.utcStamp(expired));
                 } else {
-                       if (debug==null && alwaysSpecial) {
-                               debug = new StringBuilder();
-                       }
-                       if (debug!=null) {
-                               debug.append(trans.env().encryptor().encrypt(new String(cred)));
-                               rv = Result.err(Status.ERR_Security,String.format("invalid password - %s",debug.toString()));
-                       }
+                    if (debug==null && alwaysSpecial) {
+                        debug = new StringBuilder();
+                    }
+                    if (debug!=null) {
+                        debug.append(trans.env().encryptor().encrypt(new String(cred)));
+                        rv = Result.err(Status.ERR_Security,String.format("invalid password - %s",debug.toString()));
+                    }
                 }
             }
         } else {
@@ -932,7 +1021,7 @@ public class Question {
         if (cexp<close) {
             int daysLeft = days-(int)((close-cexp)/86400000);
             trans.audit().printf("user=%s,ip=%s,expires=%s,days=%d,tag=%s,msg=\"Password expires in less than %d day%s\"",
-                cdd.id,trans.ip(),Chrono.dateOnlyStamp(cdd.expires),daysLeft, cdd.tag, 
+                cdd.id,trans.ip(),Chrono.dateOnlyStamp(cdd.expires),daysLeft, cdd.tag,
                 daysLeft,daysLeft==1?"":"s");
         }
     }
@@ -955,34 +1044,36 @@ public class Question {
             } finally {
                 tt.done();
             }
-            
+
         } else if (cred.type==CredDAO.FQI) {
-               cred.cred = null;
-               return Result.ok(cred);
+            cred.cred = null;
+            return Result.ok(cred);
         }
         return Result.err(Status.ERR_Security,"invalid/unreadable credential");
     }
-    
+
     public Result<Boolean> userCredCheck(AuthzTrans trans, CredDAO.Data orig, final byte[] raw) {
-            TimeTaken tt = trans.start("CheckCred Cred", Env.SUB);
-            try {
-                switch(orig.type) {
-                    case CredDAO.BASIC_AUTH_SHA256:
-                        ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + raw.length);
-                        bb.putInt(orig.other);
-                        bb.put(raw);
-                        return Result.ok(Hash.compareTo(orig.cred.array(),Hash.hashSHA256(bb.array()))==0);
-                    case CredDAO.BASIC_AUTH:
-                        return Result.ok( Hash.compareTo(orig.cred.array(), Hash.hashMD5(raw))==0);
-                    case CredDAO.FQI:
-                    default:
-                        return Result.ok(false);
-                }
-            } catch (NoSuchAlgorithmException e) {
-                return Result.err(Status.ERR_General,e.getLocalizedMessage());
-            } finally {
-                tt.done();
+        Result<Boolean> rv;
+        TimeTaken tt = trans.start("CheckCred Cred", Env.SUB);
+        try {
+            switch(orig.type) {
+                case CredDAO.BASIC_AUTH_SHA256:
+                    ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + raw.length);
+                    bb.putInt(orig.other);
+                    bb.put(raw);
+                    rv = Result.ok(Hash.compareTo(orig.cred.array(),Hash.hashSHA256(bb.array()))==0);
+                case CredDAO.BASIC_AUTH:
+                    rv= Result.ok( Hash.compareTo(orig.cred.array(), Hash.hashMD5(raw))==0);
+                case CredDAO.FQI:
+                default:
+                    rv = Result.ok(false);
             }
+        } catch (NoSuchAlgorithmException e) {
+            rv = Result.err(Status.ERR_General,e.getLocalizedMessage());
+        } finally {
+            tt.done();
+        }
+        return rv;
     }
 
     public static final String APPROVED = "APPROVE";
@@ -1120,7 +1211,7 @@ public class Question {
         }
         return b;
     }
-    
+
     public static void logEncryptTrace(AuthzTrans trans, String data) {
         long ti;
         trans.put(transIDSlot, ti=nextTraceID());
@@ -1137,7 +1228,7 @@ public class Question {
         }
         boolean rc = specialLog.add(id);
         if (rc) {
-            trans.trace().printf("Trace on for %s requested by %s",id,trans.user());            
+            trans.trace().printf("Trace on for %s requested by %s",id,trans.user());
         }
         return rc;
     }
@@ -1151,12 +1242,12 @@ public class Question {
             specialLog = null;
         }
         if (rv) {
-            trans.trace().printf("Trace off for %s requested by %s",id,trans.user());            
+            trans.trace().printf("Trace off for %s requested by %s",id,trans.user());
         }
         return rv;
     }
 
-    /** 
+    /**
      * canMove
      * Which Types can be moved
      * @param nsType
@@ -1178,23 +1269,23 @@ public class Question {
     }
 
     public boolean isAdmin(AuthzTrans trans, String user, String ns) {
-        Date now = new Date();
         Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_ADMIN);
         if (rur.isOKhasData()) {
-               for (UserRoleDAO.Data urdd : rur.value){
-                   if (urdd.expires.after(now)) {
-                       return true;
-                   }
-               }
+            Date now = new Date();
+            for (UserRoleDAO.Data urdd : rur.value){
+                if (urdd.expires.after(now) || trans.org().isUserExpireExempt(urdd.user, urdd.expires)) {
+                    return true;
+                }
+            }
         };
         return false;
     }
-    
+
     public boolean isOwner(AuthzTrans trans, String user, String ns) {
-        Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_OWNER);
-        Date now = new Date();
+        Result<List<UserRoleDAO.Data>> rur = userRoleDAO().read(trans, user,ns+DOT_OWNER);
         if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){
-            if (urdd.expires.after(now)) {
+            Date now = new Date();
+            if (urdd.expires.after(now) || trans.org().isUserExpireExempt(urdd.user, urdd.expires)) {
                 return true;
             }
         }};
@@ -1202,24 +1293,24 @@ public class Question {
     }
 
     public int countOwner(AuthzTrans trans, String ns) {
-        Result<List<UserRoleDAO.Data>> rur = userRoleDAO.readByRole(trans,ns+DOT_OWNER);
+        Result<List<UserRoleDAO.Data>> rur = userRoleDAO().readByRole(trans,ns+DOT_OWNER);
         Date now = new Date();
         int count = 0;
         if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){
-            if (urdd.expires.after(now)) {
+            if (urdd.expires.after(now) || trans.org().isUserExpireExempt(urdd.user, urdd.expires)) {
                 ++count;
             }
         }};
         return count;
     }
-    
+
     /**
      * Return a Unique String, (same string, if it is already unique), with only
      * lowercase letters, digits and the '.' character.
-     * 
+     *
      * @param name
      * @return
-     * @throws IOException 
+     * @throws IOException
      */
     public static String toUnique(String name) throws IOException {
         byte[] from = name.getBytes();
@@ -1232,7 +1323,7 @@ public class Question {
         }
         return sb.toString();
     }
-    
+
     public static String fromUnique(String name) throws IOException {
         byte[] from = name.getBytes();
         StringBuilder sb = new StringBuilder();