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 int dot = str.lastIndexOf('.');
407 return Result.err(Status.ERR_NsNotFound,"There is no valid Company Namespace for %s",str);
409 return deriveFirstNsForType(trans, str.substring(0, dot),type);
413 return Result.err(Status.ERR_NotFound, str + " does not contain type " + type.name());
416 public Result<NsSplit> deriveNsSplit(AuthzTrans trans, String child) {
417 Result<NsDAO.Data> ndd = deriveNs(trans, child);
419 NsSplit nss = new NsSplit(ndd.value, child);
421 return Result.ok(nss);
423 return Result.err(Status.ERR_NsNotFound,
424 "Cannot split [%s] into valid namespace elements",
428 return Result.err(ndd);
432 * Translate an ID into it's domain
434 * i.e. myid1234@aaf.att.com results in domain of com.att.aaf
439 public static String domain2ns(String id) {
440 int at = id.indexOf('@');
442 String[] domain = id.substring(at + 1).split("\\.");
443 StringBuilder ns = new StringBuilder(id.length());
444 boolean first = true;
445 for (int i = domain.length - 1; i >= 0; --i) {
451 ns.append(domain[i]);
453 return ns.toString();
461 * Validate Namespace of ID@Domain
463 * Namespace is reverse order of Domain.
469 public Result<NsDAO.Data> validNSOfDomain(AuthzTrans trans, String id) {
470 // Take domain, reverse order, and check on NS
472 if (id.indexOf('@')<0) { // it's already an ns, not an ID
477 if (ns.length() > 0) {
478 if (!trans.org().getDomain().equals(ns)) {
479 Result<List<NsDAO.Data>> rlnsd = nsDAO.read(trans, ns);
480 if (rlnsd.isOKhasData()) {
481 return Result.ok(rlnsd.value.get(0));
485 return Result.err(Status.ERR_NsNotFound,
486 "A Namespace is not available for %s", id);
489 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, Access access) {
490 // <ns>.access|:role:<role name>|<read|write>
491 String ns = ndd.name;
494 if (isGranted(trans, user, ns, ACCESS, ":ns", access.name())) {
495 return Result.ok(ndd);
497 if ((last = ns.lastIndexOf('.')) >= 0) {
498 ns = ns.substring(0, last);
501 // com.att.aaf.ns|:<client ns>:ns|<access>
502 // AAF-724 - Make consistent response for May User", and not take the
503 // last check... too confusing.
504 Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":" + ndd.name + ":ns", access.name());
507 } else if (rv.status==Result.ERR_Backend) {
508 return Result.err(rv);
510 return Result.err(Status.ERR_Denied, "[%s] may not %s in NS [%s]",
511 user, access.name(), ndd.name);
515 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, RoleDAO.Data rdd, Access access) {
516 Result<NsDAO.Data> rnsd = deriveNs(trans, rdd.ns);
518 return mayUser(trans, user, rnsd.value, rdd, access);
523 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, NsDAO.Data ndd, RoleDAO.Data rdd, Access access) {
524 // 1) Is User in the Role?
525 Result<List<UserRoleDAO.Data>> rurd = userRoleDAO.readUserInRole(trans, user, rdd.fullName());
526 if (rurd.isOKhasData()) {
527 return Result.ok(ndd);
530 String roleInst = ":role:" + rdd.name;
531 // <ns>.access|:role:<role name>|<read|write>
535 if (isGranted(trans, user, ns,ACCESS, roleInst, access.name())) {
536 return Result.ok(ndd);
538 if ((last = ns.lastIndexOf('.')) >= 0) {
539 ns = ns.substring(0, last);
543 // Check if Access by Global Role perm
544 // com.att.aaf.ns|:<client ns>:role:name|<access>
545 Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":"
546 + rdd.ns + roleInst, access.name());
549 } else if (rnsd.status==Result.ERR_Backend) {
550 return Result.err(rnsd);
553 // Check if Access to Whole NS
554 // AAF-724 - Make consistent response for May User", and not take the
555 // last check... too confusing.
556 Result<org.onap.aaf.auth.dao.cass.NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd,
557 ":" + rdd.ns + ":ns", access.name());
560 } else if (rnsd.status==Result.ERR_Backend) {
561 return Result.err(rnsd);
563 return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]",
564 user, access.name(), rdd.fullName());
569 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,PermDAO.Data pdd, Access access) {
570 Result<NsDAO.Data> rnsd = deriveNs(trans, pdd.ns);
572 return mayUser(trans, user, rnsd.value, pdd, access);
577 public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, PermDAO.Data pdd, Access access) {
578 if (isGranted(trans, user, pdd.ns, pdd.type, pdd.instance, pdd.action)) {
579 return Result.ok(ndd);
581 String permInst = ":perm:" + pdd.type + ':' + pdd.instance + ':' + pdd.action;
582 // <ns>.access|:role:<role name>|<read|write>
583 String ns = ndd.name;
586 if (isGranted(trans, user, ns, ACCESS, permInst, access.name())) {
587 return Result.ok(ndd);
589 if ((last = ns.lastIndexOf('.')) >= 0) {
590 ns = ns.substring(0, last);
594 // Check if Access by NS perm
595 // com.att.aaf.ns|:<client ns>:role:name|<access>
596 Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + permInst, access.name());
599 } else if (rnsd.status==Result.ERR_Backend) {
600 return Result.err(rnsd);
603 // Check if Access to Whole NS
604 // AAF-724 - Make consistent response for May User", and not take the
605 // last check... too confusing.
606 Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + ":ns", access.name());
610 return Result.err(Status.ERR_Denied,
611 "[%s] may not %s Perm [%s|%s|%s]", user, access.name(),
612 pdd.fullType(), pdd.instance, pdd.action);
617 public Result<Void> mayUser(AuthzTrans trans, DelegateDAO.Data dd, Access access) {
619 Result<NsDAO.Data> rnsd = deriveNs(trans, domain2ns(trans.user()));
620 if (rnsd.isOKhasData() && mayUserVirtueOfNS(trans,trans.user(),rnsd.value, ":" + rnsd.value.name + ":ns", access.name()).isOK()) {
623 boolean isUser = trans.user().equals(dd.user);
624 boolean isDelegate = dd.delegate != null
625 && (dd.user.equals(dd.delegate) || trans.user().equals(
627 Organization org = trans.org();
630 if (org.getIdentity(trans, dd.user) == null) {
631 return Result.err(Status.ERR_UserNotFound,
632 "[%s] is not a user in the company database.",
635 if (!dd.user.equals(dd.delegate) && org.getIdentity(trans, dd.delegate) == null) {
636 return Result.err(Status.ERR_UserNotFound,
637 "[%s] is not a user in the company database.",
640 if (!trans.requested(REQD_TYPE.force) && dd.user != null && dd.user.equals(dd.delegate)) {
641 return Result.err(Status.ERR_BadData,
642 "[%s] cannot be a delegate for self", dd.user);
644 if (!isUser && !isGranted(trans, trans.user(), ROOT_NS,DELG,
645 org.getDomain(), Question.CREATE)) {
646 return Result.err(Status.ERR_Denied,
647 "[%s] may not create a delegate for [%s]",
648 trans.user(), dd.user);
653 if (!isUser && !isDelegate &&
654 !isGranted(trans, trans.user(), ROOT_NS,DELG,org.getDomain(), access.name())) {
655 return Result.err(Status.ERR_Denied,
656 "[%s] may not %s delegates for [%s]", trans.user(),
657 access.name(), dd.user);
661 return Result.err(Status.ERR_BadData,"Unknown Access type [%s]", access.name());
663 } catch (Exception e) {
664 return Result.err(e);
670 * Check (recursively, if necessary), if able to do something based on NS
672 private Result<NsDAO.Data> mayUserVirtueOfNS(AuthzTrans trans, String user, NsDAO.Data nsd, String ns_and_type, String access) {
673 String ns = nsd.name;
675 // If an ADMIN of the Namespace, then allow
677 Result<List<UserRoleDAO.Data>> rurd;
678 if ((rurd = userRoleDAO.readUserInRole(trans, user, ns+DOT_ADMIN)).isOKhasData()) {
679 return Result.ok(nsd);
680 } else if (rurd.status==Result.ERR_Backend) {
681 return Result.err(rurd);
684 // If Specially granted Global Permission
685 if (isGranted(trans, user, ROOT_NS,NS, ns_and_type, access)) {
686 return Result.ok(nsd);
691 int dot = ns.length();
692 if ((dot = ns.lastIndexOf('.', dot - 1)) >= 0) {
693 Result<NsDAO.Data> rnsd = deriveNs(trans, ns.substring(0, dot));
695 rnsd = mayUserVirtueOfNS(trans, user, rnsd.value, ns_and_type,access);
696 } else if (rnsd.status==Result.ERR_Backend) {
697 return Result.err(rnsd);
700 return Result.ok(nsd);
701 } else if (rnsd.status==Result.ERR_Backend) {
702 return Result.err(rnsd);
705 return Result.err(Status.ERR_Denied, "%s may not %s %s", user, access,
713 * Important function - Check internal Permission Schemes for Permission to
722 public boolean isGranted(AuthzTrans trans, String user, String ns, String type,String instance, String action) {
723 Result<List<PermDAO.Data>> perms = getPermsByUser(trans, user, false);
725 for (PermDAO.Data pd : perms.value) {
726 if (ns.equals(pd.ns)) {
727 if (type.equals(pd.type)) {
728 if (PermEval.evalInstance(pd.instance, instance)) {
729 if (PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action
740 public Result<Date> doesUserCredMatch(AuthzTrans trans, String user, byte[] cred) throws DAOException {
741 Result<List<CredDAO.Data>> result;
742 TimeTaken tt = trans.start("Read DB Cred", Env.REMOTE);
744 result = credDAO.readID(trans, user);
749 Result<Date> rv = null;
751 if (result.isEmpty()) {
752 rv = Result.err(Status.ERR_UserNotFound, user);
753 if (willSpecialLog(trans,user)) {
754 trans.audit().log("Special DEBUG:", user, " does not exist in DB");
757 Date now = new Date();//long now = System.currentTimeMillis();
758 // Bug noticed 6/22. Sorting on the result can cause Concurrency Issues.
759 List<CredDAO.Data> cddl;
760 if (result.value.size() > 1) {
761 cddl = new ArrayList<>(result.value.size());
762 for (CredDAO.Data old : result.value) {
763 if (old.type==CredDAO.BASIC_AUTH || old.type==CredDAO.BASIC_AUTH_SHA256) {
768 Collections.sort(cddl,new Comparator<CredDAO.Data>() {
770 public int compare(org.onap.aaf.auth.dao.cass.CredDAO.Data a,
771 org.onap.aaf.auth.dao.cass.CredDAO.Data b) {
772 return b.expires.compareTo(a.expires);
781 StringBuilder debug = willSpecialLog(trans,user)?new StringBuilder():null;
782 for (CredDAO.Data cdd : cddl) {
783 if (!cdd.id.equals(user)) {
784 trans.error().log("doesUserCredMatch DB call does not match for user: " + user);
786 if (cdd.expires.after(now)) {
787 byte[] dbcred = cdd.cred.array();
791 case CredDAO.BASIC_AUTH:
792 byte[] md5=Hash.hashMD5(cred);
793 if (Hash.compareTo(md5,dbcred)==0) {
794 checkLessThanDays(trans,7,now,cdd);
795 return Result.ok(cdd.expires);
796 } else if (debug!=null) {
800 case CredDAO.BASIC_AUTH_SHA256:
801 ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.length);
802 bb.putInt(cdd.other);
804 byte[] hash = Hash.hashSHA256(bb.array());
806 if (Hash.compareTo(hash,dbcred)==0) {
807 checkLessThanDays(trans,7,now,cdd);
808 return Result.ok(cdd.expires);
809 } else if (debug!=null) {
814 trans.error().log("Unknown Credential Type %s for %s, %s",Integer.toString(cdd.type),cdd.id, Chrono.dateTime(cdd.expires));
816 } catch (NoSuchAlgorithmException e) {
817 trans.error().log(e);
820 if (expired==null || expired.before(cdd.expires)) {
821 expired = cdd.expires;
826 trans.audit().printf("No cred matches ip=%s, user=%s\n",trans.ip(),user);
828 trans.audit().printf("No cred matches ip=%s, user=%s %s\n",trans.ip(),user,debug.toString());
831 // Note: this is only returned if there are no good Credentials
832 rv = Result.err(Status.ERR_Security,
833 "Credentials %s from %s expired %s",trans.user(), trans.ip(), Chrono.dateTime(expired));
837 return Result.err(result);
839 return rv == null ? Result.create((Date) null, Status.ERR_Security, "Wrong credential") : rv;
843 private void load(StringBuilder debug, Data cdd) {
844 debug.append("DB Entry: user=");
845 debug.append(cdd.id);
846 debug.append(",type=");
847 debug.append(cdd.type);
848 debug.append(",expires=");
849 debug.append(Chrono.dateTime(cdd.expires));
854 private void checkLessThanDays(AuthzTrans trans, int days, Date now, Data cdd) {
855 long close = now.getTime() + (days * 86400000);
856 long cexp=cdd.expires.getTime();
858 int daysLeft = days-(int)((close-cexp)/86400000);
859 trans.audit().printf("user=%s,ip=%s,expires=%s,days=%d,msg=\"Password expires in less than %d day%s\"",
860 cdd.id,trans.ip(),Chrono.dateOnlyStamp(cdd.expires),daysLeft, daysLeft,daysLeft==1?"":"s");
865 public Result<CredDAO.Data> userCredSetup(AuthzTrans trans, CredDAO.Data cred) {
866 if (cred.type==CredDAO.RAW) {
867 TimeTaken tt = trans.start("Hash Cred", Env.SUB);
869 cred.type = CredDAO.BASIC_AUTH_SHA256;
870 cred.other = random.nextInt();
871 ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.cred.capacity());
872 bb.putInt(cred.other);
874 byte[] hash = Hash.hashSHA256(bb.array());
875 cred.cred = ByteBuffer.wrap(hash);
876 return Result.ok(cred);
877 } catch (NoSuchAlgorithmException e) {
878 return Result.err(Status.ERR_General,e.getLocalizedMessage());
884 return Result.err(Status.ERR_Security,"invalid/unreadable credential");
887 public Result<Boolean> userCredCheck(AuthzTrans trans, CredDAO.Data orig, final byte[] raw) {
888 TimeTaken tt = trans.start("CheckCred Cred", Env.SUB);
891 case CredDAO.BASIC_AUTH_SHA256:
892 ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + raw.length);
893 bb.putInt(orig.other);
895 return Result.ok(Hash.compareTo(orig.cred.array(),Hash.hashSHA256(bb.array()))==0);
896 case CredDAO.BASIC_AUTH:
897 return Result.ok( Hash.compareTo(orig.cred.array(), Hash.hashMD5(raw))==0);
899 return Result.ok(false);
901 } catch (NoSuchAlgorithmException e) {
902 return Result.err(Status.ERR_General,e.getLocalizedMessage());
908 public static final String APPROVED = "APPROVE";
909 public static final String REJECT = "REJECT";
910 public static final String PENDING = "PENDING";
912 public Result<Void> canAddUser(AuthzTrans trans, UserRoleDAO.Data data,
913 List<ApprovalDAO.Data> approvals) {
914 // get the approval policy for the organization
916 // get the list of approvals with an accept status
918 // validate the approvals against the policy
920 // for now check if all approvals are received and return
921 // SUCCESS/FAILURE/SKIP
922 boolean bReject = false;
923 boolean bPending = false;
925 for (ApprovalDAO.Data approval : approvals) {
926 if (approval.status.equals(REJECT)) {
928 } else if (approval.status.equals(PENDING)) {
933 return Result.err(Status.ERR_Policy,
934 "Approval Polocy not conformed");
937 return Result.err(Status.ERR_ActionNotCompleted,
938 "Required Approvals not received");
944 private static final String NO_CACHE_NAME = "No Cache Data named %s";
946 public Result<Void> clearCache(AuthzTrans trans, String cname) {
947 boolean all = "all".equals(cname);
948 Result<Void> rv = null;
950 if (all || NsDAO.TABLE.equals(cname)) {
951 int seg[] = series(NsDAO.CACHE_SEG);
952 for (int i: seg) {cacheClear(trans, NsDAO.TABLE,i);}
953 rv = cacheInfoDAO.touch(trans, NsDAO.TABLE, seg);
955 if (all || PermDAO.TABLE.equals(cname)) {
956 int seg[] = series(PermDAO.CACHE_SEG);
957 for (int i: seg) {cacheClear(trans, PermDAO.TABLE,i);}
958 rv = cacheInfoDAO.touch(trans, PermDAO.TABLE,seg);
960 if (all || RoleDAO.TABLE.equals(cname)) {
961 int seg[] = series(RoleDAO.CACHE_SEG);
962 for (int i: seg) {cacheClear(trans, RoleDAO.TABLE,i);}
963 rv = cacheInfoDAO.touch(trans, RoleDAO.TABLE,seg);
965 if (all || UserRoleDAO.TABLE.equals(cname)) {
966 int seg[] = series(UserRoleDAO.CACHE_SEG);
967 for (int i: seg) {cacheClear(trans, UserRoleDAO.TABLE,i);}
968 rv = cacheInfoDAO.touch(trans, UserRoleDAO.TABLE,seg);
970 if (all || CredDAO.TABLE.equals(cname)) {
971 int seg[] = series(CredDAO.CACHE_SEG);
972 for (int i: seg) {cacheClear(trans, CredDAO.TABLE,i);}
973 rv = cacheInfoDAO.touch(trans, CredDAO.TABLE,seg);
975 if (all || CertDAO.TABLE.equals(cname)) {
976 int seg[] = series(CertDAO.CACHE_SEG);
977 for (int i: seg) {cacheClear(trans, CertDAO.TABLE,i);}
978 rv = cacheInfoDAO.touch(trans, CertDAO.TABLE,seg);
982 rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname);
987 public Result<Void> cacheClear(AuthzTrans trans, String cname,Integer segment) {
989 if (NsDAO.TABLE.equals(cname)) {
990 rv = nsDAO.invalidate(segment);
991 } else if (PermDAO.TABLE.equals(cname)) {
992 rv = permDAO.invalidate(segment);
993 } else if (RoleDAO.TABLE.equals(cname)) {
994 rv = roleDAO.invalidate(segment);
995 } else if (UserRoleDAO.TABLE.equals(cname)) {
996 rv = userRoleDAO.invalidate(segment);
997 } else if (CredDAO.TABLE.equals(cname)) {
998 rv = credDAO.invalidate(segment);
999 } else if (CertDAO.TABLE.equals(cname)) {
1000 rv = certDAO.invalidate(segment);
1002 rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname);
1007 private int[] series(int max) {
1008 int[] series = new int[max];
1009 for (int i = 0; i < max; ++i)
1014 public boolean isDelegated(AuthzTrans trans, String user, String approver, Map<String,Result<List<DelegateDAO.Data>>> rldd ) {
1015 Result<List<DelegateDAO.Data>> userDelegatedFor = rldd.get(user);
1016 if (userDelegatedFor==null) {
1017 userDelegatedFor=delegateDAO.readByDelegate(trans, user);
1018 rldd.put(user, userDelegatedFor);
1020 if (userDelegatedFor.isOKhasData()) {
1021 for (DelegateDAO.Data curr : userDelegatedFor.value) {
1022 if (curr.user.equals(approver) && curr.delegate.equals(user)
1023 && curr.expires.after(new Date())) {
1031 public static boolean willSpecialLog(AuthzTrans trans, String user) {
1032 Boolean b = trans.get(specialLogSlot, null);
1033 if (b==null) { // we haven't evaluated in this trans for Special Log yet
1034 if (specialLog==null) {
1037 b = specialLog.contains(user);
1038 trans.put(specialLogSlot, b);
1044 public static void logEncryptTrace(AuthzTrans trans, String data) {
1046 trans.put(transIDSlot, ti=nextTraceID());
1047 trans.trace().log("id="+Long.toHexString(ti)+",data=\""+trans.env().encryptor().encrypt(data)+'"');
1050 private synchronized static long nextTraceID() {
1054 public static synchronized boolean specialLogOn(AuthzTrans trans, String id) {
1055 if (specialLog == null) {
1056 specialLog = new HashSet<>();
1058 boolean rc = specialLog.add(id);
1060 trans.trace().printf("Trace on for %s requested by %s",id,trans.user());
1065 public static synchronized boolean specialLogOff(AuthzTrans trans, String id) {
1066 if (specialLog==null) {
1069 boolean rv = specialLog.remove(id);
1070 if (specialLog.isEmpty()) {
1074 trans.trace().printf("Trace off for %s requested by %s",id,trans.user());
1081 * Which Types can be moved
1085 public boolean canMove(NsType nsType) {
1100 public boolean isAdmin(AuthzTrans trans, String user, String ns) {
1101 Date now = new Date();
1102 Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_ADMIN);
1103 if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){
1104 if (urdd.expires.after(now)) {
1111 public boolean isOwner(AuthzTrans trans, String user, String ns) {
1112 Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_OWNER);
1113 Date now = new Date();
1114 if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){
1115 if (urdd.expires.after(now)) {
1122 public int countOwner(AuthzTrans trans, String ns) {
1123 Result<List<UserRoleDAO.Data>> rur = userRoleDAO.readByRole(trans,ns+DOT_OWNER);
1124 Date now = new Date();
1126 if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){
1127 if (urdd.expires.after(now)) {
1135 * Return a Unique String, (same string, if it is already unique), with only
1136 * lowercase letters, digits and the '.' character.
1140 * @throws IOException
1142 public static String toUnique(String name) throws IOException {
1143 byte[] from = name.getBytes();
1144 StringBuilder sb = new StringBuilder();
1146 for (int i=0;i<from.length;++i) {
1147 f=(byte)(from[i]); // printables;
1148 sb.append((char)((f>>4)+0x61));
1149 sb.append((char)((f&0x0F)+0x61));
1151 return sb.toString();
1154 public static String fromUnique(String name) throws IOException {
1155 byte[] from = name.getBytes();
1156 StringBuilder sb = new StringBuilder();
1158 for (int i=0;i<from.length;++i) {
1159 c = (char)((from[i]-0x61)<<4);
1160 c |= (from[++i]-0x61);
1163 return sb.toString();