fix FirstNSbyType
[aaf/authz.git] / auth / auth-cass / src / main / java / org / onap / aaf / auth / dao / hl / Question.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.auth.dao.hl;
23
24 import java.io.IOException;
25 import java.nio.ByteBuffer;
26 import java.security.NoSuchAlgorithmException;
27 import java.security.SecureRandom;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.Comparator;
31 import java.util.Date;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Random;
36 import java.util.Set;
37 import java.util.TreeSet;
38
39 import org.onap.aaf.auth.common.Define;
40 import org.onap.aaf.auth.dao.AbsCassDAO;
41 import org.onap.aaf.auth.dao.CachedDAO;
42 import org.onap.aaf.auth.dao.DAOException;
43 import org.onap.aaf.auth.dao.cached.CachedCertDAO;
44 import org.onap.aaf.auth.dao.cached.CachedCredDAO;
45 import org.onap.aaf.auth.dao.cached.CachedNSDAO;
46 import org.onap.aaf.auth.dao.cached.CachedPermDAO;
47 import org.onap.aaf.auth.dao.cached.CachedRoleDAO;
48 import org.onap.aaf.auth.dao.cached.CachedUserRoleDAO;
49 import org.onap.aaf.auth.dao.cass.ApprovalDAO;
50 import org.onap.aaf.auth.dao.cass.CacheInfoDAO;
51 import org.onap.aaf.auth.dao.cass.CertDAO;
52 import org.onap.aaf.auth.dao.cass.CredDAO;
53 import org.onap.aaf.auth.dao.cass.CredDAO.Data;
54 import org.onap.aaf.auth.dao.cass.DelegateDAO;
55 import org.onap.aaf.auth.dao.cass.FutureDAO;
56 import org.onap.aaf.auth.dao.cass.HistoryDAO;
57 import org.onap.aaf.auth.dao.cass.LocateDAO;
58 import org.onap.aaf.auth.dao.cass.NsDAO;
59 import org.onap.aaf.auth.dao.cass.NsSplit;
60 import org.onap.aaf.auth.dao.cass.NsType;
61 import org.onap.aaf.auth.dao.cass.PermDAO;
62 import org.onap.aaf.auth.dao.cass.RoleDAO;
63 import org.onap.aaf.auth.dao.cass.Status;
64 import org.onap.aaf.auth.dao.cass.UserRoleDAO;
65 import org.onap.aaf.auth.env.AuthzTrans;
66 import org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE;
67 import org.onap.aaf.auth.env.AuthzTransFilter;
68 import org.onap.aaf.auth.layer.Result;
69 import org.onap.aaf.auth.org.Organization;
70 import org.onap.aaf.cadi.Hash;
71 import org.onap.aaf.cadi.aaf.PermEval;
72 import org.onap.aaf.cadi.config.Config;
73 import org.onap.aaf.misc.env.APIException;
74 import org.onap.aaf.misc.env.Env;
75 import org.onap.aaf.misc.env.Slot;
76 import org.onap.aaf.misc.env.TimeTaken;
77 import org.onap.aaf.misc.env.util.Chrono;
78
79 import com.datastax.driver.core.Cluster;
80
81 /**
82  * Question HL DAO
83  * 
84  * A Data Access Combination Object which asks Security and other Questions
85  * 
86  * @author Jonathan
87  *
88  */
89 public class Question {
90
91     // DON'T CHANGE FROM lower Case!!!
92     public static enum Type {
93         ns, role, perm, cred
94     };
95
96     public static final String OWNER="owner";
97     public static final String ADMIN="admin";
98     public static final String DOT_OWNER=".owner";
99     public static final String DOT_ADMIN=".admin";
100     public static final String ACCESS = "access";
101
102     static final String ASTERIX = "*";
103
104     public static enum Access {
105         read, write, create
106     };
107
108     public static final String READ = Access.read.name();
109     public static final String WRITE = Access.write.name();
110     public static final String CREATE = Access.create.name();
111
112     public static final String ROLE = Type.role.name();
113     public static final String PERM = Type.perm.name();
114     public static final String NS = Type.ns.name();
115     public static final String CRED = Type.cred.name();
116     private static final String DELG = "delg";
117     public static final String ROOT_NS = Define.isInitialized() ? Define.ROOT_NS() : "undefined";
118     public static final String ATTRIB = "attrib";
119
120
121     public static final int MAX_SCOPE = 10;
122     public static final int APP_SCOPE = 3;
123     public static final int COMPANY_SCOPE = 2;
124     static Slot PERMS;
125
126     private static Set<String> specialLog = null;
127     public static final Random random = new SecureRandom();
128     private static long traceID = random.nextLong();
129     private static Slot specialLogSlot = null;
130     private static Slot transIDSlot = null;
131
132
133     public final HistoryDAO historyDAO;
134     public final CachedNSDAO nsDAO;
135     public final CachedRoleDAO roleDAO;
136     public final CachedPermDAO permDAO;
137     public final CachedUserRoleDAO userRoleDAO;
138     public final CachedCredDAO credDAO;
139     public final CachedCertDAO certDAO;
140     public final DelegateDAO delegateDAO;
141     public final FutureDAO futureDAO;
142     public final ApprovalDAO approvalDAO;
143     private final CacheInfoDAO cacheInfoDAO;
144     public final LocateDAO locateDAO;
145
146     public Question(AuthzTrans trans, Cluster cluster, String keyspace, boolean startClean) throws APIException, IOException {
147         PERMS = trans.slot("USER_PERMS");
148         trans.init().log("Instantiating DAOs");
149         long expiresIn = Long.parseLong(trans.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF));
150         historyDAO = new HistoryDAO(trans, cluster, keyspace);
151
152         // Deal with Cached Entries
153         cacheInfoDAO = new CacheInfoDAO(trans, historyDAO);
154
155         nsDAO = new CachedNSDAO(new NsDAO(trans, historyDAO, cacheInfoDAO),cacheInfoDAO, expiresIn);
156         permDAO = new CachedPermDAO(new PermDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn);
157         roleDAO = new CachedRoleDAO(new RoleDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn);
158         userRoleDAO = new CachedUserRoleDAO(new UserRoleDAO(trans, historyDAO,cacheInfoDAO), cacheInfoDAO, expiresIn);
159         credDAO = new CachedCredDAO(new CredDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn);
160         certDAO = new CachedCertDAO(new CertDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn);
161
162         locateDAO = new LocateDAO(trans,historyDAO);
163         futureDAO = new FutureDAO(trans, historyDAO);
164         delegateDAO = new DelegateDAO(trans, historyDAO);
165         approvalDAO = new ApprovalDAO(trans, historyDAO);
166
167         // Only want to aggressively cleanse User related Caches... The others,
168         // just normal refresh
169         if (startClean) {
170             CachedDAO.startCleansing(trans.env(), credDAO, userRoleDAO);
171             CachedDAO.startRefresh(trans.env(), cacheInfoDAO);
172         }
173         // Set a Timer to Check Caches to send messages for Caching changes
174         
175         if (specialLogSlot==null) {
176             specialLogSlot = trans.slot(AuthzTransFilter.SPECIAL_LOG_SLOT);
177         }
178         
179         if (transIDSlot==null) {
180             transIDSlot = trans.slot(AuthzTransFilter.TRANS_ID_SLOT);
181         }
182         
183         AbsCassDAO.primePSIs(trans);
184     }
185
186
187     public void close(AuthzTrans trans) {
188         historyDAO.close(trans);
189         cacheInfoDAO.close(trans);
190         nsDAO.close(trans);
191         permDAO.close(trans);
192         roleDAO.close(trans);
193         userRoleDAO.close(trans);
194         credDAO.close(trans);
195         certDAO.close(trans);
196         delegateDAO.close(trans);
197         futureDAO.close(trans);
198         approvalDAO.close(trans);
199     }
200
201     public Result<PermDAO.Data> permFrom(AuthzTrans trans, String type,
202             String instance, String action) {
203         Result<NsDAO.Data> rnd = deriveNs(trans, type);
204         if (rnd.isOK()) {
205             return Result.ok(new PermDAO.Data(new NsSplit(rnd.value, type),
206                     instance, action));
207         } else {
208             return Result.err(rnd);
209         }
210     }
211
212     /**
213      * getPermsByUser
214      * 
215      * Because this call is frequently called internally, AND because we already
216      * look for it in the initial Call, we cache within the Transaction
217      * 
218      * @param trans
219      * @param user
220      * @return
221      */
222     public Result<List<PermDAO.Data>> getPermsByUser(AuthzTrans trans, String user, boolean lookup) {
223         return PermLookup.get(trans, this, user).getPerms(lookup);
224     }
225     
226     public Result<List<PermDAO.Data>> getPermsByUserFromRolesFilter(AuthzTrans trans, String user, String forUser) {
227         PermLookup plUser = PermLookup.get(trans, this, user);
228         Result<Set<String>> plPermNames = plUser.getPermNames();
229         if (plPermNames.notOK()) {
230             return Result.err(plPermNames);
231         }
232         
233         Set<String> nss;
234         if (forUser.equals(user)) {
235             nss = null;
236         } else {
237             // Setup a TreeSet to check on Namespaces to 
238             nss = new TreeSet<>();
239             PermLookup fUser = PermLookup.get(trans, this, forUser);
240             Result<Set<String>> forUpn = fUser.getPermNames();
241             if (forUpn.notOK()) {
242                 return Result.err(forUpn);
243             }
244             
245             for (String pn : forUpn.value) {
246                 Result<String[]> decoded = PermDAO.Data.decodeToArray(trans, this, pn);
247                 if (decoded.isOKhasData()) {
248                     nss.add(decoded.value[0]);
249                 } else {
250                     trans.error().log(pn,", derived from a Role, is invalid:",decoded.errorString());
251                 }
252             }
253         }
254
255         List<PermDAO.Data> rlpUser = new ArrayList<>();
256         Result<PermDAO.Data> rpdd;
257         PermDAO.Data pdd;
258         for (String pn : plPermNames.value) {
259             rpdd = PermDAO.Data.decode(trans, this, pn);
260             if (rpdd.isOKhasData()) {
261                 pdd=rpdd.value;
262                 if (nss==null || nss.contains(pdd.ns)) {
263                     rlpUser.add(pdd);
264                 }
265             } else {
266                 trans.error().log(pn,", derived from a Role, is invalid.  Run Data Cleanup:",rpdd.errorString());
267             }
268         }
269         return Result.ok(rlpUser); 
270     }
271
272     public Result<List<PermDAO.Data>> getPermsByType(AuthzTrans trans, String perm) {
273         Result<NsSplit> nss = deriveNsSplit(trans, perm);
274         if (nss.notOK()) {
275             return Result.err(nss);
276         }
277         return permDAO.readByType(trans, nss.value.ns, nss.value.name);
278     }
279
280     public Result<List<PermDAO.Data>> getPermsByName(AuthzTrans trans,
281             String type, String instance, String action) {
282         Result<NsSplit> nss = deriveNsSplit(trans, type);
283         if (nss.notOK()) {
284             return Result.err(nss);
285         }
286         return permDAO.read(trans, nss.value.ns, nss.value.name, instance,action);
287     }
288
289     public Result<List<PermDAO.Data>> getPermsByRole(AuthzTrans trans, String role, boolean lookup) {
290         Result<NsSplit> nss = deriveNsSplit(trans, role);
291         if (nss.notOK()) {
292             return Result.err(nss);
293         }
294
295         Result<List<RoleDAO.Data>> rlrd = roleDAO.read(trans, nss.value.ns,
296                 nss.value.name);
297         if (rlrd.notOKorIsEmpty()) {
298             return Result.err(rlrd);
299         }
300         // Using Set to avoid duplicates
301         Set<String> permNames = new HashSet<>();
302         if (rlrd.isOKhasData()) {
303             for (RoleDAO.Data drr : rlrd.value) {
304                 permNames.addAll(drr.perms(false));
305             }
306         }
307
308         // Note: It should be ok for a Valid user to have no permissions -
309         // Jonathan 8/12/2013
310         List<PermDAO.Data> perms = new ArrayList<>();
311         for (String perm : permNames) {
312             Result<PermDAO.Data> pr = PermDAO.Data.decode(trans, this, perm);
313             if (pr.notOK()) {
314                 return Result.err(pr);
315             }
316
317             if (lookup) {
318                 Result<List<PermDAO.Data>> rlpd = permDAO.read(trans, pr.value);
319                 if (rlpd.isOKhasData()) {
320                     for (PermDAO.Data pData : rlpd.value) {
321                         perms.add(pData);
322                     }
323                 }
324             } else {
325                 perms.add(pr.value);
326             }
327         }
328
329         return Result.ok(perms);
330     }
331
332     public Result<List<RoleDAO.Data>> getRolesByName(AuthzTrans trans,
333             String role) {
334         Result<NsSplit> nss = deriveNsSplit(trans, role);
335         if (nss.notOK()) {
336             return Result.err(nss);
337         }
338         String r = nss.value.name;
339         if (r.endsWith(".*")) { // do children Search
340             return roleDAO.readChildren(trans, nss.value.ns,
341                     r.substring(0, r.length() - 2));
342         } else if (ASTERIX.equals(r)) {
343             return roleDAO.readChildren(trans, nss.value.ns, ASTERIX);
344         } else {
345             return roleDAO.read(trans, nss.value.ns, r);
346         }
347     }
348
349     /**
350      * Derive NS
351      * 
352      * Given a Child Namespace, figure out what the best Namespace parent is.
353      * 
354      * For instance, if in the NS table, the parent "org.osaaf" exists, but not
355      * "org.osaaf.child" or "org.osaaf.a.b.c", then passing in either
356      * "org.osaaf.child" or "org.osaaf.a.b.c" will return "org.osaaf"
357      * 
358      * Uses recursive search on Cached DAO data
359      * 
360      * @param trans
361      * @param child
362      * @return
363      */
364     public Result<NsDAO.Data> deriveNs(AuthzTrans trans, String child) {
365         Result<List<NsDAO.Data>> r = nsDAO.read(trans, child);
366         
367         if (r.isOKhasData()) {
368             return Result.ok(r.value.get(0));
369         } else {
370             int dot;
371             if (child==null) {
372                 return Result.err(Status.ERR_NsNotFound, "No Namespace");
373             } else {
374                 dot = child.lastIndexOf('.');
375             }
376             if (dot < 0) {
377                 return Result.err(Status.ERR_NsNotFound, "No Namespace for [%s]", child);
378             } else {
379                 return deriveNs(trans, child.substring(0, dot));
380             }
381         }
382     }
383
384     public Result<NsDAO.Data> deriveFirstNsForType(AuthzTrans trans, String str, NsType type) {
385         NsDAO.Data nsd;
386
387         for (String lookup = str;!".".equals(lookup) && lookup!=null;) {
388             Result<List<NsDAO.Data>> rld = nsDAO.read(trans, lookup);
389             if (rld.isOKhasData()) {
390                 nsd=rld.value.get(0);
391                 lookup = nsd.parent;
392                 if (type.type == nsd.type) {
393                     return Result.ok(nsd);
394                 } else {
395                     int dot = str.lastIndexOf('.');
396                         
397                         if (dot < 0) {
398                             return Result.err(Status.ERR_NsNotFound, "No Namespace for [%s]", str);
399                         } else {
400                             return deriveFirstNsForType(trans, str.substring(0, dot),type);
401                         }
402                 }
403             } else {
404                 return Result.err(Status.ERR_NsNotFound,"There is no valid Company Namespace for %s",str);
405             }
406         }
407         return Result.err(Status.ERR_NotFound, str + " does not contain type " + type.name());
408     }
409
410     public Result<NsSplit> deriveNsSplit(AuthzTrans trans, String child) {
411         Result<NsDAO.Data> ndd = deriveNs(trans, child);
412         if (ndd.isOK()) {
413             NsSplit nss = new NsSplit(ndd.value, child);
414             if (nss.isOK()) {
415                 return Result.ok(nss);
416             } else {
417                 return Result.err(Status.ERR_NsNotFound,
418                         "Cannot split [%s] into valid namespace elements",
419                         child);
420             }
421         }
422         return Result.err(ndd);
423     }
424
425     /**
426      * Translate an ID into it's domain
427      * 
428      * i.e. myid1234@aaf.att.com results in domain of com.att.aaf
429      * 
430      * @param id
431      * @return
432      */
433     public static String domain2ns(String id) {
434         int at = id.indexOf('@');
435         if (at >= 0) {
436             String[] domain = id.substring(at + 1).split("\\.");
437             StringBuilder ns = new StringBuilder(id.length());
438             boolean first = true;
439             for (int i = domain.length - 1; i >= 0; --i) {
440                 if (first) {
441                     first = false;
442                 } else {
443                     ns.append('.');
444                 }
445                 ns.append(domain[i]);
446             }
447             return ns.toString();
448         } else {
449             return "";
450         }
451
452     }
453
454     /**
455      * Validate Namespace of ID@Domain
456      * 
457      * Namespace is reverse order of Domain.
458      * 
459      * @param trans
460      * @param id
461      * @return
462      */
463     public Result<NsDAO.Data> validNSOfDomain(AuthzTrans trans, String id) {
464         // Take domain, reverse order, and check on NS
465         String ns;
466         if (id.indexOf('@')<0) { // it's already an ns, not an ID
467             ns = id;
468         } else {
469             ns = domain2ns(id);
470         }
471         if (ns.length() > 0) {
472             if (!trans.org().getDomain().equals(ns)) { 
473                 Result<List<NsDAO.Data>> rlnsd = nsDAO.read(trans, ns);
474                 if (rlnsd.isOKhasData()) {
475                     return Result.ok(rlnsd.value.get(0));
476                 }
477             }
478         }
479         return Result.err(Status.ERR_NsNotFound,
480                 "A Namespace is not available for %s", id);
481     }
482
483     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, Access access) {
484         // <ns>.access|:role:<role name>|<read|write>
485         String ns = ndd.name;
486         int last;
487         do {
488             if (isGranted(trans, user, ns, ACCESS, ":ns", access.name())) {
489                 return Result.ok(ndd);
490             }
491             if ((last = ns.lastIndexOf('.')) >= 0) {
492                 ns = ns.substring(0, last);
493             }
494         } while (last >= 0);
495         // com.att.aaf.ns|:<client ns>:ns|<access>
496         // AAF-724 - Make consistent response for May User", and not take the
497         // last check... too confusing.
498         Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":"    + ndd.name + ":ns", access.name());
499         if (rv.isOK()) {
500             return rv;
501         } else if (rv.status==Result.ERR_Backend) {
502             return Result.err(rv);
503         } else {
504             return Result.err(Status.ERR_Denied, "[%s] may not %s in NS [%s]",
505                     user, access.name(), ndd.name);
506         }
507     }
508
509     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, RoleDAO.Data rdd, Access access) {
510         Result<NsDAO.Data> rnsd = deriveNs(trans, rdd.ns);
511         if (rnsd.isOK()) {
512             return mayUser(trans, user, rnsd.value, rdd, access);
513         }
514         return rnsd;
515     }
516
517     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, NsDAO.Data ndd, RoleDAO.Data rdd, Access access) {
518         // 1) Is User in the Role?
519         Result<List<UserRoleDAO.Data>> rurd = userRoleDAO.readUserInRole(trans, user, rdd.fullName());
520         if (rurd.isOKhasData()) {
521             return Result.ok(ndd);
522         }
523
524         String roleInst = ":role:" + rdd.name;
525         // <ns>.access|:role:<role name>|<read|write>
526         String ns = rdd.ns;
527         int last;
528         do {
529             if (isGranted(trans, user, ns,ACCESS, roleInst, access.name())) {
530                 return Result.ok(ndd);
531             }
532             if ((last = ns.lastIndexOf('.')) >= 0) {
533                 ns = ns.substring(0, last);
534             }
535         } while (last >= 0);
536
537         // Check if Access by Global Role perm
538         // com.att.aaf.ns|:<client ns>:role:name|<access>
539         Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":"
540                 + rdd.ns + roleInst, access.name());
541         if (rnsd.isOK()) {
542             return rnsd;
543         } else if (rnsd.status==Result.ERR_Backend) {
544             return Result.err(rnsd);
545         }
546
547         // Check if Access to Whole NS
548         // AAF-724 - Make consistent response for May User", and not take the
549         // last check... too confusing.
550         Result<org.onap.aaf.auth.dao.cass.NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, 
551                 ":" + rdd.ns + ":ns", access.name());
552         if (rv.isOK()) {
553             return rv;
554         } else if (rnsd.status==Result.ERR_Backend) {
555             return Result.err(rnsd);
556         } else {
557             return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]",
558                     user, access.name(), rdd.fullName());
559         }
560
561     }
562
563     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,PermDAO.Data pdd, Access access) {
564         Result<NsDAO.Data> rnsd = deriveNs(trans, pdd.ns);
565         if (rnsd.isOK()) {
566             return mayUser(trans, user, rnsd.value, pdd, access);
567         }
568         return rnsd;
569     }
570
571     public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, PermDAO.Data pdd, Access access) {
572         if (isGranted(trans, user, pdd.ns, pdd.type, pdd.instance, pdd.action)) {
573             return Result.ok(ndd);
574         }
575         String permInst = ":perm:" + pdd.type + ':' + pdd.instance + ':' + pdd.action;
576         // <ns>.access|:role:<role name>|<read|write>
577         String ns = ndd.name;
578         int last;
579         do {
580             if (isGranted(trans, user, ns, ACCESS, permInst, access.name())) {
581                 return Result.ok(ndd);
582             }
583             if ((last = ns.lastIndexOf('.')) >= 0) {
584                 ns = ns.substring(0, last);
585             }
586         } while (last >= 0);
587
588         // Check if Access by NS perm
589         // com.att.aaf.ns|:<client ns>:role:name|<access>
590         Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + permInst, access.name());
591         if (rnsd.isOK()) {
592             return rnsd;
593         } else if (rnsd.status==Result.ERR_Backend) {
594             return Result.err(rnsd);
595         }
596
597         // Check if Access to Whole NS
598         // AAF-724 - Make consistent response for May User", and not take the
599         // last check... too confusing.
600         Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":"    + pdd.ns + ":ns", access.name());
601         if (rv.isOK()) {
602             return rv;
603         } else {
604             return Result.err(Status.ERR_Denied,
605                     "[%s] may not %s Perm [%s|%s|%s]", user, access.name(),
606                     pdd.fullType(), pdd.instance, pdd.action);
607         }
608
609     }
610
611     public Result<Void> mayUser(AuthzTrans trans, DelegateDAO.Data dd, Access access) {
612         try {
613             Result<NsDAO.Data> rnsd = deriveNs(trans, domain2ns(trans.user()));
614             if (rnsd.isOKhasData() && mayUserVirtueOfNS(trans,trans.user(),rnsd.value, ":"    + rnsd.value.name + ":ns", access.name()).isOK()) {
615                 return Result.ok();
616             }
617             boolean isUser = trans.user().equals(dd.user);
618             boolean isDelegate = dd.delegate != null
619                     && (dd.user.equals(dd.delegate) || trans.user().equals(
620                             dd.delegate));
621             Organization org = trans.org();
622             switch (access) {
623             case create:
624                 if (org.getIdentity(trans, dd.user) == null) {
625                     return Result.err(Status.ERR_UserNotFound,
626                             "[%s] is not a user in the company database.",
627                             dd.user);
628                 }
629                 if (!dd.user.equals(dd.delegate) && org.getIdentity(trans, dd.delegate) == null) {
630                     return Result.err(Status.ERR_UserNotFound,
631                             "[%s] is not a user in the company database.",
632                             dd.delegate);
633                 }
634                 if (!trans.requested(REQD_TYPE.force) && dd.user != null && dd.user.equals(dd.delegate)) {
635                     return Result.err(Status.ERR_BadData,
636                             "[%s] cannot be a delegate for self", dd.user);
637                 }
638                 if (!isUser    && !isGranted(trans, trans.user(), ROOT_NS,DELG,
639                                 org.getDomain(), Question.CREATE)) {
640                     return Result.err(Status.ERR_Denied,
641                             "[%s] may not create a delegate for [%s]",
642                             trans.user(), dd.user);
643                 }
644                 break;
645             case read:
646             case write:
647                 if (!isUser    && !isDelegate && 
648                         !isGranted(trans, trans.user(), ROOT_NS,DELG,org.getDomain(), access.name())) {
649                     return Result.err(Status.ERR_Denied,
650                             "[%s] may not %s delegates for [%s]", trans.user(),
651                             access.name(), dd.user);
652                 }
653                 break;
654             default:
655                 return Result.err(Status.ERR_BadData,"Unknown Access type [%s]", access.name());
656             }
657         } catch (Exception e) {
658             return Result.err(e);
659         }
660         return Result.ok();
661     }
662
663     /*
664      * Check (recursively, if necessary), if able to do something based on NS
665      */
666     private Result<NsDAO.Data> mayUserVirtueOfNS(AuthzTrans trans, String user,    NsDAO.Data nsd, String ns_and_type, String access) {
667         String ns = nsd.name;
668
669         // If an ADMIN of the Namespace, then allow
670         
671         Result<List<UserRoleDAO.Data>> rurd;
672         if ((rurd = userRoleDAO.readUserInRole(trans, user, ns+DOT_ADMIN)).isOKhasData()) {
673             return Result.ok(nsd);
674         } else if (rurd.status==Result.ERR_Backend) {
675             return Result.err(rurd);
676         }
677         
678         // If Specially granted Global Permission
679         if (isGranted(trans, user, ROOT_NS,NS, ns_and_type, access)) {
680             return Result.ok(nsd);
681         }
682
683         // Check recur
684
685         int dot = ns.length();
686         if ((dot = ns.lastIndexOf('.', dot - 1)) >= 0) {
687             Result<NsDAO.Data> rnsd = deriveNs(trans, ns.substring(0, dot));
688             if (rnsd.isOK()) {
689                 rnsd = mayUserVirtueOfNS(trans, user, rnsd.value, ns_and_type,access);
690             } else if (rnsd.status==Result.ERR_Backend) {
691                 return Result.err(rnsd);
692             }
693             if (rnsd.isOK()) {
694                 return Result.ok(nsd);
695             } else if (rnsd.status==Result.ERR_Backend) {
696                 return Result.err(rnsd);
697             }
698         }
699         return Result.err(Status.ERR_Denied, "%s may not %s %s", user, access,
700                 ns_and_type);
701     }
702
703     
704     /**
705      * isGranted
706      * 
707      * Important function - Check internal Permission Schemes for Permission to
708      * do things
709      * 
710      * @param trans
711      * @param type
712      * @param instance
713      * @param action
714      * @return
715      */
716     public boolean isGranted(AuthzTrans trans, String user, String ns, String type,String instance, String action) {
717         Result<List<PermDAO.Data>> perms = getPermsByUser(trans, user, false);
718         if (perms.isOK()) {
719             for (PermDAO.Data pd : perms.value) {
720                 if (ns.equals(pd.ns)) {
721                     if (type.equals(pd.type)) {
722                         if (PermEval.evalInstance(pd.instance, instance)) {
723                             if (PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action 
724                                 return true;
725                             }
726                         }
727                     }
728                 }
729             }
730         }
731         return false;
732     }
733
734     public Result<Date> doesUserCredMatch(AuthzTrans trans, String user, byte[] cred) throws DAOException {
735         Result<List<CredDAO.Data>> result;
736         TimeTaken tt = trans.start("Read DB Cred", Env.REMOTE);
737         try {
738             result = credDAO.readID(trans, user);
739         } finally {
740             tt.done();
741         }
742
743         Result<Date> rv = null;
744         if (result.isOK()) {
745             if (result.isEmpty()) {
746                 rv = Result.err(Status.ERR_UserNotFound, user);
747                 if (willSpecialLog(trans,user)) {
748                     trans.audit().log("Special DEBUG:", user, " does not exist in DB");
749                 }
750             } else {
751                 Date now = new Date();//long now = System.currentTimeMillis();
752                 // Bug noticed 6/22. Sorting on the result can cause Concurrency Issues.     
753                 List<CredDAO.Data> cddl;
754                 if (result.value.size() > 1) {
755                     cddl = new ArrayList<>(result.value.size());
756                     for (CredDAO.Data old : result.value) {
757                         if (old.type==CredDAO.BASIC_AUTH || old.type==CredDAO.BASIC_AUTH_SHA256) {
758                             cddl.add(old);
759                         }
760                     }
761                     if (cddl.size()>1) {
762                         Collections.sort(cddl,new Comparator<CredDAO.Data>() {
763                             @Override
764                             public int compare(org.onap.aaf.auth.dao.cass.CredDAO.Data a,
765                                                org.onap.aaf.auth.dao.cass.CredDAO.Data b) {
766                                 return b.expires.compareTo(a.expires);
767                             }
768                         });
769                     }
770                 } else {
771                     cddl = result.value;
772                 }
773     
774                 Date expired = null;
775                 StringBuilder debug = willSpecialLog(trans,user)?new StringBuilder():null;
776                 for (CredDAO.Data cdd : cddl) {
777                     if (!cdd.id.equals(user)) {
778                         trans.error().log("doesUserCredMatch DB call does not match for user: " + user);
779                     }
780                     if (cdd.expires.after(now)) {
781                         byte[] dbcred = cdd.cred.array();
782                         
783                         try {
784                             switch(cdd.type) {
785                                 case CredDAO.BASIC_AUTH:
786                                     byte[] md5=Hash.hashMD5(cred);
787                                     if (Hash.compareTo(md5,dbcred)==0) {
788                                         checkLessThanDays(trans,7,now,cdd);
789                                         return Result.ok(cdd.expires);
790                                     } else if (debug!=null) {
791                                         load(debug, cdd);
792                                     }
793                                     break;
794                                 case CredDAO.BASIC_AUTH_SHA256:
795                                     ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.length);
796                                     bb.putInt(cdd.other);
797                                     bb.put(cred);
798                                     byte[] hash = Hash.hashSHA256(bb.array());
799     
800                                     if (Hash.compareTo(hash,dbcred)==0) {
801                                         checkLessThanDays(trans,7,now,cdd);
802                                         return Result.ok(cdd.expires);
803                                     } else if (debug!=null) {
804                                         load(debug, cdd);
805                                     }
806                                     break;
807                                 default:
808                                     trans.error().log("Unknown Credential Type %s for %s, %s",Integer.toString(cdd.type),cdd.id, Chrono.dateTime(cdd.expires));
809                             }
810                         } catch (NoSuchAlgorithmException e) {
811                             trans.error().log(e);
812                         }
813                     } else {
814                         if (expired==null || expired.before(cdd.expires)) {
815                             expired = cdd.expires;
816                         }
817                     }
818                 } // end for each
819                 if (debug==null) {
820                     trans.audit().printf("No cred matches ip=%s, user=%s\n",trans.ip(),user);
821                 } else {
822                     trans.audit().printf("No cred matches ip=%s, user=%s %s\n",trans.ip(),user,debug.toString());
823                 }
824                 if (expired!=null) {
825                     // Note: this is only returned if there are no good Credentials
826                     rv = Result.err(Status.ERR_Security,
827                             "Credentials %s from %s expired %s",trans.user(), trans.ip(), Chrono.dateTime(expired));
828                 }
829             }
830         } else {
831             return Result.err(result);
832         }
833         return rv == null ? Result.create((Date) null, Status.ERR_Security, "Wrong credential") : rv;
834     }
835
836
837     private void load(StringBuilder debug, Data cdd) {
838         debug.append("DB Entry: user=");
839         debug.append(cdd.id);
840         debug.append(",type=");
841         debug.append(cdd.type);
842         debug.append(",expires=");
843         debug.append(Chrono.dateTime(cdd.expires));
844         debug.append('\n');
845     }
846
847
848     private void checkLessThanDays(AuthzTrans trans, int days, Date now, Data cdd) {
849         long close = now.getTime() + (days * 86400000);
850         long cexp=cdd.expires.getTime();
851         if (cexp<close) {
852             int daysLeft = days-(int)((close-cexp)/86400000);
853             trans.audit().printf("user=%s,ip=%s,expires=%s,days=%d,msg=\"Password expires in less than %d day%s\"",
854                 cdd.id,trans.ip(),Chrono.dateOnlyStamp(cdd.expires),daysLeft, daysLeft,daysLeft==1?"":"s");
855         }
856     }
857
858
859     public Result<CredDAO.Data> userCredSetup(AuthzTrans trans, CredDAO.Data cred) {
860         if (cred.type==CredDAO.RAW) {
861             TimeTaken tt = trans.start("Hash Cred", Env.SUB);
862             try {
863                 cred.type = CredDAO.BASIC_AUTH_SHA256;
864                 cred.other = random.nextInt();
865                 ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.cred.capacity());
866                 bb.putInt(cred.other);
867                 bb.put(cred.cred);
868                 byte[] hash = Hash.hashSHA256(bb.array());
869                 cred.cred = ByteBuffer.wrap(hash);
870                 return Result.ok(cred);
871             } catch (NoSuchAlgorithmException e) {
872                 return Result.err(Status.ERR_General,e.getLocalizedMessage());
873             } finally {
874                 tt.done();
875             }
876             
877         }
878         return Result.err(Status.ERR_Security,"invalid/unreadable credential");
879     }
880     
881     public Result<Boolean> userCredCheck(AuthzTrans trans, CredDAO.Data orig, final byte[] raw) {
882             TimeTaken tt = trans.start("CheckCred Cred", Env.SUB);
883             try {
884                 switch(orig.type) {
885                     case CredDAO.BASIC_AUTH_SHA256:
886                         ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + raw.length);
887                         bb.putInt(orig.other);
888                         bb.put(raw);
889                         return Result.ok(Hash.compareTo(orig.cred.array(),Hash.hashSHA256(bb.array()))==0);
890                     case CredDAO.BASIC_AUTH:
891                         return Result.ok( Hash.compareTo(orig.cred.array(), Hash.hashMD5(raw))==0);
892                     default:
893                         return Result.ok(false);
894                 }
895             } catch (NoSuchAlgorithmException e) {
896                 return Result.err(Status.ERR_General,e.getLocalizedMessage());
897             } finally {
898                 tt.done();
899             }
900     }
901
902     public static final String APPROVED = "APPROVE";
903     public static final String REJECT = "REJECT";
904     public static final String PENDING = "PENDING";
905
906     public Result<Void> canAddUser(AuthzTrans trans, UserRoleDAO.Data data,
907             List<ApprovalDAO.Data> approvals) {
908         // get the approval policy for the organization
909
910         // get the list of approvals with an accept status
911
912         // validate the approvals against the policy
913
914         // for now check if all approvals are received and return
915         // SUCCESS/FAILURE/SKIP
916         boolean bReject = false;
917         boolean bPending = false;
918
919         for (ApprovalDAO.Data approval : approvals) {
920             if (approval.status.equals(REJECT)) {
921                 bReject = true;
922             } else if (approval.status.equals(PENDING)) {
923                 bPending = true;
924             }
925         }
926         if (bReject) {
927             return Result.err(Status.ERR_Policy,
928                     "Approval Polocy not conformed");
929         }
930         if (bPending) {
931             return Result.err(Status.ERR_ActionNotCompleted,
932                     "Required Approvals not received");
933         }
934
935         return Result.ok();
936     }
937
938     private static final String NO_CACHE_NAME = "No Cache Data named %s";
939
940     public Result<Void> clearCache(AuthzTrans trans, String cname) {
941         boolean all = "all".equals(cname);
942         Result<Void> rv = null;
943
944         if (all || NsDAO.TABLE.equals(cname)) {
945             int seg[] = series(NsDAO.CACHE_SEG);
946             for (int i: seg) {cacheClear(trans, NsDAO.TABLE,i);}
947             rv = cacheInfoDAO.touch(trans, NsDAO.TABLE, seg);
948         }
949         if (all || PermDAO.TABLE.equals(cname)) {
950             int seg[] = series(NsDAO.CACHE_SEG);
951             for (int i: seg) {cacheClear(trans, PermDAO.TABLE,i);}
952             rv = cacheInfoDAO.touch(trans, PermDAO.TABLE,seg);
953         }
954         if (all || RoleDAO.TABLE.equals(cname)) {
955             int seg[] = series(NsDAO.CACHE_SEG);
956             for (int i: seg) {cacheClear(trans, RoleDAO.TABLE,i);}
957             rv = cacheInfoDAO.touch(trans, RoleDAO.TABLE,seg);
958         }
959         if (all || UserRoleDAO.TABLE.equals(cname)) {
960             int seg[] = series(NsDAO.CACHE_SEG);
961             for (int i: seg) {cacheClear(trans, UserRoleDAO.TABLE,i);}
962             rv = cacheInfoDAO.touch(trans, UserRoleDAO.TABLE,seg);
963         }
964         if (all || CredDAO.TABLE.equals(cname)) {
965             int seg[] = series(NsDAO.CACHE_SEG);
966             for (int i: seg) {cacheClear(trans, CredDAO.TABLE,i);}
967             rv = cacheInfoDAO.touch(trans, CredDAO.TABLE,seg);
968         }
969         if (all || CertDAO.TABLE.equals(cname)) {
970             int seg[] = series(NsDAO.CACHE_SEG);
971             for (int i: seg) {cacheClear(trans, CertDAO.TABLE,i);}
972             rv = cacheInfoDAO.touch(trans, CertDAO.TABLE,seg);
973         }
974
975         if (rv == null) {
976             rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname);
977         }
978         return rv;
979     }
980
981     public Result<Void> cacheClear(AuthzTrans trans, String cname,Integer segment) {
982         Result<Void> rv;
983         if (NsDAO.TABLE.equals(cname)) {
984             rv = nsDAO.invalidate(segment);
985         } else if (PermDAO.TABLE.equals(cname)) {
986             rv = permDAO.invalidate(segment);
987         } else if (RoleDAO.TABLE.equals(cname)) {
988             rv = roleDAO.invalidate(segment);
989         } else if (UserRoleDAO.TABLE.equals(cname)) {
990             rv = userRoleDAO.invalidate(segment);
991         } else if (CredDAO.TABLE.equals(cname)) {
992             rv = credDAO.invalidate(segment);
993         } else if (CertDAO.TABLE.equals(cname)) {
994             rv = certDAO.invalidate(segment);
995         } else {
996             rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname);
997         }
998         return rv;
999     }
1000
1001     private int[] series(int max) {
1002         int[] series = new int[max];
1003         for (int i = 0; i < max; ++i)
1004             series[i] = i;
1005         return series;
1006     }
1007
1008     public boolean isDelegated(AuthzTrans trans, String user, String approver, Map<String,Result<List<DelegateDAO.Data>>> rldd ) {
1009         Result<List<DelegateDAO.Data>> userDelegatedFor = rldd.get(user);
1010         if (userDelegatedFor==null) {
1011             userDelegatedFor=delegateDAO.readByDelegate(trans, user);
1012             rldd.put(user, userDelegatedFor);
1013         }
1014         if (userDelegatedFor.isOKhasData()) {
1015             for (DelegateDAO.Data curr : userDelegatedFor.value) {
1016                 if (curr.user.equals(approver) && curr.delegate.equals(user)
1017                         && curr.expires.after(new Date())) {
1018                     return true;
1019                 }
1020             }
1021         }
1022         return false;
1023     }
1024
1025     public static boolean willSpecialLog(AuthzTrans trans, String user) {
1026         Boolean b = trans.get(specialLogSlot, null);
1027         if (b==null) { // we haven't evaluated in this trans for Special Log yet
1028             if (specialLog==null) {
1029                 return false;
1030             } else {
1031                 b = specialLog.contains(user);
1032                 trans.put(specialLogSlot, b);
1033             }
1034         }
1035         return b;
1036     }
1037     
1038     public static void logEncryptTrace(AuthzTrans trans, String data) {
1039         long ti;
1040         trans.put(transIDSlot, ti=nextTraceID());
1041         trans.trace().log("id="+Long.toHexString(ti)+",data=\""+trans.env().encryptor().encrypt(data)+'"');
1042     }
1043
1044     private synchronized static long nextTraceID() {
1045         return ++traceID;
1046     }
1047
1048     public static synchronized boolean specialLogOn(AuthzTrans trans, String id) {
1049         if (specialLog == null) {
1050             specialLog = new HashSet<>();
1051         }
1052         boolean rc = specialLog.add(id);
1053         if (rc) {
1054             trans.trace().printf("Trace on for %s requested by %s",id,trans.user());            
1055         }
1056         return rc;
1057     }
1058
1059     public static synchronized boolean specialLogOff(AuthzTrans trans, String id) {
1060         if (specialLog==null) {
1061             return false;
1062         }
1063         boolean rv = specialLog.remove(id);
1064         if (specialLog.isEmpty()) {
1065             specialLog = null;
1066         }
1067         if (rv) {
1068             trans.trace().printf("Trace off for %s requested by %s",id,trans.user());            
1069         }
1070         return rv;
1071     }
1072
1073     /** 
1074      * canMove
1075      * Which Types can be moved
1076      * @param nsType
1077      * @return
1078      */
1079     public boolean canMove(NsType nsType) {
1080         boolean rv;
1081         switch(nsType) {
1082             case DOT:
1083             case ROOT:
1084             case COMPANY:
1085             case UNKNOWN:
1086                 rv = false;
1087                 break;
1088             default:
1089                 rv = true;
1090         }
1091         return rv;
1092     }
1093
1094     public boolean isAdmin(AuthzTrans trans, String user, String ns) {
1095         Date now = new Date();
1096         Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_ADMIN);
1097         if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){
1098             if (urdd.expires.after(now)) {
1099                 return true;
1100             }
1101         }};
1102         return false;
1103     }
1104     
1105     public boolean isOwner(AuthzTrans trans, String user, String ns) {
1106         Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_OWNER);
1107         Date now = new Date();
1108         if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){
1109             if (urdd.expires.after(now)) {
1110                 return true;
1111             }
1112         }};
1113         return false;
1114     }
1115
1116     public int countOwner(AuthzTrans trans, String ns) {
1117         Result<List<UserRoleDAO.Data>> rur = userRoleDAO.readByRole(trans,ns+DOT_OWNER);
1118         Date now = new Date();
1119         int count = 0;
1120         if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){
1121             if (urdd.expires.after(now)) {
1122                 ++count;
1123             }
1124         }};
1125         return count;
1126     }
1127     
1128     /**
1129      * Return a Unique String, (same string, if it is already unique), with only
1130      * lowercase letters, digits and the '.' character.
1131      * 
1132      * @param name
1133      * @return
1134      * @throws IOException 
1135      */
1136     public static String toUnique(String name) throws IOException {
1137         byte[] from = name.getBytes();
1138         StringBuilder sb = new StringBuilder();
1139         byte f;
1140         for (int i=0;i<from.length;++i) {
1141             f=(byte)(from[i]); // printables;
1142             sb.append((char)((f>>4)+0x61));
1143             sb.append((char)((f&0x0F)+0x61));
1144         }
1145         return sb.toString();
1146     }
1147     
1148     public static String fromUnique(String name) throws IOException {
1149         byte[] from = name.getBytes();
1150         StringBuilder sb = new StringBuilder();
1151         char c;
1152         for (int i=0;i<from.length;++i) {
1153             c = (char)((from[i]-0x61)<<4);
1154             c |= (from[++i]-0x61);
1155             sb.append(c);
1156         }
1157         return sb.toString();
1158     }
1159
1160 }