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====================================================
22 package org.onap.aaf.auth.dao.hl;
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;
35 import java.util.Random;
37 import java.util.TreeSet;
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.DelegateDAO;
54 import org.onap.aaf.auth.dao.cass.FutureDAO;
55 import org.onap.aaf.auth.dao.cass.HistoryDAO;
56 import org.onap.aaf.auth.dao.cass.LocateDAO;
57 import org.onap.aaf.auth.dao.cass.NsDAO;
58 import org.onap.aaf.auth.dao.cass.NsSplit;
59 import org.onap.aaf.auth.dao.cass.NsType;
60 import org.onap.aaf.auth.dao.cass.PermDAO;
61 import org.onap.aaf.auth.dao.cass.RoleDAO;
62 import org.onap.aaf.auth.dao.cass.Status;
63 import org.onap.aaf.auth.dao.cass.UserRoleDAO;
64 import org.onap.aaf.auth.dao.cass.CredDAO.Data;
65 import org.onap.aaf.auth.env.AuthzTrans;
66 import org.onap.aaf.auth.env.AuthzTransFilter;
67 import org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE;
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;
79 import com.datastax.driver.core.Cluster;
84 * A Data Access Combination Object which asks Security and other Questions
89 public class Question {
91 // DON'T CHANGE FROM lower Case!!!
92 public static enum Type {
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";
102 static final String ASTERIX = "*";
104 public static enum Access {
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();
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.ROOT_NS();
118 public static final String ATTRIB = "attrib";
121 public static final int MAX_SCOPE = 10;
122 public static final int APP_SCOPE = 3;
123 public static final int COMPANY_SCOPE = 2;
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;
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;
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);
152 // Deal with Cached Entries
153 cacheInfoDAO = new CacheInfoDAO(trans, historyDAO);
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);
162 locateDAO = new LocateDAO(trans,historyDAO);
163 futureDAO = new FutureDAO(trans, historyDAO);
164 delegateDAO = new DelegateDAO(trans, historyDAO);
165 approvalDAO = new ApprovalDAO(trans, historyDAO);
167 // Only want to aggressively cleanse User related Caches... The others,
168 // just normal refresh
170 CachedDAO.startCleansing(trans.env(), credDAO, userRoleDAO);
171 CachedDAO.startRefresh(trans.env(), cacheInfoDAO);
173 // Set a Timer to Check Caches to send messages for Caching changes
175 if(specialLogSlot==null) {
176 specialLogSlot = trans.slot(AuthzTransFilter.SPECIAL_LOG_SLOT);
179 if(transIDSlot==null) {
180 transIDSlot = trans.slot(AuthzTransFilter.TRANS_ID_SLOT);
183 AbsCassDAO.primePSIs(trans);
187 public void close(AuthzTrans trans) {
188 historyDAO.close(trans);
189 cacheInfoDAO.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);
201 public Result<PermDAO.Data> permFrom(AuthzTrans trans, String type,
202 String instance, String action) {
203 Result<NsDAO.Data> rnd = deriveNs(trans, type);
205 return Result.ok(new PermDAO.Data(new NsSplit(rnd.value, type),
208 return Result.err(rnd);
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
222 public Result<List<PermDAO.Data>> getPermsByUser(AuthzTrans trans, String user, boolean lookup) {
223 return PermLookup.get(trans, this, user).getPerms(lookup);
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);
234 if(forUser.equals(user)) {
237 // Setup a TreeSet to check on Namespaces to
238 nss = new TreeSet<String>();
239 PermLookup fUser = PermLookup.get(trans, this, forUser);
240 Result<Set<String>> forUpn = fUser.getPermNames();
242 return Result.err(forUpn);
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]);
250 trans.error().log(pn,", derived from a Role, is invalid:",decoded.errorString());
255 List<PermDAO.Data> rlpUser = new ArrayList<PermDAO.Data>();
256 Result<PermDAO.Data> rpdd;
258 for(String pn : plPermNames.value) {
259 rpdd = PermDAO.Data.decode(trans, this, pn);
260 if(rpdd.isOKhasData()) {
262 if(nss==null || nss.contains(pdd.ns)) {
266 trans.error().log(pn,", derived from a Role, is invalid. Run Data Cleanup:",rpdd.errorString());
269 return Result.ok(rlpUser);
272 public Result<List<PermDAO.Data>> getPermsByType(AuthzTrans trans, String perm) {
273 Result<NsSplit> nss = deriveNsSplit(trans, perm);
275 return Result.err(nss);
277 return permDAO.readByType(trans, nss.value.ns, nss.value.name);
280 public Result<List<PermDAO.Data>> getPermsByName(AuthzTrans trans,
281 String type, String instance, String action) {
282 Result<NsSplit> nss = deriveNsSplit(trans, type);
284 return Result.err(nss);
286 return permDAO.read(trans, nss.value.ns, nss.value.name, instance,action);
289 public Result<List<PermDAO.Data>> getPermsByRole(AuthzTrans trans, String role, boolean lookup) {
290 Result<NsSplit> nss = deriveNsSplit(trans, role);
292 return Result.err(nss);
295 Result<List<RoleDAO.Data>> rlrd = roleDAO.read(trans, nss.value.ns,
297 if (rlrd.notOKorIsEmpty()) {
298 return Result.err(rlrd);
300 // Using Set to avoid duplicates
301 Set<String> permNames = new HashSet<String>();
302 if (rlrd.isOKhasData()) {
303 for (RoleDAO.Data drr : rlrd.value) {
304 permNames.addAll(drr.perms(false));
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<PermDAO.Data>();
311 for (String perm : permNames) {
312 Result<PermDAO.Data> pr = PermDAO.Data.decode(trans, this, perm);
314 return Result.err(pr);
318 Result<List<PermDAO.Data>> rlpd = permDAO.read(trans, pr.value);
319 if (rlpd.isOKhasData()) {
320 for (PermDAO.Data pData : rlpd.value) {
329 return Result.ok(perms);
332 public Result<List<RoleDAO.Data>> getRolesByName(AuthzTrans trans,
334 Result<NsSplit> nss = deriveNsSplit(trans, role);
336 return Result.err(nss);
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);
345 return roleDAO.read(trans, nss.value.ns, r);
352 * Given a Child Namespace, figure out what the best Namespace parent is.
354 * For instance, if in the NS table, the parent "com.att" 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 "com.att"
358 * Uses recursive search on Cached DAO data
364 public Result<NsDAO.Data> deriveNs(AuthzTrans trans, String child) {
365 Result<List<NsDAO.Data>> r = nsDAO.read(trans, child);
367 if (r.isOKhasData()) {
368 return Result.ok(r.value.get(0));
372 return Result.err(Status.ERR_NsNotFound, "No Namespace");
374 dot = child.lastIndexOf('.');
377 return Result.err(Status.ERR_NsNotFound, "No Namespace for [%s]", child);
379 return deriveNs(trans, child.substring(0, dot));
384 public Result<NsDAO.Data> deriveFirstNsForType(AuthzTrans trans, String str, NsType type) {
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);
392 if(type.type == nsd.type) {
393 return Result.ok(nsd);
396 return Result.err(Status.ERR_NsNotFound,"There is no valid Company Namespace for %s",str);
399 return Result.err(Status.ERR_NotFound, str + " does not contain type " + type.name());
402 public Result<NsSplit> deriveNsSplit(AuthzTrans trans, String child) {
403 Result<NsDAO.Data> ndd = deriveNs(trans, child);
405 NsSplit nss = new NsSplit(ndd.value, child);
407 return Result.ok(nss);
409 return Result.err(Status.ERR_NsNotFound,
410 "Cannot split [%s] into valid namespace elements",
414 return Result.err(ndd);
418 * Translate an ID into it's domain
420 * i.e. myid1234@aaf.att.com results in domain of com.att.aaf
425 public static String domain2ns(String id) {
426 int at = id.indexOf('@');
428 String[] domain = id.substring(at + 1).split("\\.");
429 StringBuilder ns = new StringBuilder(id.length());
430 boolean first = true;
431 for (int i = domain.length - 1; i >= 0; --i) {
437 ns.append(domain[i]);
439 return ns.toString();
447 * Validate Namespace of ID@Domain
449 * Namespace is reverse order of Domain.
455 public Result<NsDAO.Data> validNSOfDomain(AuthzTrans trans, String id) {
456 // Take domain, reverse order, and check on NS
458 if(id.indexOf('@')<0) { // it's already an ns, not an ID
463 if (ns.length() > 0) {
464 if(!trans.org().getDomain().equals(ns)) {
465 Result<List<NsDAO.Data>> rlnsd = nsDAO.read(trans, ns);
466 if (rlnsd.isOKhasData()) {
467 return Result.ok(rlnsd.value.get(0));
471 return Result.err(Status.ERR_NsNotFound,
472 "A Namespace is not available for %s", id);
475 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, Access access) {
476 // <ns>.access|:role:<role name>|<read|write>
477 String ns = ndd.name;
480 if (isGranted(trans, user, ns, ACCESS, ":ns", access.name())) {
481 return Result.ok(ndd);
483 if ((last = ns.lastIndexOf('.')) >= 0) {
484 ns = ns.substring(0, last);
487 // com.att.aaf.ns|:<client ns>:ns|<access>
488 // AAF-724 - Make consistent response for May User", and not take the
489 // last check... too confusing.
490 Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":" + ndd.name + ":ns", access.name());
493 } else if(rv.status==Result.ERR_Backend) {
494 return Result.err(rv);
496 return Result.err(Status.ERR_Denied, "[%s] may not %s in NS [%s]",
497 user, access.name(), ndd.name);
501 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, RoleDAO.Data rdd, Access access) {
502 Result<NsDAO.Data> rnsd = deriveNs(trans, rdd.ns);
504 return mayUser(trans, user, rnsd.value, rdd, access);
509 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, NsDAO.Data ndd, RoleDAO.Data rdd, Access access) {
510 // 1) Is User in the Role?
511 Result<List<UserRoleDAO.Data>> rurd = userRoleDAO.readUserInRole(trans, user, rdd.fullName());
512 if (rurd.isOKhasData()) {
513 return Result.ok(ndd);
516 String roleInst = ":role:" + rdd.name;
517 // <ns>.access|:role:<role name>|<read|write>
521 if (isGranted(trans, user, ns,ACCESS, roleInst, access.name())) {
522 return Result.ok(ndd);
524 if ((last = ns.lastIndexOf('.')) >= 0) {
525 ns = ns.substring(0, last);
529 // Check if Access by Global Role perm
530 // com.att.aaf.ns|:<client ns>:role:name|<access>
531 Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":"
532 + rdd.ns + roleInst, access.name());
535 } else if(rnsd.status==Result.ERR_Backend) {
536 return Result.err(rnsd);
539 // Check if Access to Whole NS
540 // AAF-724 - Make consistent response for May User", and not take the
541 // last check... too confusing.
542 Result<org.onap.aaf.auth.dao.cass.NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd,
543 ":" + rdd.ns + ":ns", access.name());
546 } else if(rnsd.status==Result.ERR_Backend) {
547 return Result.err(rnsd);
549 return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]",
550 user, access.name(), rdd.fullName());
555 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,PermDAO.Data pdd, Access access) {
556 Result<NsDAO.Data> rnsd = deriveNs(trans, pdd.ns);
558 return mayUser(trans, user, rnsd.value, pdd, access);
563 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, PermDAO.Data pdd, Access access) {
564 if (isGranted(trans, user, pdd.ns, pdd.type, pdd.instance, pdd.action)) {
565 return Result.ok(ndd);
567 String permInst = ":perm:" + pdd.type + ':' + pdd.instance + ':' + pdd.action;
568 // <ns>.access|:role:<role name>|<read|write>
569 String ns = ndd.name;
572 if (isGranted(trans, user, ns, ACCESS, permInst, access.name())) {
573 return Result.ok(ndd);
575 if ((last = ns.lastIndexOf('.')) >= 0) {
576 ns = ns.substring(0, last);
580 // Check if Access by NS perm
581 // com.att.aaf.ns|:<client ns>:role:name|<access>
582 Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + permInst, access.name());
585 } else if(rnsd.status==Result.ERR_Backend) {
586 return Result.err(rnsd);
589 // Check if Access to Whole NS
590 // AAF-724 - Make consistent response for May User", and not take the
591 // last check... too confusing.
592 Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + ":ns", access.name());
596 return Result.err(Status.ERR_Denied,
597 "[%s] may not %s Perm [%s|%s|%s]", user, access.name(),
598 pdd.fullType(), pdd.instance, pdd.action);
603 public Result<Void> mayUser(AuthzTrans trans, DelegateDAO.Data dd, Access access) {
605 Result<NsDAO.Data> rnsd = deriveNs(trans, domain2ns(trans.user()));
606 if(rnsd.isOKhasData() && mayUserVirtueOfNS(trans,trans.user(),rnsd.value, ":" + rnsd.value.name + ":ns", access.name()).isOK()) {
609 boolean isUser = trans.user().equals(dd.user);
610 boolean isDelegate = dd.delegate != null
611 && (dd.user.equals(dd.delegate) || trans.user().equals(
613 Organization org = trans.org();
616 if (org.getIdentity(trans, dd.user) == null) {
617 return Result.err(Status.ERR_UserNotFound,
618 "[%s] is not a user in the company database.",
621 if (!dd.user.equals(dd.delegate) && org.getIdentity(trans, dd.delegate) == null) {
622 return Result.err(Status.ERR_UserNotFound,
623 "[%s] is not a user in the company database.",
626 if (!trans.requested(REQD_TYPE.force) && dd.user != null && dd.user.equals(dd.delegate)) {
627 return Result.err(Status.ERR_BadData,
628 "[%s] cannot be a delegate for self", dd.user);
630 if (!isUser && !isGranted(trans, trans.user(), ROOT_NS,DELG,
631 org.getDomain(), Question.CREATE)) {
632 return Result.err(Status.ERR_Denied,
633 "[%s] may not create a delegate for [%s]",
634 trans.user(), dd.user);
639 if (!isUser && !isDelegate &&
640 !isGranted(trans, trans.user(), ROOT_NS,DELG,org.getDomain(), access.name())) {
641 return Result.err(Status.ERR_Denied,
642 "[%s] may not %s delegates for [%s]", trans.user(),
643 access.name(), dd.user);
647 return Result.err(Status.ERR_BadData,"Unknown Access type [%s]", access.name());
649 } catch (Exception e) {
650 return Result.err(e);
656 * Check (recursively, if necessary), if able to do something based on NS
658 private Result<NsDAO.Data> mayUserVirtueOfNS(AuthzTrans trans, String user, NsDAO.Data nsd, String ns_and_type, String access) {
659 String ns = nsd.name;
661 // If an ADMIN of the Namespace, then allow
663 Result<List<UserRoleDAO.Data>> rurd;
664 if ((rurd = userRoleDAO.readUserInRole(trans, user, ns+DOT_ADMIN)).isOKhasData()) {
665 return Result.ok(nsd);
666 } else if(rurd.status==Result.ERR_Backend) {
667 return Result.err(rurd);
670 // If Specially granted Global Permission
671 if (isGranted(trans, user, ROOT_NS,NS, ns_and_type, access)) {
672 return Result.ok(nsd);
677 int dot = ns.length();
678 if ((dot = ns.lastIndexOf('.', dot - 1)) >= 0) {
679 Result<NsDAO.Data> rnsd = deriveNs(trans, ns.substring(0, dot));
681 rnsd = mayUserVirtueOfNS(trans, user, rnsd.value, ns_and_type,access);
682 } else if(rnsd.status==Result.ERR_Backend) {
683 return Result.err(rnsd);
686 return Result.ok(nsd);
687 } else if(rnsd.status==Result.ERR_Backend) {
688 return Result.err(rnsd);
691 return Result.err(Status.ERR_Denied, "%s may not %s %s", user, access,
699 * Important function - Check internal Permission Schemes for Permission to
708 public boolean isGranted(AuthzTrans trans, String user, String ns, String type,String instance, String action) {
709 Result<List<PermDAO.Data>> perms = getPermsByUser(trans, user, false);
711 for (PermDAO.Data pd : perms.value) {
712 if (ns.equals(pd.ns)) {
713 if (type.equals(pd.type)) {
714 if (PermEval.evalInstance(pd.instance, instance)) {
715 if(PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action
726 public Result<Date> doesUserCredMatch(AuthzTrans trans, String user, byte[] cred) throws DAOException {
727 Result<List<CredDAO.Data>> result;
728 TimeTaken tt = trans.start("Read DB Cred", Env.REMOTE);
730 result = credDAO.readID(trans, user);
735 Result<Date> rv = null;
737 if (result.isEmpty()) {
738 rv = Result.err(Status.ERR_UserNotFound, user);
739 if (willSpecialLog(trans,user)) {
740 trans.audit().log("Special DEBUG:", user, " does not exist in DB");
743 Date now = new Date();//long now = System.currentTimeMillis();
744 // Bug noticed 6/22. Sorting on the result can cause Concurrency Issues.
745 List<CredDAO.Data> cddl;
746 if(result.value.size() > 1) {
747 cddl = new ArrayList<CredDAO.Data>(result.value.size());
748 for(CredDAO.Data old : result.value) {
749 if(old.type==CredDAO.BASIC_AUTH || old.type==CredDAO.BASIC_AUTH_SHA256) {
754 Collections.sort(cddl,new Comparator<CredDAO.Data>() {
756 public int compare(org.onap.aaf.auth.dao.cass.CredDAO.Data a,
757 org.onap.aaf.auth.dao.cass.CredDAO.Data b) {
758 return b.expires.compareTo(a.expires);
767 StringBuilder debug = willSpecialLog(trans,user)?new StringBuilder():null;
768 for (CredDAO.Data cdd : cddl) {
769 if(!cdd.id.equals(user)) {
770 trans.error().log("doesUserCredMatch DB call does not match for user: " + user);
772 if (cdd.expires.after(now)) {
773 byte[] dbcred = cdd.cred.array();
777 case CredDAO.BASIC_AUTH:
778 byte[] md5=Hash.hashMD5(cred);
779 if(Hash.compareTo(md5,dbcred)==0) {
780 checkLessThanDays(trans,7,now,cdd);
781 return Result.ok(cdd.expires);
782 } else if (debug!=null) {
783 load(debug, cdd,dbcred);
786 case CredDAO.BASIC_AUTH_SHA256:
787 ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.length);
788 bb.putInt(cdd.other);
790 byte[] hash = Hash.hashSHA256(bb.array());
792 if(Hash.compareTo(hash,dbcred)==0) {
793 checkLessThanDays(trans,7,now,cdd);
794 return Result.ok(cdd.expires);
795 } else if (debug!=null) {
796 load(debug, cdd, dbcred);
800 trans.error().log("Unknown Credential Type %s for %s, %s",Integer.toString(cdd.type),cdd.id, Chrono.dateTime(cdd.expires));
802 } catch (NoSuchAlgorithmException e) {
803 trans.error().log(e);
806 if(expired==null || expired.before(cdd.expires)) {
807 expired = cdd.expires;
812 debug=new StringBuilder();
817 debug.append("cred=");
818 debug.append(new String(cred));
819 trans.audit().printf("No cred matches ip=%s, user=%s, %s\n",trans.ip(),user,trans.encryptor().encrypt(debug.toString()));
821 // Note: this is only returned if there are no good Credentials
822 rv = Result.err(Status.ERR_Security,
823 "Credentials %s from %s expired %s",trans.user(), trans.ip(), Chrono.dateTime(expired));
827 return Result.err(result);
829 return rv == null ? Result.create((Date) null, Status.ERR_Security, "Wrong credential") : rv;
833 private void load(StringBuilder debug, Data cdd, byte[] dbcred) {
834 debug.append("DB Entry: user=");
835 debug.append(cdd.id);
836 debug.append(",type=");
837 debug.append(cdd.type);
838 debug.append(",cred=");
839 debug.append(Hash.toHex(dbcred));
840 debug.append(",expires=");
841 debug.append(Chrono.dateTime(cdd.expires));
846 private void checkLessThanDays(AuthzTrans trans, int days, Date now, Data cdd) {
847 long close = now.getTime() + (days * 86400000);
848 long cexp=cdd.expires.getTime();
850 int daysLeft = days-(int)((close-cexp)/86400000);
851 trans.audit().printf("user=%s,ip=%s,expires=%s,days=%d,msg=\"Password expires in less than %d day%s\"",
852 cdd.id,trans.ip(),Chrono.dateOnlyStamp(cdd.expires),daysLeft, daysLeft,daysLeft==1?"":"s");
857 public Result<CredDAO.Data> userCredSetup(AuthzTrans trans, CredDAO.Data cred) {
858 if(cred.type==CredDAO.RAW) {
859 TimeTaken tt = trans.start("Hash Cred", Env.SUB);
861 cred.type = CredDAO.BASIC_AUTH_SHA256;
862 cred.other = random.nextInt();
863 ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.cred.capacity());
864 bb.putInt(cred.other);
866 byte[] hash = Hash.hashSHA256(bb.array());
867 cred.cred = ByteBuffer.wrap(hash);
868 return Result.ok(cred);
869 } catch (NoSuchAlgorithmException e) {
870 return Result.err(Status.ERR_General,e.getLocalizedMessage());
876 return Result.err(Status.ERR_Security,"invalid/unreadable credential");
879 public Result<Boolean> userCredCheck(AuthzTrans trans, CredDAO.Data orig, final byte[] raw) {
880 TimeTaken tt = trans.start("CheckCred Cred", Env.SUB);
883 case CredDAO.BASIC_AUTH_SHA256:
884 ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + raw.length);
885 bb.putInt(orig.other);
887 return Result.ok(Hash.compareTo(orig.cred.array(),Hash.hashSHA256(bb.array()))==0);
888 case CredDAO.BASIC_AUTH:
889 return Result.ok( Hash.compareTo(orig.cred.array(), Hash.hashMD5(raw))==0);
891 return Result.ok(false);
893 } catch (NoSuchAlgorithmException e) {
894 return Result.err(Status.ERR_General,e.getLocalizedMessage());
900 public static final String APPROVED = "APPROVE";
901 public static final String REJECT = "REJECT";
902 public static final String PENDING = "PENDING";
904 public Result<Void> canAddUser(AuthzTrans trans, UserRoleDAO.Data data,
905 List<ApprovalDAO.Data> approvals) {
906 // get the approval policy for the organization
908 // get the list of approvals with an accept status
910 // validate the approvals against the policy
912 // for now check if all approvals are received and return
913 // SUCCESS/FAILURE/SKIP
914 boolean bReject = false;
915 boolean bPending = false;
917 for (ApprovalDAO.Data approval : approvals) {
918 if (approval.status.equals(REJECT)) {
920 } else if (approval.status.equals(PENDING)) {
925 return Result.err(Status.ERR_Policy,
926 "Approval Polocy not conformed");
929 return Result.err(Status.ERR_ActionNotCompleted,
930 "Required Approvals not received");
936 private static final String NO_CACHE_NAME = "No Cache Data named %s";
938 public Result<Void> clearCache(AuthzTrans trans, String cname) {
939 boolean all = "all".equals(cname);
940 Result<Void> rv = null;
942 if (all || NsDAO.TABLE.equals(cname)) {
943 int seg[] = series(NsDAO.CACHE_SEG);
944 for(int i: seg) {cacheClear(trans, NsDAO.TABLE,i);}
945 rv = cacheInfoDAO.touch(trans, NsDAO.TABLE, seg);
947 if (all || PermDAO.TABLE.equals(cname)) {
948 int seg[] = series(NsDAO.CACHE_SEG);
949 for(int i: seg) {cacheClear(trans, PermDAO.TABLE,i);}
950 rv = cacheInfoDAO.touch(trans, PermDAO.TABLE,seg);
952 if (all || RoleDAO.TABLE.equals(cname)) {
953 int seg[] = series(NsDAO.CACHE_SEG);
954 for(int i: seg) {cacheClear(trans, RoleDAO.TABLE,i);}
955 rv = cacheInfoDAO.touch(trans, RoleDAO.TABLE,seg);
957 if (all || UserRoleDAO.TABLE.equals(cname)) {
958 int seg[] = series(NsDAO.CACHE_SEG);
959 for(int i: seg) {cacheClear(trans, UserRoleDAO.TABLE,i);}
960 rv = cacheInfoDAO.touch(trans, UserRoleDAO.TABLE,seg);
962 if (all || CredDAO.TABLE.equals(cname)) {
963 int seg[] = series(NsDAO.CACHE_SEG);
964 for(int i: seg) {cacheClear(trans, CredDAO.TABLE,i);}
965 rv = cacheInfoDAO.touch(trans, CredDAO.TABLE,seg);
967 if (all || CertDAO.TABLE.equals(cname)) {
968 int seg[] = series(NsDAO.CACHE_SEG);
969 for(int i: seg) {cacheClear(trans, CertDAO.TABLE,i);}
970 rv = cacheInfoDAO.touch(trans, CertDAO.TABLE,seg);
974 rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname);
979 public Result<Void> cacheClear(AuthzTrans trans, String cname,Integer segment) {
981 if (NsDAO.TABLE.equals(cname)) {
982 rv = nsDAO.invalidate(segment);
983 } else if (PermDAO.TABLE.equals(cname)) {
984 rv = permDAO.invalidate(segment);
985 } else if (RoleDAO.TABLE.equals(cname)) {
986 rv = roleDAO.invalidate(segment);
987 } else if (UserRoleDAO.TABLE.equals(cname)) {
988 rv = userRoleDAO.invalidate(segment);
989 } else if (CredDAO.TABLE.equals(cname)) {
990 rv = credDAO.invalidate(segment);
991 } else if (CertDAO.TABLE.equals(cname)) {
992 rv = certDAO.invalidate(segment);
994 rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname);
999 private int[] series(int max) {
1000 int[] series = new int[max];
1001 for (int i = 0; i < max; ++i)
1006 public boolean isDelegated(AuthzTrans trans, String user, String approver, Map<String,Result<List<DelegateDAO.Data>>> rldd ) {
1007 Result<List<DelegateDAO.Data>> userDelegatedFor = rldd.get(user);
1008 if(userDelegatedFor==null) {
1009 userDelegatedFor=delegateDAO.readByDelegate(trans, user);
1010 rldd.put(user, userDelegatedFor);
1012 if(userDelegatedFor.isOKhasData()) {
1013 for (DelegateDAO.Data curr : userDelegatedFor.value) {
1014 if (curr.user.equals(approver) && curr.delegate.equals(user)
1015 && curr.expires.after(new Date())) {
1023 public static boolean willSpecialLog(AuthzTrans trans, String user) {
1024 Boolean b = trans.get(specialLogSlot, null);
1025 if(b==null) { // we haven't evaluated in this trans for Special Log yet
1026 if(specialLog==null) {
1029 b = specialLog.contains(user);
1030 trans.put(specialLogSlot, b);
1036 public static void logEncryptTrace(AuthzTrans trans, String data) {
1038 trans.put(transIDSlot, ti=nextTraceID());
1039 trans.trace().log("id="+Long.toHexString(ti)+",data=\""+trans.env().encryptor().encrypt(data)+'"');
1042 private synchronized static long nextTraceID() {
1046 public static synchronized boolean specialLogOn(AuthzTrans trans, String id) {
1047 if (specialLog == null) {
1048 specialLog = new HashSet<String>();
1050 boolean rc = specialLog.add(id);
1052 trans.trace().printf("Trace on for %s requested by %s",id,trans.user());
1057 public static synchronized boolean specialLogOff(AuthzTrans trans, String id) {
1058 if(specialLog==null) {
1061 boolean rv = specialLog.remove(id);
1062 if (specialLog.isEmpty()) {
1066 trans.trace().printf("Trace off for %s requested by %s",id,trans.user());
1073 * Which Types can be moved
1077 public boolean canMove(NsType nsType) {
1092 public boolean isAdmin(AuthzTrans trans, String user, String ns) {
1093 Date now = new Date();
1094 Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_ADMIN);
1095 if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){
1096 if(urdd.expires.after(now)) {
1103 public boolean isOwner(AuthzTrans trans, String user, String ns) {
1104 Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_OWNER);
1105 Date now = new Date();
1106 if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){
1107 if(urdd.expires.after(now)) {
1114 public int countOwner(AuthzTrans trans, String ns) {
1115 Result<List<UserRoleDAO.Data>> rur = userRoleDAO.readByRole(trans,ns+DOT_OWNER);
1116 Date now = new Date();
1118 if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){
1119 if(urdd.expires.after(now)) {
1127 * Return a Unique String, (same string, if it is already unique), with only
1128 * lowercase letters, digits and the '.' character.
1132 * @throws IOException
1134 public static String toUnique(String name) throws IOException {
1135 byte[] from = name.getBytes();
1136 StringBuilder sb = new StringBuilder();
1138 for(int i=0;i<from.length;++i) {
1139 f=(byte)(from[i]); // printables;
1140 sb.append((char)((f>>4)+0x61));
1141 sb.append((char)((f&0x0F)+0x61));
1143 return sb.toString();
1146 public static String fromUnique(String name) throws IOException {
1147 byte[] from = name.getBytes();
1148 StringBuilder sb = new StringBuilder();
1150 for(int i=0;i<from.length;++i) {
1151 c = (char)((from[i]-0x61)<<4);
1152 c |= (from[++i]-0x61);
1155 return sb.toString();