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.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;
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.isInitialized() ? Define.ROOT_NS() : "undefined";
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<>();
239 PermLookup fUser = PermLookup.get(trans, this, forUser);
240 Result<Set<String>> forUpn = fUser.getPermNames();
241 if (forUpn.notOK()) {
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<>();
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<>();
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<>();
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 "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"
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);
395 int dot = str.lastIndexOf('.');
398 return Result.err(Status.ERR_NsNotFound, "No Namespace for [%s]", str);
400 return deriveFirstNsForType(trans, str.substring(0, dot),type);
404 return Result.err(Status.ERR_NsNotFound,"There is no valid Company Namespace for %s",str);
407 return Result.err(Status.ERR_NotFound, str + " does not contain type " + type.name());
410 public Result<NsSplit> deriveNsSplit(AuthzTrans trans, String child) {
411 Result<NsDAO.Data> ndd = deriveNs(trans, child);
413 NsSplit nss = new NsSplit(ndd.value, child);
415 return Result.ok(nss);
417 return Result.err(Status.ERR_NsNotFound,
418 "Cannot split [%s] into valid namespace elements",
422 return Result.err(ndd);
426 * Translate an ID into it's domain
428 * i.e. myid1234@aaf.att.com results in domain of com.att.aaf
433 public static String domain2ns(String id) {
434 int at = id.indexOf('@');
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) {
445 ns.append(domain[i]);
447 return ns.toString();
455 * Validate Namespace of ID@Domain
457 * Namespace is reverse order of Domain.
463 public Result<NsDAO.Data> validNSOfDomain(AuthzTrans trans, String id) {
464 // Take domain, reverse order, and check on NS
466 if (id.indexOf('@')<0) { // it's already an ns, not an ID
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));
479 return Result.err(Status.ERR_NsNotFound,
480 "A Namespace is not available for %s", id);
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;
488 if (isGranted(trans, user, ns, ACCESS, ":ns", access.name())) {
489 return Result.ok(ndd);
491 if ((last = ns.lastIndexOf('.')) >= 0) {
492 ns = ns.substring(0, last);
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());
501 } else if (rv.status==Result.ERR_Backend) {
502 return Result.err(rv);
504 return Result.err(Status.ERR_Denied, "[%s] may not %s in NS [%s]",
505 user, access.name(), ndd.name);
509 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, RoleDAO.Data rdd, Access access) {
510 Result<NsDAO.Data> rnsd = deriveNs(trans, rdd.ns);
512 return mayUser(trans, user, rnsd.value, rdd, access);
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);
524 String roleInst = ":role:" + rdd.name;
525 // <ns>.access|:role:<role name>|<read|write>
529 if (isGranted(trans, user, ns,ACCESS, roleInst, access.name())) {
530 return Result.ok(ndd);
532 if ((last = ns.lastIndexOf('.')) >= 0) {
533 ns = ns.substring(0, last);
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());
543 } else if (rnsd.status==Result.ERR_Backend) {
544 return Result.err(rnsd);
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());
554 } else if (rnsd.status==Result.ERR_Backend) {
555 return Result.err(rnsd);
557 return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]",
558 user, access.name(), rdd.fullName());
563 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,PermDAO.Data pdd, Access access) {
564 Result<NsDAO.Data> rnsd = deriveNs(trans, pdd.ns);
566 return mayUser(trans, user, rnsd.value, pdd, access);
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);
575 String permInst = ":perm:" + pdd.type + ':' + pdd.instance + ':' + pdd.action;
576 // <ns>.access|:role:<role name>|<read|write>
577 String ns = ndd.name;
580 if (isGranted(trans, user, ns, ACCESS, permInst, access.name())) {
581 return Result.ok(ndd);
583 if ((last = ns.lastIndexOf('.')) >= 0) {
584 ns = ns.substring(0, last);
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());
593 } else if (rnsd.status==Result.ERR_Backend) {
594 return Result.err(rnsd);
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());
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);
611 public Result<Void> mayUser(AuthzTrans trans, DelegateDAO.Data dd, Access access) {
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()) {
617 boolean isUser = trans.user().equals(dd.user);
618 boolean isDelegate = dd.delegate != null
619 && (dd.user.equals(dd.delegate) || trans.user().equals(
621 Organization org = trans.org();
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.",
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.",
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);
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);
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);
655 return Result.err(Status.ERR_BadData,"Unknown Access type [%s]", access.name());
657 } catch (Exception e) {
658 return Result.err(e);
664 * Check (recursively, if necessary), if able to do something based on NS
666 private Result<NsDAO.Data> mayUserVirtueOfNS(AuthzTrans trans, String user, NsDAO.Data nsd, String ns_and_type, String access) {
667 String ns = nsd.name;
669 // If an ADMIN of the Namespace, then allow
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);
678 // If Specially granted Global Permission
679 if (isGranted(trans, user, ROOT_NS,NS, ns_and_type, access)) {
680 return Result.ok(nsd);
685 int dot = ns.length();
686 if ((dot = ns.lastIndexOf('.', dot - 1)) >= 0) {
687 Result<NsDAO.Data> rnsd = deriveNs(trans, ns.substring(0, dot));
689 rnsd = mayUserVirtueOfNS(trans, user, rnsd.value, ns_and_type,access);
690 } else if (rnsd.status==Result.ERR_Backend) {
691 return Result.err(rnsd);
694 return Result.ok(nsd);
695 } else if (rnsd.status==Result.ERR_Backend) {
696 return Result.err(rnsd);
699 return Result.err(Status.ERR_Denied, "%s may not %s %s", user, access,
707 * Important function - Check internal Permission Schemes for Permission to
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);
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
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);
738 result = credDAO.readID(trans, user);
743 Result<Date> rv = null;
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");
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) {
762 Collections.sort(cddl,new Comparator<CredDAO.Data>() {
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);
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);
780 if (cdd.expires.after(now)) {
781 byte[] dbcred = cdd.cred.array();
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) {
794 case CredDAO.BASIC_AUTH_SHA256:
795 ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.length);
796 bb.putInt(cdd.other);
798 byte[] hash = Hash.hashSHA256(bb.array());
800 if (Hash.compareTo(hash,dbcred)==0) {
801 checkLessThanDays(trans,7,now,cdd);
802 return Result.ok(cdd.expires);
803 } else if (debug!=null) {
808 trans.error().log("Unknown Credential Type %s for %s, %s",Integer.toString(cdd.type),cdd.id, Chrono.dateTime(cdd.expires));
810 } catch (NoSuchAlgorithmException e) {
811 trans.error().log(e);
814 if (expired==null || expired.before(cdd.expires)) {
815 expired = cdd.expires;
820 trans.audit().printf("No cred matches ip=%s, user=%s\n",trans.ip(),user);
822 trans.audit().printf("No cred matches ip=%s, user=%s %s\n",trans.ip(),user,debug.toString());
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));
831 return Result.err(result);
833 return rv == null ? Result.create((Date) null, Status.ERR_Security, "Wrong credential") : rv;
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));
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();
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");
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);
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);
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());
878 return Result.err(Status.ERR_Security,"invalid/unreadable credential");
881 public Result<Boolean> userCredCheck(AuthzTrans trans, CredDAO.Data orig, final byte[] raw) {
882 TimeTaken tt = trans.start("CheckCred Cred", Env.SUB);
885 case CredDAO.BASIC_AUTH_SHA256:
886 ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + raw.length);
887 bb.putInt(orig.other);
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);
893 return Result.ok(false);
895 } catch (NoSuchAlgorithmException e) {
896 return Result.err(Status.ERR_General,e.getLocalizedMessage());
902 public static final String APPROVED = "APPROVE";
903 public static final String REJECT = "REJECT";
904 public static final String PENDING = "PENDING";
906 public Result<Void> canAddUser(AuthzTrans trans, UserRoleDAO.Data data,
907 List<ApprovalDAO.Data> approvals) {
908 // get the approval policy for the organization
910 // get the list of approvals with an accept status
912 // validate the approvals against the policy
914 // for now check if all approvals are received and return
915 // SUCCESS/FAILURE/SKIP
916 boolean bReject = false;
917 boolean bPending = false;
919 for (ApprovalDAO.Data approval : approvals) {
920 if (approval.status.equals(REJECT)) {
922 } else if (approval.status.equals(PENDING)) {
927 return Result.err(Status.ERR_Policy,
928 "Approval Polocy not conformed");
931 return Result.err(Status.ERR_ActionNotCompleted,
932 "Required Approvals not received");
938 private static final String NO_CACHE_NAME = "No Cache Data named %s";
940 public Result<Void> clearCache(AuthzTrans trans, String cname) {
941 boolean all = "all".equals(cname);
942 Result<Void> rv = null;
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);
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);
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);
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);
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);
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);
976 rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname);
981 public Result<Void> cacheClear(AuthzTrans trans, String cname,Integer segment) {
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);
996 rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname);
1001 private int[] series(int max) {
1002 int[] series = new int[max];
1003 for (int i = 0; i < max; ++i)
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);
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())) {
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) {
1031 b = specialLog.contains(user);
1032 trans.put(specialLogSlot, b);
1038 public static void logEncryptTrace(AuthzTrans trans, String data) {
1040 trans.put(transIDSlot, ti=nextTraceID());
1041 trans.trace().log("id="+Long.toHexString(ti)+",data=\""+trans.env().encryptor().encrypt(data)+'"');
1044 private synchronized static long nextTraceID() {
1048 public static synchronized boolean specialLogOn(AuthzTrans trans, String id) {
1049 if (specialLog == null) {
1050 specialLog = new HashSet<>();
1052 boolean rc = specialLog.add(id);
1054 trans.trace().printf("Trace on for %s requested by %s",id,trans.user());
1059 public static synchronized boolean specialLogOff(AuthzTrans trans, String id) {
1060 if (specialLog==null) {
1063 boolean rv = specialLog.remove(id);
1064 if (specialLog.isEmpty()) {
1068 trans.trace().printf("Trace off for %s requested by %s",id,trans.user());
1075 * Which Types can be moved
1079 public boolean canMove(NsType nsType) {
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)) {
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)) {
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();
1120 if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){
1121 if (urdd.expires.after(now)) {
1129 * Return a Unique String, (same string, if it is already unique), with only
1130 * lowercase letters, digits and the '.' character.
1134 * @throws IOException
1136 public static String toUnique(String name) throws IOException {
1137 byte[] from = name.getBytes();
1138 StringBuilder sb = new StringBuilder();
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));
1145 return sb.toString();
1148 public static String fromUnique(String name) throws IOException {
1149 byte[] from = name.getBytes();
1150 StringBuilder sb = new StringBuilder();
1152 for (int i=0;i<from.length;++i) {
1153 c = (char)((from[i]-0x61)<<4);
1154 c |= (from[++i]-0x61);
1157 return sb.toString();