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.service;
24 import static org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE.force;
25 import static org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE.future;
26 import static org.onap.aaf.auth.layer.Result.OK;
27 import static org.onap.aaf.auth.rserv.HttpMethods.DELETE;
28 import static org.onap.aaf.auth.rserv.HttpMethods.GET;
29 import static org.onap.aaf.auth.rserv.HttpMethods.POST;
30 import static org.onap.aaf.auth.rserv.HttpMethods.PUT;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.Comparator;
37 import java.util.Date;
38 import java.util.GregorianCalendar;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.List;
44 import java.util.TreeMap;
45 import java.util.UUID;
47 import javax.servlet.http.HttpServletRequest;
49 import org.onap.aaf.auth.common.Define;
50 import org.onap.aaf.auth.dao.DAOException;
51 import org.onap.aaf.auth.dao.cass.ApprovalDAO;
52 import org.onap.aaf.auth.dao.cass.CertDAO;
53 import org.onap.aaf.auth.dao.cass.CredDAO;
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.Namespace;
58 import org.onap.aaf.auth.dao.cass.NsDAO;
59 import org.onap.aaf.auth.dao.cass.NsDAO.Data;
60 import org.onap.aaf.auth.dao.cass.NsSplit;
61 import org.onap.aaf.auth.dao.cass.NsType;
62 import org.onap.aaf.auth.dao.cass.PermDAO;
63 import org.onap.aaf.auth.dao.cass.RoleDAO;
64 import org.onap.aaf.auth.dao.cass.Status;
65 import org.onap.aaf.auth.dao.cass.UserRoleDAO;
66 import org.onap.aaf.auth.dao.hl.CassExecutor;
67 import org.onap.aaf.auth.dao.hl.Function;
68 import org.onap.aaf.auth.dao.hl.Function.FUTURE_OP;
69 import org.onap.aaf.auth.dao.hl.Function.Lookup;
70 import org.onap.aaf.auth.dao.hl.Function.OP_STATUS;
71 import org.onap.aaf.auth.dao.hl.Question;
72 import org.onap.aaf.auth.dao.hl.Question.Access;
73 import org.onap.aaf.auth.env.AuthzTrans;
74 import org.onap.aaf.auth.layer.Result;
75 import org.onap.aaf.auth.org.Executor;
76 import org.onap.aaf.auth.org.Organization;
77 import org.onap.aaf.auth.org.Organization.Expiration;
78 import org.onap.aaf.auth.org.Organization.Identity;
79 import org.onap.aaf.auth.org.Organization.Policy;
80 import org.onap.aaf.auth.org.OrganizationException;
81 import org.onap.aaf.auth.rserv.doc.ApiDoc;
82 import org.onap.aaf.auth.service.mapper.Mapper;
83 import org.onap.aaf.auth.service.mapper.Mapper.API;
84 import org.onap.aaf.auth.service.validation.ServiceValidator;
85 import org.onap.aaf.auth.validation.Validator;
86 import org.onap.aaf.cadi.principal.BasicPrincipal;
87 import org.onap.aaf.misc.env.Env;
88 import org.onap.aaf.misc.env.TimeTaken;
89 import org.onap.aaf.misc.env.util.Chrono;
90 import org.onap.aaf.misc.env.util.Split;
92 import aaf.v2_0.CredRequest;
95 * AuthzCassServiceImpl implements AuthzCassService for
110 public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS>
111 implements AuthzService <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> {
113 private Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper;
115 public Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper() {return mapper;}
117 private static final String ASTERIX = "*";
118 private static final String CACHE = "cache";
119 private static final String ROOT_NS = Define.ROOT_NS();
120 private static final String ROOT_COMPANY = Define.ROOT_COMPANY();
122 private final Question ques;
123 private final Function func;
125 public AuthzCassServiceImpl(AuthzTrans trans, Mapper<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper,Question question) {
126 this.ques = question;
127 func = new Function(trans, question);
128 this.mapper = mapper;
132 /***********************************
134 ***********************************/
137 * @throws DAOException
138 * @see org.onap.aaf.auth.service.AuthzService#createNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String)
145 errorCodes = { 403,404,406,409 },
146 text = { "Namespace consists of: ",
147 "<ul><li>name - What you want to call this Namespace</li>",
148 "<li>responsible(s) - Person(s) who receive Notifications and approves Requests ",
149 "regarding this Namespace. Companies have Policies as to who may take on ",
150 "this Responsibility. Separate multiple identities with commas</li>",
151 "<li>admin(s) - Person(s) who are allowed to make changes on the namespace, ",
152 "including creating Roles, Permissions and Credentials. Separate multiple ",
153 "identities with commas</li></ul>",
154 "Note: Namespaces are dot-delimited (i.e. com.myCompany.myApp) and must be ",
155 "created with parent credentials (i.e. To create com.myCompany.myApp, you must ",
156 "be an admin of com.myCompany or com"
160 public Result<Void> createNS(final AuthzTrans trans, REQUEST from, NsType type) {
161 final Result<Namespace> rnamespace = mapper.ns(trans, from);
162 final ServiceValidator v = new ServiceValidator();
163 if(v.ns(rnamespace).err()) {
164 return Result.err(Status.ERR_BadData,v.errs());
166 final Namespace namespace = rnamespace.value;
167 final Result<NsDAO.Data> parentNs = ques.deriveNs(trans,namespace.name);
168 if(parentNs.notOK()) {
169 return Result.err(parentNs);
172 if(namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed
173 return func.createNS(trans, namespace, false);
176 Result<FutureDAO.Data> fd = mapper.future(trans, NsDAO.TABLE,from,namespace,true,
179 public String get() {
180 return "Create Namespace [" + namespace.name + ']';
184 private Result<NsDAO.Data> rnd;
186 public Result<?> mayChange() {
188 rnd = ques.mayUser(trans, trans.user(), parentNs.value,Access.write);
195 Result<String> rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, FUTURE_OP.C);
197 return Result.err(Status.ACC_Future, "NS [%s] is saved for future processing",namespace.name);
199 return Result.err(rfc);
202 return func.createNS(trans, namespace, false);
204 return Result.err(fd);
210 path = "/authz/ns/:ns/admin/:id",
211 params = { "ns|string|true",
215 errorCodes = { 403,404,406,409 },
216 text = { "Add an Identity :id to the list of Admins for the Namespace :ns",
217 "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" }
220 public Result<Void> addAdminNS(AuthzTrans trans, String ns, String id) {
221 return func.addUserRole(trans, id, ns,Question.ADMIN);
226 path = "/authz/ns/:ns/admin/:id",
227 params = { "ns|string|true",
231 errorCodes = { 403,404 },
232 text = { "Remove an Identity :id from the list of Admins for the Namespace :ns",
233 "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" }
236 public Result<Void> delAdminNS(AuthzTrans trans, String ns, String id) {
237 return func.delAdmin(trans,ns,id);
242 path = "/authz/ns/:ns/responsible/:id",
243 params = { "ns|string|true",
247 errorCodes = { 403,404,406,409 },
248 text = { "Add an Identity :id to the list of Responsibles for the Namespace :ns",
249 "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" }
252 public Result<Void> addResponsibleNS(AuthzTrans trans, String ns, String id) {
253 return func.addUserRole(trans,id,ns,Question.OWNER);
258 path = "/authz/ns/:ns/responsible/:id",
259 params = { "ns|string|true",
263 errorCodes = { 403,404 },
264 text = { "Remove an Identity :id to the list of Responsibles for the Namespace :ns",
265 "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)",
266 "Note: A namespace must have at least 1 responsible party"
270 public Result<Void> delResponsibleNS(AuthzTrans trans, String ns, String id) {
271 return func.delOwner(trans,ns,id);
275 * @see org.onap.aaf.auth.service.AuthzService#applyModel(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object)
279 path = "/authz/ns/:ns/attrib/:key/:value",
280 params = { "ns|string|true",
282 "value|string|true"},
284 errorCodes = { 403,404,406,409 },
286 "Create an attribute in the Namespace",
287 "You must be given direct permission for key by AAF"
291 public Result<Void> createNsAttrib(AuthzTrans trans, String ns, String key, String value) {
292 TimeTaken tt = trans.start("Create NsAttrib " + ns + ':' + key + ':' + value, Env.SUB);
295 final Validator v = new ServiceValidator();
298 v.value(value).err()) {
299 return Result.err(Status.ERR_BadData,v.errs());
302 // Check if exists already
303 Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
304 if(rlnsd.notOKorIsEmpty()) {
305 return Result.err(rlnsd);
307 NsDAO.Data nsd = rlnsd.value.get(0);
309 // Check for Existence
310 if(nsd.attrib.get(key)!=null) {
311 return Result.err(Status.ERR_ConflictAlreadyExists, "NS Property %s:%s exists", ns, key);
314 // Check if User may put
315 if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB,
316 ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) {
317 return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key);
321 nsd.attrib.put(key, value);
322 ques.nsDAO.dao().attribAdd(trans,ns,key,value);
331 path = "/authz/ns/attrib/:key",
332 params = { "key|string|true" },
334 errorCodes = { 403,404 },
336 "Read Attributes for Namespace"
340 public Result<KEYS> readNsByAttrib(AuthzTrans trans, String key) {
342 final Validator v = new ServiceValidator();
343 if(v.nullOrBlank("Key",key).err()) {
344 return Result.err(Status.ERR_BadData,v.errs());
348 if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB,
349 ":"+trans.org().getDomain()+".*:"+key, Question.READ)) {
350 return Result.err(Status.ERR_Denied,"%s may not read NS by Attrib '%s'",trans.user(),key);
353 Result<Set<String>> rsd = ques.nsDAO.dao().readNsByAttrib(trans, key);
355 return Result.err(rsd);
357 return mapper().keys(rsd.value);
363 path = "/authz/ns/:ns/attrib/:key/:value",
364 params = { "ns|string|true",
367 errorCodes = { 403,404 },
369 "Update Value on an existing attribute in the Namespace",
370 "You must be given direct permission for key by AAF"
374 public Result<?> updateNsAttrib(AuthzTrans trans, String ns, String key, String value) {
375 TimeTaken tt = trans.start("Update NsAttrib " + ns + ':' + key + ':' + value, Env.SUB);
378 final Validator v = new ServiceValidator();
381 v.value(value).err()) {
382 return Result.err(Status.ERR_BadData,v.errs());
385 // Check if exists already (NS must exist)
386 Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
387 if(rlnsd.notOKorIsEmpty()) {
388 return Result.err(rlnsd);
390 NsDAO.Data nsd = rlnsd.value.get(0);
392 // Check for Existence
393 if(nsd.attrib.get(key)==null) {
394 return Result.err(Status.ERR_NotFound, "NS Property %s:%s exists", ns, key);
397 // Check if User may put
398 if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB,
399 ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) {
400 return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key);
404 nsd.attrib.put(key, value);
406 return ques.nsDAO.update(trans,nsd);
415 path = "/authz/ns/:ns/attrib/:key",
416 params = { "ns|string|true",
419 errorCodes = { 403,404 },
421 "Delete an attribute in the Namespace",
422 "You must be given direct permission for key by AAF"
426 public Result<Void> deleteNsAttrib(AuthzTrans trans, String ns, String key) {
427 TimeTaken tt = trans.start("Delete NsAttrib " + ns + ':' + key, Env.SUB);
430 final Validator v = new ServiceValidator();
431 if(v.nullOrBlank("NS",ns).err() ||
432 v.nullOrBlank("Key",key).err()) {
433 return Result.err(Status.ERR_BadData,v.errs());
436 // Check if exists already
437 Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
438 if(rlnsd.notOKorIsEmpty()) {
439 return Result.err(rlnsd);
441 NsDAO.Data nsd = rlnsd.value.get(0);
443 // Check for Existence
444 if(nsd.attrib.get(key)==null) {
445 return Result.err(Status.ERR_NotFound, "NS Property [%s:%s] does not exist", ns, key);
448 // Check if User may del
449 if(!ques.isGranted(trans, trans.user(), ROOT_NS, "attrib", ":" + ROOT_COMPANY + ".*:"+key, Access.write.name())) {
450 return Result.err(Status.ERR_Denied, "%s may not delete NS Attrib [%s:%s]", trans.user(),ns, key);
454 nsd.attrib.remove(key);
455 ques.nsDAO.dao().attribRemove(trans,ns,key);
464 path = "/authz/nss/:id",
465 params = { "id|string|true" },
467 errorCodes = { 404,406 },
469 "Lists the Admin(s), Responsible Party(s), Role(s), Permission(s)",
470 "Credential(s) and Expiration of Credential(s) in Namespace :id",
474 public Result<NSS> getNSbyName(AuthzTrans trans, String ns) {
475 final Validator v = new ServiceValidator();
476 if(v.nullOrBlank("NS", ns).err()) {
477 return Result.err(Status.ERR_BadData,v.errs());
480 Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, ns);
483 return Result.err(Status.ERR_NotFound, "No data found for %s",ns);
485 Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.read);
487 return Result.err(rnd);
491 Namespace namespace = new Namespace(rnd.value);
492 Result<List<String>> rd = func.getOwners(trans, namespace.name, false);
494 namespace.owner = rd.value;
496 rd = func.getAdmins(trans, namespace.name, false);
498 namespace.admin = rd.value;
501 NSS nss = mapper.newInstance(API.NSS);
502 return mapper.nss(trans, namespace, nss);
504 return Result.err(rlnd);
510 path = "/authz/nss/admin/:id",
511 params = { "id|string|true" },
513 errorCodes = { 403,404 },
514 text = { "Lists all Namespaces where Identity :id is an Admin",
515 "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)"
519 public Result<NSS> getNSbyAdmin(AuthzTrans trans, String user, boolean full) {
520 final Validator v = new ServiceValidator();
521 if (v.nullOrBlank("User", user).err()) {
522 return Result.err(Status.ERR_BadData, v.errs());
525 Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".admin", full);
527 return Result.err(rn);
530 return Result.err(Status.ERR_NotFound, "[%s] is not an admin for any namespaces",user);
532 NSS nss = mapper.newInstance(API.NSS);
533 // Note: "loadNamespace" already validates view of Namespace
534 return mapper.nss(trans, rn.value, nss);
540 path = "/authz/nss/either/:id",
541 params = { "id|string|true" },
543 errorCodes = { 403,404 },
544 text = { "Lists all Namespaces where Identity :id is either an Admin or an Owner",
545 "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)"
549 public Result<NSS> getNSbyEither(AuthzTrans trans, String user, boolean full) {
550 final Validator v = new ServiceValidator();
551 if (v.nullOrBlank("User", user).err()) {
552 return Result.err(Status.ERR_BadData, v.errs());
555 Result<Collection<Namespace>> rn = loadNamepace(trans, user, null, full);
557 return Result.err(rn);
560 return Result.err(Status.ERR_NotFound, "[%s] is not an admin or owner for any namespaces",user);
562 NSS nss = mapper.newInstance(API.NSS);
563 // Note: "loadNamespace" already validates view of Namespace
564 return mapper.nss(trans, rn.value, nss);
567 private Result<Collection<Namespace>> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) {
568 Result<List<UserRoleDAO.Data>> urd = ques.userRoleDAO.readByUser(trans, user);
569 if(urd.notOKorIsEmpty()) {
570 return Result.err(urd);
572 Map<String, Namespace> lm = new HashMap<String,Namespace>();
573 Map<String, Namespace> other = full || endsWith==null?null:new TreeMap<String,Namespace>();
574 for(UserRoleDAO.Data urdd : urd.value) {
576 if(endsWith==null || urdd.role.endsWith(endsWith)) {
577 RoleDAO.Data rd = RoleDAO.Data.decode(urdd);
578 Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read);
580 Namespace namespace = lm.get(nsd.value.name);
581 if(namespace==null) {
582 namespace = new Namespace(nsd.value);
583 lm.put(namespace.name,namespace);
585 Result<List<String>> rls = func.getAdmins(trans, namespace.name, false);
587 namespace.admin=rls.value;
590 rls = func.getOwners(trans, namespace.name, false);
592 namespace.owner=rls.value;
596 } else { // Shortened version. Only Namespace Info available from Role.
597 if(Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) {
598 RoleDAO.Data rd = RoleDAO.Data.decode(urdd);
599 Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read);
601 Namespace namespace = lm.get(nsd.value.name);
602 if(namespace==null) {
604 namespace = other.remove(nsd.value.name);
606 if(namespace==null) {
607 namespace = new Namespace(nsd.value);
608 namespace.admin=new ArrayList<String>();
609 namespace.owner=new ArrayList<String>();
611 if(endsWith==null || urdd.role.endsWith(endsWith)) {
612 lm.put(namespace.name,namespace);
614 other.put(namespace.name,namespace);
617 if(Question.OWNER.equals(urdd.rname)) {
618 namespace.owner.add(urdd.user);
620 namespace.admin.add(urdd.user);
626 return Result.ok(lm.values());
631 path = "/authz/nss/responsible/:id",
632 params = { "id|string|true" },
634 errorCodes = { 403,404 },
635 text = { "Lists all Namespaces where Identity :id is a Responsible Party",
636 "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)"
640 public Result<NSS> getNSbyResponsible(AuthzTrans trans, String user, boolean full) {
641 final Validator v = new ServiceValidator();
642 if (v.nullOrBlank("User", user).err()) {
643 return Result.err(Status.ERR_BadData, v.errs());
645 Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".owner",full);
647 return Result.err(rn);
650 return Result.err(Status.ERR_NotFound, "[%s] is not an owner for any namespaces",user);
652 NSS nss = mapper.newInstance(API.NSS);
653 // Note: "loadNamespace" prevalidates
654 return mapper.nss(trans, rn.value, nss);
659 path = "/authz/nss/children/:id",
660 params = { "id|string|true" },
662 errorCodes = { 403,404 },
663 text = { "Lists all Child Namespaces of Namespace :id",
664 "Note: This is not a cached read"
668 public Result<NSS> getNSsChildren(AuthzTrans trans, String parent) {
669 final Validator v = new ServiceValidator();
670 if(v.nullOrBlank("NS", parent).err()) {
671 return Result.err(Status.ERR_BadData,v.errs());
674 Result<NsDAO.Data> rnd = ques.deriveNs(trans, parent);
676 return Result.err(rnd);
678 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
680 return Result.err(rnd);
683 Set<Namespace> lm = new HashSet<Namespace>();
684 Result<List<NsDAO.Data>> rlnd = ques.nsDAO.dao().getChildren(trans, parent);
687 return Result.err(Status.ERR_NotFound, "No data found for %s",parent);
689 for(NsDAO.Data ndd : rlnd.value) {
690 Namespace namespace = new Namespace(ndd);
691 Result<List<String>> rls = func.getAdmins(trans, namespace.name, false);
693 namespace.admin=rls.value;
696 rls = func.getOwners(trans, namespace.name, false);
698 namespace.owner=rls.value;
703 NSS nss = mapper.newInstance(API.NSS);
704 return mapper.nss(trans,lm, nss);
706 return Result.err(rlnd);
716 errorCodes = { 403,404,406 },
717 text = { "Replace the Current Description of a Namespace with a new one"
721 public Result<Void> updateNsDescription(AuthzTrans trans, REQUEST from) {
722 final Result<Namespace> nsd = mapper.ns(trans, from);
723 final ServiceValidator v = new ServiceValidator();
724 if(v.ns(nsd).err()) {
725 return Result.err(Status.ERR_BadData,v.errs());
727 if(v.nullOrBlank("description", nsd.value.description).err()) {
728 return Result.err(Status.ERR_BadData,v.errs());
731 Namespace namespace = nsd.value;
732 Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, namespace.name);
734 if(rlnd.notOKorIsEmpty()) {
735 return Result.err(Status.ERR_NotFound, "Namespace [%s] does not exist",namespace.name);
738 if (ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.write).notOK()) {
739 return Result.err(Status.ERR_Denied, "You do not have approval to change %s",namespace.name);
742 Result<Void> rdr = ques.nsDAO.dao().addDescription(trans, namespace.name, namespace.description);
746 return Result.err(rdr);
752 * @throws DAOException
753 * @see org.onap.aaf.auth.service.AuthzService#deleteNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String)
757 path = "/authz/ns/:ns",
758 params = { "ns|string|true" },
760 errorCodes = { 403,404,424 },
761 text = { "Delete the Namespace :ns. Namespaces cannot normally be deleted when there ",
762 "are still credentials associated with them, but they can be deleted by setting ",
763 "the \"force\" property. To do this: Add 'force=true' as a query parameter",
764 "<p>WARNING: Using force will delete all credentials attached to this namespace. Use with care.</p>"
765 + "if the \"force\" property is set to 'force=move', then Permissions and Roles are not deleted,"
766 + "but are retained, and assigned to the Parent Namespace. 'force=move' is not permitted "
767 + "at or below Application Scope"
771 public Result<Void> deleteNS(AuthzTrans trans, String ns) {
772 return func.deleteNS(trans, ns);
776 /***********************************
778 ***********************************/
782 * @see org.onap.aaf.auth.service.AuthzService#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object, boolean, java.lang.String, java.lang.String, java.lang.String, java.util.List, java.util.List)
786 path = "/authz/perm",
789 errorCodes = {403,404,406,409},
790 text = { "Permission consists of:",
791 "<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
792 + "is being protected</li>",
793 "<li>instance - a key, possibly multi-dimensional, that identifies a specific "
794 + " instance of the type</li>",
795 "<li>action - what kind of action is allowed</li></ul>",
796 "Note: instance and action can be an *"
800 public Result<Void> createPerm(final AuthzTrans trans,REQUEST rreq) {
801 final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq);
802 final ServiceValidator v = new ServiceValidator();
803 if(v.perm(newPd).err()) {
804 return Result.err(Status.ERR_BadData,v.errs());
807 Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false,
810 public String get() {
811 return "Create Permission [" +
812 newPd.value.fullType() + '|' +
813 newPd.value.instance + '|' +
814 newPd.value.action + ']';
818 private Result<NsDAO.Data> nsd;
820 public Result<?> mayChange() {
822 nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write);
827 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, newPd.value.ns);
828 if(nsr.notOKorIsEmpty()) {
829 return Result.err(nsr);
833 Result<String> rfc = func.createFuture(trans,fd.value,
834 newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action,
839 return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
842 newPd.value.instance,
845 return Result.err(rfc);
848 return func.createPerm(trans, newPd.value, true);
850 return Result.err(fd);
856 path = "/authz/perms/:type",
857 params = {"type|string|true"},
859 errorCodes = { 404,406 },
860 text = { "List All Permissions that match the :type element of the key" }
863 public Result<PERMS> getPermsByType(AuthzTrans trans, final String permType) {
864 final Validator v = new ServiceValidator();
865 if(v.nullOrBlank("PermType", permType).err()) {
866 return Result.err(Status.ERR_BadData,v.errs());
869 Result<List<PermDAO.Data>> rlpd = ques.getPermsByType(trans, permType);
871 return Result.err(rlpd);
874 // We don't have instance & action for mayUserView... do we want to loop through all returned here as well as in mapper?
875 // Result<NsDAO.Data> r;
876 // if((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r);
878 PERMS perms = mapper.newInstance(API.PERMS);
879 if(!rlpd.isEmpty()) {
880 // Note: Mapper will restrict what can be viewed
881 return mapper.perms(trans, rlpd.value, perms, true);
883 return Result.ok(perms);
888 path = "/authz/perms/:type/:instance/:action",
889 params = {"type|string|true",
890 "instance|string|true",
891 "action|string|true"},
893 errorCodes = { 404,406 },
894 text = { "List Permissions that match key; :type, :instance and :action" }
897 public Result<PERMS> getPermsByName(AuthzTrans trans, String type, String instance, String action) {
898 final Validator v = new ServiceValidator();
899 if(v.nullOrBlank("PermType", type).err()
900 || v.nullOrBlank("PermInstance", instance).err()
901 || v.nullOrBlank("PermAction", action).err()) {
902 return Result.err(Status.ERR_BadData,v.errs());
905 Result<List<PermDAO.Data>> rlpd = ques.getPermsByName(trans, type, instance, action);
907 return Result.err(rlpd);
910 PERMS perms = mapper.newInstance(API.PERMS);
911 if(!rlpd.isEmpty()) {
912 // Note: Mapper will restrict what can be viewed
913 return mapper.perms(trans, rlpd.value, perms, true);
915 return Result.ok(perms);
920 path = "/authz/perms/user/:user",
921 params = {"user|string|true"},
923 errorCodes = { 404,406 },
924 text = { "List All Permissions that match user :user",
925 "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>"}
928 public Result<PERMS> getPermsByUser(AuthzTrans trans, String user) {
929 final Validator v = new ServiceValidator();
930 if(v.nullOrBlank("User", user).err()) {
931 return Result.err(Status.ERR_BadData,v.errs());
934 Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,
935 trans.requested(force));
937 return Result.err(rlpd);
940 PERMS perms = mapper.newInstance(API.PERMS);
943 return Result.ok(perms);
945 // Note: Mapper will restrict what can be viewed
946 // if user is the same as that which is looked up, no filtering is required
947 return mapper.perms(trans, rlpd.value,
949 !user.equals(trans.user()));
954 path = "/authz/perms/user/:user/scope/:scope",
955 params = {"user|string|true","scope|string|true"},
957 errorCodes = { 404,406 },
958 text = { "List All Permissions that match user :user, filtered by NS (Scope)",
959 "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>",
960 "<p>'scope' must be expressed as NSs separated by ':'</p>"
964 public Result<PERMS> getPermsByUserScope(AuthzTrans trans, String user, String[] scopes) {
965 final Validator v = new ServiceValidator();
966 if(v.nullOrBlank("User", user).err()) {
967 return Result.err(Status.ERR_BadData,v.errs());
970 Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user, trans.requested(force));
972 return Result.err(rlpd);
975 PERMS perms = mapper.newInstance(API.PERMS);
978 return Result.ok(perms);
980 // Note: Mapper will restrict what can be viewed
981 // if user is the same as that which is looked up, no filtering is required
982 return mapper.perms(trans, rlpd.value,
985 !user.equals(trans.user()));
990 path = "/authz/perms/user/:user",
991 params = {"user|string|true"},
993 errorCodes = { 404,406 },
994 text = { "List All Permissions that match user :user",
995 "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>",
997 "Present Queries as one or more Permissions (see ContentType Links below for format).",
999 "If the Caller is Granted this specific Permission, and the Permission is valid",
1000 " for the User, it will be included in response Permissions, along with",
1001 " all the normal permissions on the 'GET' version of this call. If it is not",
1002 " valid, or Caller does not have permission to see, it will be removed from the list",
1004 " *Note: This design allows you to make one call for all expected permissions",
1005 " The permission to be included MUST be:",
1006 " <user namespace>.access|:<ns|role|perm>[:key]|<create|read|write>",
1008 " com.att.myns.access|:ns|write",
1009 " com.att.myns.access|:role:myrole|create",
1010 " com.att.myns.access|:perm:mytype:myinstance:myaction|read",
1015 public Result<PERMS> getPermsByUser(AuthzTrans trans, PERMS _perms, String user) {
1016 PERMS perms = _perms;
1017 final Validator v = new ServiceValidator();
1018 if(v.nullOrBlank("User", user).err()) {
1019 return Result.err(Status.ERR_BadData,v.errs());
1023 Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,trans.requested(force));
1025 return Result.err(rlpd);
1029 1) See if allowed to query
1030 2) See if User is allowed
1032 Result<List<PermDAO.Data>> in = mapper.perms(trans, perms);
1033 if(in.isOKhasData()) {
1034 List<PermDAO.Data> out = rlpd.value;
1036 for(PermDAO.Data pdd : in.value) {
1038 if("access".equals(pdd.type)) {
1039 Access access = Access.valueOf(pdd.action);
1040 String[] mdkey = Split.splitTrim(':',pdd.instance);
1041 if(mdkey.length>1) {
1042 String type = mdkey[1];
1043 if("role".equals(type)) {
1044 if(mdkey.length>2) {
1045 RoleDAO.Data rdd = new RoleDAO.Data();
1048 ok = ques.mayUser(trans, trans.user(), rdd, Access.read).isOK() && ques.mayUser(trans, user, rdd , access).isOK();
1050 } else if("perm".equals(type)) {
1051 if(mdkey.length>4) { // also need instance/action
1052 PermDAO.Data p = new PermDAO.Data();
1055 p.instance=mdkey[3];
1057 ok = ques.mayUser(trans, trans.user(), p, Access.read).isOK() && ques.mayUser(trans, user, p , access).isOK();
1059 } else if("ns".equals(type)) {
1060 NsDAO.Data ndd = new NsDAO.Data();
1062 ok = ques.mayUser(trans, trans.user(), ndd, Access.read).isOK() && ques.mayUser(trans, user, ndd , access).isOK();
1072 perms = mapper.newInstance(API.PERMS);
1073 if(rlpd.isEmpty()) {
1074 return Result.ok(perms);
1076 // Note: Mapper will restrict what can be viewed
1077 // if user is the same as that which is looked up, no filtering is required
1078 return mapper.perms(trans, rlpd.value,
1080 !user.equals(trans.user()));
1085 path = "/authz/perms/role/:role",
1086 params = {"role|string|true"},
1088 errorCodes = { 404,406 },
1089 text = { "List All Permissions that are granted to :role" }
1092 public Result<PERMS> getPermsByRole(AuthzTrans trans,String role) {
1093 final Validator v = new ServiceValidator();
1094 if(v.nullOrBlank("Role", role).err()) {
1095 return Result.err(Status.ERR_BadData,v.errs());
1098 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques,role);
1100 return Result.err(rrdd);
1103 Result<NsDAO.Data> r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read);
1105 return Result.err(r);
1108 PERMS perms = mapper.newInstance(API.PERMS);
1110 Result<List<PermDAO.Data>> rlpd = ques.getPermsByRole(trans, role, trans.requested(force));
1111 if(rlpd.isOKhasData()) {
1112 // Note: Mapper will restrict what can be viewed
1113 return mapper.perms(trans, rlpd.value, perms, true);
1115 return Result.ok(perms);
1120 path = "/authz/perms/ns/:ns",
1121 params = {"ns|string|true"},
1123 errorCodes = { 404,406 },
1124 text = { "List All Permissions that are in Namespace :ns" }
1127 public Result<PERMS> getPermsByNS(AuthzTrans trans,String ns) {
1128 final Validator v = new ServiceValidator();
1129 if(v.nullOrBlank("NS", ns).err()) {
1130 return Result.err(Status.ERR_BadData,v.errs());
1133 Result<NsDAO.Data> rnd = ques.deriveNs(trans, ns);
1135 return Result.err(rnd);
1138 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
1140 return Result.err(rnd);
1143 Result<List<PermDAO.Data>> rlpd = ques.permDAO.readNS(trans, ns);
1145 return Result.err(rlpd);
1148 PERMS perms = mapper.newInstance(API.PERMS);
1149 if(!rlpd.isEmpty()) {
1150 // Note: Mapper will restrict what can be viewed
1151 return mapper.perms(trans, rlpd.value,perms, true);
1153 return Result.ok(perms);
1158 path = "/authz/perm/:type/:instance/:action",
1159 params = {"type|string|true",
1160 "instance|string|true",
1161 "action|string|true"},
1163 errorCodes = { 404,406, 409 },
1164 text = { "Rename the Permission referenced by :type :instance :action, and "
1165 + "rename (copy/delete) to the Permission described in PermRequest" }
1168 public Result<Void> renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) {
1169 final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq);
1170 final ServiceValidator v = new ServiceValidator();
1171 if(v.perm(newPd).err()) {
1172 return Result.err(Status.ERR_BadData,v.errs());
1175 if (ques.mayUser(trans, trans.user(), newPd.value,Access.write).notOK()) {
1176 return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]",
1177 newPd.value.ns,newPd.value.type,newPd.value.instance,newPd.value.action);
1180 Result<NsSplit> nss = ques.deriveNsSplit(trans, origType);
1181 Result<List<PermDAO.Data>> origRlpd = ques.permDAO.read(trans, nss.value.ns, nss.value.name, origInstance, origAction);
1183 if(origRlpd.notOKorIsEmpty()) {
1184 return Result.err(Status.ERR_PermissionNotFound,
1185 "Permission [%s|%s|%s] does not exist",
1186 origType,origInstance,origAction);
1189 PermDAO.Data origPd = origRlpd.value.get(0);
1191 if (!origPd.ns.equals(newPd.value.ns)) {
1192 return Result.err(Status.ERR_Denied, "Cannot change namespace with rename command. " +
1193 "<new type> must start with [" + origPd.ns + "]");
1196 if ( origPd.type.equals(newPd.value.type) &&
1197 origPd.action.equals(newPd.value.action) &&
1198 origPd.instance.equals(newPd.value.instance) ) {
1199 return Result.err(Status.ERR_ConflictAlreadyExists, "New Permission must be different than original permission");
1202 Set<String> origRoles = origPd.roles(false);
1203 if (!origRoles.isEmpty()) {
1204 Set<String> roles = newPd.value.roles(true);
1205 for (String role : origPd.roles) {
1210 newPd.value.description = origPd.description;
1212 Result<Void> rv = null;
1214 rv = func.createPerm(trans, newPd.value, false);
1216 rv = func.deletePerm(trans, origPd, true, false);
1223 path = "/authz/perm",
1226 errorCodes = { 404,406 },
1227 text = { "Add Description Data to Perm" }
1230 public Result<Void> updatePermDescription(AuthzTrans trans, REQUEST from) {
1231 final Result<PermDAO.Data> pd = mapper.perm(trans, from);
1232 final ServiceValidator v = new ServiceValidator();
1233 if(v.perm(pd).err()) {
1234 return Result.err(Status.ERR_BadData,v.errs());
1236 if(v.nullOrBlank("description", pd.value.description).err()) {
1237 return Result.err(Status.ERR_BadData,v.errs());
1239 final PermDAO.Data perm = pd.value;
1240 if(ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) {
1241 return Result.err(Status.ERR_NotFound, "Permission [%s.%s|%s|%s] does not exist",
1242 perm.ns,perm.type,perm.instance,perm.action);
1245 if (ques.mayUser(trans, trans.user(), perm, Access.write).notOK()) {
1246 return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]",
1247 perm.ns,perm.type,perm.instance,perm.action);
1250 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pd.value.ns);
1251 if(nsr.notOKorIsEmpty()) {
1252 return Result.err(nsr);
1255 Result<Void> rdr = ques.permDAO.addDescription(trans, perm.ns, perm.type, perm.instance,
1256 perm.action, perm.description);
1260 return Result.err(rdr);
1267 path = "/authz/role/perm",
1270 errorCodes = {403,404,406,409},
1271 text = { "Set a permission's roles to roles given" }
1275 public Result<Void> resetPermRoles(final AuthzTrans trans, REQUEST rreq) {
1276 final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq);
1277 if(updt.notOKorIsEmpty()) {
1278 return Result.err(updt);
1281 final ServiceValidator v = new ServiceValidator();
1282 if(v.perm(updt).err()) {
1283 return Result.err(Status.ERR_BadData,v.errs());
1286 Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write);
1288 return Result.err(nsd);
1291 // Read full set to get CURRENT values
1292 Result<List<PermDAO.Data>> rcurr = ques.permDAO.read(trans,
1295 updt.value.instance,
1298 if(rcurr.notOKorIsEmpty()) {
1299 return Result.err(Status.ERR_PermissionNotFound,
1300 "Permission [%s.%s|%s|%s] does not exist",
1301 updt.value.ns,updt.value.type,updt.value.instance,updt.value.action);
1304 // Create a set of Update Roles, which are in Internal Format
1305 Set<String> updtRoles = new HashSet<String>();
1306 Result<NsSplit> nss;
1307 for(String role : updt.value.roles(false)) {
1308 nss = ques.deriveNsSplit(trans, role);
1310 updtRoles.add(nss.value.ns + '|' + nss.value.name);
1312 trans.error().log(nss.errorString());
1316 Result<Void> rv = null;
1318 for(PermDAO.Data curr : rcurr.value) {
1319 Set<String> currRoles = curr.roles(false);
1320 // must add roles to this perm, and add this perm to each role
1321 // in the update, but not in the current
1322 for (String role : updtRoles) {
1323 if (!currRoles.contains(role)) {
1324 Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role);
1325 if(key.isOKhasData()) {
1326 Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, key.value);
1327 if(rrd.isOKhasData()) {
1328 for(RoleDAO.Data r : rrd.value) {
1329 rv = func.addPermToRole(trans, r, curr, false);
1330 if (rv.notOK() && rv.status!=Result.ERR_ConflictAlreadyExists) {
1331 return Result.err(rv);
1335 return Result.err(rrd);
1340 // similarly, must delete roles from this perm, and delete this perm from each role
1341 // in the update, but not in the current
1342 for (String role : currRoles) {
1343 if (!updtRoles.contains(role)) {
1344 Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role);
1345 if(key.isOKhasData()) {
1346 Result<List<RoleDAO.Data>> rdd = ques.roleDAO.read(trans, key.value);
1347 if(rdd.isOKhasData()) {
1348 for(RoleDAO.Data r : rdd.value) {
1349 rv = func.delPermFromRole(trans, r, curr, true);
1350 if (rv.notOK() && rv.status!=Status.ERR_PermissionNotFound) {
1351 return Result.err(rv);
1359 return rv==null?Result.ok():rv;
1364 path = "/authz/perm",
1367 errorCodes = { 404,406 },
1368 text = { "Delete the Permission referenced by PermKey.",
1369 "You cannot normally delete a permission which is still granted to roles,",
1370 "however the \"force\" property allows you to do just that. To do this: Add",
1371 "'force=true' as a query parameter.",
1372 "<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>" }
1375 public Result<Void> deletePerm(final AuthzTrans trans, REQUEST from) {
1376 Result<PermDAO.Data> pd = mapper.perm(trans, from);
1378 return Result.err(pd);
1380 final ServiceValidator v = new ServiceValidator();
1381 if(v.nullOrBlank(pd.value).err()) {
1382 return Result.err(Status.ERR_BadData,v.errs());
1384 final PermDAO.Data perm = pd.value;
1385 if (ques.permDAO.read(trans, perm).notOKorIsEmpty()) {
1386 return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist",
1387 perm.ns,perm.type,perm.instance,perm.action );
1390 Result<FutureDAO.Data> fd = mapper.future(trans,PermDAO.TABLE,from,perm,false,
1393 public String get() {
1394 return "Delete Permission [" + perm.fullPerm() + ']';
1398 private Result<NsDAO.Data> nsd;
1400 public Result<?> mayChange() {
1402 nsd = ques.mayUser(trans, trans.user(), perm, Access.write);
1410 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, perm.ns);
1411 if(nsr.notOKorIsEmpty()) {
1412 return Result.err(nsr);
1415 Result<String> rfc = func.createFuture(trans, fd.value,
1416 perm.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D);
1418 return Result.err(Status.ACC_Future, "Perm Deletion [%s] is saved for future processing",perm.encode());
1420 return Result.err(rfc);
1422 case Status.ACC_Now:
1423 return func.deletePerm(trans,perm,trans.requested(force), false);
1425 return Result.err(fd);
1431 path = "/authz/perm/:name/:type/:action",
1432 params = {"type|string|true",
1433 "instance|string|true",
1434 "action|string|true"},
1436 errorCodes = { 404,406 },
1437 text = { "Delete the Permission referenced by :type :instance :action",
1438 "You cannot normally delete a permission which is still granted to roles,",
1439 "however the \"force\" property allows you to do just that. To do this: Add",
1440 "'force=true' as a query parameter",
1441 "<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>"}
1444 public Result<Void> deletePerm(AuthzTrans trans, String type, String instance, String action) {
1445 final Validator v = new ServiceValidator();
1446 if(v.nullOrBlank("Type",type)
1447 .nullOrBlank("Instance",instance)
1448 .nullOrBlank("Action",action)
1450 return Result.err(Status.ERR_BadData,v.errs());
1453 Result<PermDAO.Data> pd = ques.permFrom(trans, type, instance, action);
1455 return func.deletePerm(trans, pd.value, trans.requested(force), false);
1457 return Result.err(pd);
1461 /***********************************
1463 ***********************************/
1466 path = "/authz/role",
1469 errorCodes = {403,404,406,409},
1472 "Roles are part of Namespaces",
1474 "<ul><li>org.onap.aaf - The team that created and maintains AAF</li>",
1475 "Roles do not include implied permissions for an App. Instead, they contain explicit Granted Permissions by any Namespace in AAF (See Permissions)",
1476 "Restrictions on Role Names:",
1477 "<ul><li>Must start with valid Namespace name, terminated by . (dot/period)</li>",
1478 "<li>Allowed Characters are a-zA-Z0-9._-</li>",
1479 "<li>role names are Case Sensitive</li></ul>",
1480 "The right questions to ask for defining and populating a Role in AAF, therefore, are:",
1481 "<ul><li>'What Job Function does this represent?'</li>",
1482 "<li>'Does this person perform this Job Function?'</li></ul>" }
1486 public Result<Void> createRole(final AuthzTrans trans, REQUEST from) {
1487 final Result<RoleDAO.Data> rd = mapper.role(trans, from);
1488 final ServiceValidator v = new ServiceValidator();
1489 if(v.role(rd).err()) {
1490 return Result.err(Status.ERR_BadData,v.errs());
1492 final RoleDAO.Data role = rd.value;
1493 if(ques.roleDAO.read(trans, role.ns, role.name).isOKhasData()) {
1494 return Result.err(Status.ERR_ConflictAlreadyExists, "Role [" + role.fullName() + "] already exists");
1497 Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false,
1500 public String get() {
1501 return "Create Role [" +
1502 rd.value.fullName() +
1507 private Result<NsDAO.Data> nsd;
1509 public Result<?> mayChange() {
1511 nsd = ques.mayUser(trans, trans.user(), role, Access.write);
1517 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
1518 if(nsr.notOKorIsEmpty()) {
1519 return Result.err(nsr);
1524 Result<String> rfc = func.createFuture(trans, fd.value,
1525 role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.C);
1527 return Result.err(Status.ACC_Future, "Role [%s.%s] is saved for future processing",
1531 return Result.err(rfc);
1533 case Status.ACC_Now:
1534 Result<RoleDAO.Data> rdr = ques.roleDAO.create(trans, role);
1538 return Result.err(rdr);
1541 return Result.err(fd);
1546 * @see org.onap.aaf.auth.service.AuthzService#getRolesByName(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
1550 path = "/authz/roles/:role",
1551 params = {"role|string|true"},
1553 errorCodes = {404,406},
1554 text = { "List Roles that match :role",
1555 "Note: You must have permission to see any given role"
1559 public Result<ROLES> getRolesByName(AuthzTrans trans, String role) {
1560 final Validator v = new ServiceValidator();
1561 if(v.nullOrBlank("Role", role).err()) {
1562 return Result.err(Status.ERR_BadData,v.errs());
1565 // Determine if User can ask this question
1566 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
1567 if(rrdd.isOKhasData()) {
1568 Result<NsDAO.Data> r;
1569 if((r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read)).notOK()) {
1570 return Result.err(r);
1573 return Result.err(rrdd);
1577 Result<List<RoleDAO.Data>> rlrd = ques.getRolesByName(trans, role);
1579 // Note: Mapper will restrict what can be viewed
1580 ROLES roles = mapper.newInstance(API.ROLES);
1581 return mapper.roles(trans, rlrd.value, roles, true);
1583 return Result.err(rlrd);
1588 * @see org.onap.aaf.auth.service.AuthzService#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
1592 path = "/authz/roles/user/:name",
1593 params = {"name|string|true"},
1595 errorCodes = {404,406},
1596 text = { "List all Roles that match user :name",
1597 "'user' must be expressed as full identity (ex: id@full.domain.com)",
1598 "Note: You must have permission to see any given role"
1603 public Result<ROLES> getRolesByUser(AuthzTrans trans, String user) {
1604 final Validator v = new ServiceValidator();
1605 if(v.nullOrBlank("User", user).err()) {
1606 return Result.err(Status.ERR_BadData,v.errs());
1609 ROLES roles = mapper.newInstance(API.ROLES);
1610 // Get list of roles per user, then add to Roles as we go
1611 Result<List<RoleDAO.Data>> rlrd;
1612 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user);
1613 if(rlurd.isOKhasData()) {
1614 for(UserRoleDAO.Data urd : rlurd.value ) {
1615 rlrd = ques.roleDAO.read(trans, urd.ns,urd.rname);
1616 // Note: Mapper will restrict what can be viewed
1617 // if user is the same as that which is looked up, no filtering is required
1618 if(rlrd.isOKhasData()) {
1619 mapper.roles(trans, rlrd.value,roles, !user.equals(trans.user()));
1623 return Result.ok(roles);
1628 * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
1632 path = "/authz/roles/ns/:ns",
1633 params = {"ns|string|true"},
1635 errorCodes = {404,406},
1636 text = { "List all Roles for the Namespace :ns",
1637 "Note: You must have permission to see any given role"
1642 public Result<ROLES> getRolesByNS(AuthzTrans trans, String ns) {
1643 final Validator v = new ServiceValidator();
1644 if(v.nullOrBlank("NS", ns).err()) {
1645 return Result.err(Status.ERR_BadData,v.errs());
1648 // check if user is allowed to view NS
1649 Result<NsDAO.Data> rnsd = ques.deriveNs(trans, ns);
1651 return Result.err(rnsd);
1653 rnsd = ques.mayUser(trans, trans.user(), rnsd.value, Access.read);
1655 return Result.err(rnsd);
1658 TimeTaken tt = trans.start("MAP Roles by NS to Roles", Env.SUB);
1660 ROLES roles = mapper.newInstance(API.ROLES);
1661 // Get list of roles per user, then add to Roles as we go
1662 Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readNS(trans, ns);
1664 if(!rlrd.isEmpty()) {
1665 // Note: Mapper doesn't need to restrict what can be viewed, because we did it already.
1666 mapper.roles(trans,rlrd.value,roles,false);
1668 return Result.ok(roles);
1670 return Result.err(rlrd);
1679 * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
1683 path = "/authz/roles/name/:name",
1684 params = {"name|string|true"},
1686 errorCodes = {404,406},
1687 text = { "List all Roles for only the Name of Role (without Namespace)",
1688 "Note: You must have permission to see any given role"
1692 public Result<ROLES> getRolesByNameOnly(AuthzTrans trans, String name) {
1693 final Validator v = new ServiceValidator();
1694 if(v.nullOrBlank("Name", name).err()) {
1695 return Result.err(Status.ERR_BadData,v.errs());
1698 // User Mapper to make sure user is allowed to view NS
1700 TimeTaken tt = trans.start("MAP Roles by Name to Roles", Env.SUB);
1702 ROLES roles = mapper.newInstance(API.ROLES);
1703 // Get list of roles per user, then add to Roles as we go
1704 Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readName(trans, name);
1706 if(!rlrd.isEmpty()) {
1707 // Note: Mapper will restrict what can be viewed
1708 mapper.roles(trans,rlrd.value,roles,true);
1710 return Result.ok(roles);
1712 return Result.err(rlrd);
1721 path = "/authz/roles/perm/:type/:instance/:action",
1722 params = {"type|string|true",
1723 "instance|string|true",
1724 "action|string|true"},
1726 errorCodes = {404,406},
1727 text = { "Find all Roles containing the given Permission." +
1728 "Permission consists of:",
1729 "<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
1730 + "is being protected</li>",
1731 "<li>instance - a key, possibly multi-dimensional, that identifies a specific "
1732 + " instance of the type</li>",
1733 "<li>action - what kind of action is allowed</li></ul>",
1734 "Notes: instance and action can be an *",
1735 " You must have permission to see any given role"
1740 public Result<ROLES> getRolesByPerm(AuthzTrans trans, String type, String instance, String action) {
1741 final Validator v = new ServiceValidator();
1742 if(v.permType(type,null)
1743 .permInstance(instance)
1746 return Result.err(Status.ERR_BadData,v.errs());
1749 TimeTaken tt = trans.start("Map Perm Roles Roles", Env.SUB);
1751 ROLES roles = mapper.newInstance(API.ROLES);
1752 // Get list of roles per user, then add to Roles as we go
1753 Result<NsSplit> nsSplit = ques.deriveNsSplit(trans, type);
1754 if(nsSplit.isOK()) {
1755 PermDAO.Data pdd = new PermDAO.Data(nsSplit.value, instance, action);
1757 if((res=ques.mayUser(trans, trans.user(), pdd, Question.Access.read)).notOK()) {
1758 return Result.err(res);
1761 Result<List<PermDAO.Data>> pdlr = ques.permDAO.read(trans, pdd);
1762 if(pdlr.isOK())for(PermDAO.Data pd : pdlr.value) {
1763 Result<List<RoleDAO.Data>> rlrd;
1764 for(String r : pd.roles) {
1765 Result<String[]> rs = RoleDAO.Data.decodeToArray(trans, ques, r);
1767 rlrd = ques.roleDAO.read(trans, rs.value[0],rs.value[1]);
1768 // Note: Mapper will restrict what can be viewed
1769 if(rlrd.isOKhasData()) {
1770 mapper.roles(trans,rlrd.value,roles,true);
1776 return Result.ok(roles);
1784 path = "/authz/role",
1787 errorCodes = {404,406},
1788 text = { "Add Description Data to a Role" }
1792 public Result<Void> updateRoleDescription(AuthzTrans trans, REQUEST from) {
1793 final Result<RoleDAO.Data> rd = mapper.role(trans, from);
1794 final ServiceValidator v = new ServiceValidator();
1795 if(v.role(rd).err()) {
1796 return Result.err(Status.ERR_BadData,v.errs());
1798 if(v.nullOrBlank("description", rd.value.description).err()) {
1799 return Result.err(Status.ERR_BadData,v.errs());
1802 final RoleDAO.Data role = rd.value;
1803 if(ques.roleDAO.read(trans, role.ns, role.name).notOKorIsEmpty()) {
1804 return Result.err(Status.ERR_NotFound, "Role [" + role.fullName() + "] does not exist");
1807 if (ques.mayUser(trans, trans.user(), role, Access.write).notOK()) {
1808 return Result.err(Status.ERR_Denied, "You do not have approval to change " + role.fullName());
1811 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
1812 if(nsr.notOKorIsEmpty()) {
1813 return Result.err(nsr);
1816 Result<Void> rdr = ques.roleDAO.addDescription(trans, role.ns, role.name, role.description);
1820 return Result.err(rdr);
1827 path = "/authz/role/perm",
1830 errorCodes = {403,404,406,409},
1831 text = { "Grant a Permission to a Role",
1832 "Permission consists of:",
1833 "<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
1834 + "is being protected</li>",
1835 "<li>instance - a key, possibly multi-dimensional, that identifies a specific "
1836 + " instance of the type</li>",
1837 "<li>action - what kind of action is allowed</li></ul>",
1838 "Note: instance and action can be an *",
1839 "Note: Using the \"force\" property will create the Permission, if it doesn't exist AND the requesting " +
1840 " ID is allowed to create. It will then grant",
1841 " the permission to the role in one step. To do this: add 'force=true' as a query parameter."
1846 public Result<Void> addPermToRole(final AuthzTrans trans, REQUEST rreq) {
1847 // Translate Request into Perm and Role Objects
1848 final Result<PermDAO.Data> rpd = mapper.permFromRPRequest(trans, rreq);
1849 if(rpd.notOKorIsEmpty()) {
1850 return Result.err(rpd);
1852 final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq);
1853 if(rrd.notOKorIsEmpty()) {
1854 return Result.err(rrd);
1857 // Validate Role and Perm values
1858 final ServiceValidator v = new ServiceValidator();
1859 if(v.perm(rpd.value)
1862 return Result.err(Status.ERR_BadData,v.errs());
1865 Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.read(trans, rrd.value.ns, rrd.value.name);
1866 if(rlrd.notOKorIsEmpty()) {
1867 return Result.err(Status.ERR_RoleNotFound, "Role [%s] does not exist", rrd.value.fullName());
1870 // Check Status of Data in DB (does it exist)
1871 Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, rpd.value.ns,
1872 rpd.value.type, rpd.value.instance, rpd.value.action);
1873 PermDAO.Data createPerm = null; // if not null, create first
1874 if(rlpd.notOKorIsEmpty()) { // Permission doesn't exist
1875 if(trans.requested(force)) {
1876 // Remove roles from perm data object so we just create the perm here
1877 createPerm = rpd.value;
1878 createPerm.roles.clear();
1880 return Result.err(Status.ERR_PermissionNotFound,"Permission [%s.%s|%s|%s] does not exist",
1881 rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action);
1884 if (rlpd.value.get(0).roles(false).contains(rrd.value.encode())) {
1885 return Result.err(Status.ERR_ConflictAlreadyExists,
1886 "Permission [%s.%s|%s|%s] already granted to Role [%s.%s]",
1887 rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action,
1888 rrd.value.ns,rrd.value.name
1894 Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, rpd.value,true, // Allow grants to create Approvals
1897 public String get() {
1898 return "Grant Permission [" + rpd.value.fullPerm() + ']' +
1899 " to Role [" + rrd.value.fullName() + "]";
1903 private Result<NsDAO.Data> nsd;
1905 public Result<?> mayChange() {
1907 nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write);
1912 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rpd.value.ns);
1913 if(nsr.notOKorIsEmpty()) {
1914 return Result.err(nsr);
1918 Result<String> rfc = func.createFuture(trans,fd.value,
1919 rpd.value.fullPerm(),
1924 return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
1930 return Result.err(rfc);
1932 case Status.ACC_Now:
1933 Result<Void> rv = null;
1934 if(createPerm!=null) {// has been validated for creating
1935 rv = func.createPerm(trans, createPerm, false);
1937 if(rv==null || rv.isOK()) {
1938 rv = func.addPermToRole(trans, rrd.value, rpd.value, false);
1942 return Result.err(fd);
1948 * Delete Perms from Roles (UnGrant)
1950 * @param roleFullName
1955 path = "/authz/role/:role/perm",
1956 params = {"role|string|true"},
1958 errorCodes = {404,406},
1959 text = { "Ungrant a permission from Role :role" }
1963 public Result<Void> delPermFromRole(final AuthzTrans trans, REQUEST rreq) {
1964 final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq);
1965 if(updt.notOKorIsEmpty()) {
1966 return Result.err(updt);
1968 final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq);
1969 if(rrd.notOKorIsEmpty()) {
1970 return Result.err(rrd);
1973 final ServiceValidator v = new ServiceValidator();
1974 if(v.nullOrBlank(updt.value)
1975 .nullOrBlank(rrd.value)
1977 return Result.err(Status.ERR_BadData,v.errs());
1980 return delPermFromRole(trans, updt.value,rrd.value, rreq);
1983 private Result<Void> delPermFromRole(final AuthzTrans trans, PermDAO.Data pdd, RoleDAO.Data rdd, REQUEST rreq) {
1984 Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, pdd.ns, pdd.type,
1985 pdd.instance, pdd.action);
1987 if(rlpd.notOKorIsEmpty()) {
1988 return Result.err(Status.ERR_PermissionNotFound,
1989 "Permission [%s.%s|%s|%s] does not exist",
1990 pdd.ns,pdd.type,pdd.instance,pdd.action);
1993 Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, pdd,true, // allow ungrants requests
1996 public String get() {
1997 return "Ungrant Permission [" + pdd.fullPerm() + ']' +
1998 " from Role [" + rdd.fullName() + "]";
2002 private Result<NsDAO.Data> nsd;
2004 public Result<?> mayChange() {
2006 nsd = ques.mayUser(trans, trans.user(), pdd, Access.write);
2011 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pdd.ns);
2012 if(nsr.notOKorIsEmpty()) {
2013 return Result.err(nsr);
2017 Result<String> rfc = func.createFuture(trans,fd.value,
2024 return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
2030 return Result.err(rfc);
2032 case Status.ACC_Now:
2033 return func.delPermFromRole(trans, rdd, pdd, false);
2035 return Result.err(fd);
2042 path = "/authz/role/:role/perm/:type/:instance/:action",
2043 params = {"role|string|true",
2044 "perm type|string|true",
2045 "perm instance|string|true",
2046 "perm action|string|true"
2049 errorCodes = {404,406},
2050 text = { "Ungrant a single permission from Role :role with direct key" }
2054 public Result<Void> delPermFromRole(AuthzTrans trans, String role, String type, String instance, String action) {
2055 Result<Data> rpns = ques.deriveNs(trans, type);
2056 if(rpns.notOKorIsEmpty()) {
2057 return Result.err(rpns);
2060 final Validator v = new ServiceValidator();
2062 .permType(rpns.value.name,rpns.value.parent)
2063 .permInstance(instance)
2066 return Result.err(Status.ERR_BadData,v.errs());
2069 Result<Data> rrns = ques.deriveNs(trans, role);
2070 if(rrns.notOKorIsEmpty()) {
2071 return Result.err(rrns);
2074 final Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, rrns.value.parent, rrns.value.name);
2075 if(rrd.notOKorIsEmpty()) {
2076 return Result.err(rrd);
2079 final Result<List<PermDAO.Data>> rpd = ques.permDAO.read(trans, rpns.value.parent, rpns.value.name, instance, action);
2080 if(rpd.notOKorIsEmpty()) {
2081 return Result.err(rpd);
2085 return delPermFromRole(trans,rpd.value.get(0), rrd.value.get(0), mapper.ungrantRequest(trans, role, type, instance, action));
2090 path = "/authz/role/:role",
2091 params = {"role|string|true"},
2093 errorCodes = {404,406},
2094 text = { "Delete the Role named :role"}
2098 public Result<Void> deleteRole(AuthzTrans trans, String role) {
2099 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
2100 if(rrdd.isOKhasData()) {
2101 final ServiceValidator v = new ServiceValidator();
2102 if(v.nullOrBlank(rrdd.value).err()) {
2103 return Result.err(Status.ERR_BadData,v.errs());
2105 return func.deleteRole(trans, rrdd.value, false, false);
2107 return Result.err(rrdd);
2113 path = "/authz/role",
2116 errorCodes = { 404,406 },
2117 text = { "Delete the Role referenced by RoleKey",
2118 "You cannot normally delete a role which still has permissions granted or users assigned to it,",
2119 "however the \"force\" property allows you to do just that. To do this: Add 'force=true'",
2120 "as a query parameter.",
2121 "<p>WARNING: Using force will remove all users and permission from this role. Use with care.</p>"}
2125 public Result<Void> deleteRole(final AuthzTrans trans, REQUEST from) {
2126 final Result<RoleDAO.Data> rd = mapper.role(trans, from);
2127 final ServiceValidator v = new ServiceValidator();
2129 return Result.err(Status.ERR_BadData,"Request does not contain Role");
2131 if(v.nullOrBlank(rd.value).err()) {
2132 return Result.err(Status.ERR_BadData,v.errs());
2134 final RoleDAO.Data role = rd.value;
2135 if(ques.roleDAO.read(trans, role).notOKorIsEmpty() && !trans.requested(force)) {
2136 return Result.err(Status.ERR_RoleNotFound, "Role [" + role.fullName() + "] does not exist");
2139 Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false,
2142 public String get() {
2143 return "Delete Role [" + role.fullName() + ']'
2144 + " and all attached user roles";
2148 private Result<NsDAO.Data> nsd;
2150 public Result<?> mayChange() {
2152 nsd = ques.mayUser(trans, trans.user(), role, Access.write);
2160 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
2161 if(nsr.notOKorIsEmpty()) {
2162 return Result.err(nsr);
2165 Result<String> rfc = func.createFuture(trans, fd.value,
2166 role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D);
2168 return Result.err(Status.ACC_Future, "Role Deletion [%s.%s] is saved for future processing",
2172 return Result.err(rfc);
2174 case Status.ACC_Now:
2175 return func.deleteRole(trans,role,trans.requested(force), true /*preapproved*/);
2177 return Result.err(fd);
2182 /***********************************
2184 ***********************************/
2185 private class MayCreateCred implements MayChange {
2186 private Result<NsDAO.Data> nsd;
2187 private AuthzTrans trans;
2188 private CredDAO.Data cred;
2189 private Executor exec;
2191 public MayCreateCred(AuthzTrans trans, CredDAO.Data cred, Executor exec) {
2198 public Result<?> mayChange() {
2200 nsd = ques.validNSOfDomain(trans, cred.id);
2202 // is Ns of CredID valid?
2206 if(trans.org().validate(trans,Policy.CREATE_MECHID, exec, cred.id)==null) {
2209 Result<?> rmc = ques.mayUser(trans, trans.user(), nsd.value, Access.write);
2210 if(rmc.isOKhasData()) {
2214 } catch (Exception e) {
2215 trans.warn().log(e);
2218 trans.warn().log(nsd.errorString());
2220 return Result.err(Status.ERR_Denied,"%s is not allowed to create %s in %s",trans.user(),cred.id,cred.ns);
2224 private class MayChangeCred implements MayChange {
2226 private Result<NsDAO.Data> nsd;
2227 private AuthzTrans trans;
2228 private CredDAO.Data cred;
2229 public MayChangeCred(AuthzTrans trans, CredDAO.Data cred) {
2235 public Result<?> mayChange() {
2236 // User can change himself (but not create)
2237 if(trans.user().equals(cred.id)) {
2241 nsd = ques.validNSOfDomain(trans, cred.id);
2243 // Get the Namespace
2245 if(ques.mayUser(trans, trans.user(), nsd.value,Access.write).isOK()) {
2248 String user[] = Split.split('.',trans.user());
2250 String company = user[user.length-1] + '.' + user[user.length-2];
2251 if(ques.isGranted(trans, trans.user(), ROOT_NS,"password",company,"reset")) {
2256 return Result.err(Status.ERR_Denied,"%s is not allowed to change %s in %s",trans.user(),cred.id,cred.ns);
2261 private final long DAY_IN_MILLIS = 24*3600*1000L;
2265 path = "/authn/cred",
2268 errorCodes = {403,404,406,409},
2269 text = { "A credential consists of:",
2270 "<ul><li>id - the ID to create within AAF. The domain is in reverse",
2271 "order of Namespace (i.e. Users of Namespace com.att.myapp would be",
2272 "AB1234@myapp.att.com</li>",
2273 "<li>password - Company Policy Compliant Password</li></ul>",
2274 "Note: AAF does support multiple credentials with the same ID.",
2275 "Check with your organization if you have this implemented."
2279 public Result<Void> createUserCred(final AuthzTrans trans, REQUEST from) {
2280 final String cmdDescription = ("Create User Credential");
2281 TimeTaken tt = trans.start(cmdDescription, Env.SUB);
2284 Result<CredDAO.Data> rcred = mapper.cred(trans, from, true);
2285 if(rcred.isOKhasData()) {
2286 byte[] rawCred = rcred.value.cred.array();
2287 rcred = ques.userCredSetup(trans, rcred.value);
2289 final ServiceValidator v = new ServiceValidator();
2291 if(v.cred(trans, trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations
2292 return Result.err(Status.ERR_BadData,v.errs());
2296 // 2016-4 Jonathan, New Behavior - If MechID is not registered with Org, deny creation
2297 Identity mechID = null;
2298 Organization org = trans.org();
2300 mechID = org.getIdentity(trans, rcred.value.id);
2301 } catch (Exception e1) {
2302 trans.error().log(e1,rcred.value.id,"cannot be validated at this time");
2304 if(mechID==null || !mechID.isFound()) {
2305 return Result.err(Status.ERR_Policy,"MechIDs must be registered with %s before provisioning in AAF",org.getName());
2308 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns);
2309 if(nsr.notOKorIsEmpty()) {
2310 return Result.err(Status.ERR_NsNotFound,"Cannot provision %s on non-existent Namespace %s",mechID.id(),rcred.value.ns);
2314 boolean firstID = false;
2317 CassExecutor exec = new CassExecutor(trans, func);
2318 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id);
2319 if (rlcd.isOKhasData()) {
2320 if (!org.canHaveMultipleCreds(rcred.value.id)) {
2321 return Result.err(Status.ERR_ConflictAlreadyExists, "Credential exists");
2324 for (CredDAO.Data curr : rlcd.value) {
2325 // May not use the same password in the list
2326 // Note: ASPR specifies character differences, but we don't actually store the
2327 // password to validate char differences.
2329 rb = ques.userCredCheck(trans, curr, rawCred);
2331 return Result.err(rb);
2332 } else if(rb.value){
2333 return Result.err(Status.ERR_Policy, "Credential content cannot be reused.");
2334 } else if (Chrono.dateOnlyStamp(curr.expires).equals(Chrono.dateOnlyStamp(rcred.value.expires)) && curr.type==rcred.value.type) {
2335 return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists, use 'reset'");
2340 // 2016-04-12 Jonathan If Caller is the Sponsor and is also an Owner of NS, allow without special Perm
2341 String theMechID = rcred.value.id;
2342 Boolean otherMechIDs = false;
2343 // find out if this is the only mechID. other MechIDs mean special handling (not automated)
2344 for(CredDAO.Data cd : ques.credDAO.readNS(trans,nsr.value.get(0).name).value) {
2345 if(!cd.id.equals(theMechID)) {
2346 otherMechIDs = true;
2351 // We can say "ID does not exist" here
2352 if((reason=org.validate(trans, Policy.CREATE_MECHID, exec, theMechID,trans.user(),otherMechIDs.toString()))!=null) {
2353 return Result.err(Status.ERR_Denied, reason);
2356 } catch (Exception e) {
2357 return Result.err(e);
2361 mc = new MayCreateCred(trans, rcred.value, exec);
2363 final CredDAO.Data cdd = rcred.value;
2364 Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, // may want to enable in future.
2367 public String get() {
2368 return cmdDescription + " [" +
2371 + cdd.expires + ']';
2378 Result<String> rfc = func.createFuture(trans, fd.value,
2379 rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
2380 trans.user(), nsr.value.get(0), FUTURE_OP.C);
2382 return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s] is saved for future processing",
2384 Integer.toString(rcred.value.type),
2385 rcred.value.expires.toString());
2387 return Result.err(rfc);
2389 case Status.ACC_Now:
2392 // && !nsr.value.get(0).isAdmin(trans.getUserPrincipal().getName())) {
2393 Result<List<String>> admins = func.getAdmins(trans, nsr.value.get(0).name, false);
2394 // OK, it's a first ID, and not by NS Admin, so let's set TempPassword length
2395 // Note, we only do this on First time, because of possibility of
2396 // prematurely expiring a production id
2397 if(admins.isOKhasData() && !admins.value.contains(trans.user())) {
2398 rcred.value.expires = org.expiration(null, Expiration.TempPassword).getTime();
2401 } catch (Exception e) {
2402 trans.error().log(e, "While setting expiration to TempPassword");
2404 Result<?>udr = ques.credDAO.create(trans, rcred.value);
2408 return Result.err(udr);
2410 return Result.err(fd);
2414 return Result.err(rcred);
2423 path = "/authn/creds/ns/:ns",
2424 params = {"ns|string|true"},
2426 errorCodes = {403,404,406},
2427 text = { "Return all IDs in Namespace :ns"
2431 public Result<USERS> getCredsByNS(AuthzTrans trans, String ns) {
2432 final Validator v = new ServiceValidator();
2433 if(v.ns(ns).err()) {
2434 return Result.err(Status.ERR_BadData,v.errs());
2437 // check if user is allowed to view NS
2438 Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
2440 return Result.err(rnd);
2442 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
2444 return Result.err(rnd);
2447 TimeTaken tt = trans.start("MAP Creds by NS to Creds", Env.SUB);
2449 USERS users = mapper.newInstance(API.USERS);
2450 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readNS(trans, ns);
2453 if(!rlcd.isEmpty()) {
2454 return mapper.cred(rlcd.value, users);
2456 return Result.ok(users);
2458 return Result.err(rlcd);
2468 path = "/authn/creds/id/:ns",
2469 params = {"id|string|true"},
2471 errorCodes = {403,404,406},
2472 text = { "Return all IDs in for ID"
2473 ,"(because IDs are multiple, due to multiple Expiration Dates)"
2477 public Result<USERS> getCredsByID(AuthzTrans trans, String id) {
2478 final Validator v = new ServiceValidator();
2479 if(v.nullOrBlank("ID",id).err()) {
2480 return Result.err(Status.ERR_BadData,v.errs());
2483 String ns = Question.domain2ns(id);
2484 // check if user is allowed to view NS
2485 Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
2487 return Result.err(rnd);
2489 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
2491 return Result.err(rnd);
2494 TimeTaken tt = trans.start("MAP Creds by ID to Creds", Env.SUB);
2496 USERS users = mapper.newInstance(API.USERS);
2497 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, id);
2500 if(!rlcd.isEmpty()) {
2501 return mapper.cred(rlcd.value, users);
2503 return Result.ok(users);
2505 return Result.err(rlcd);
2515 path = "/authn/certs/id/:id",
2516 params = {"id|string|true"},
2518 errorCodes = {403,404,406},
2519 text = { "Return Cert Info for ID"
2523 public Result<CERTS> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id) {
2524 TimeTaken tt = trans.start("Get Cert Info by ID", Env.SUB);
2526 CERTS certs = mapper.newInstance(API.CERTS);
2527 Result<List<CertDAO.Data>> rlcd = ques.certDAO.readID(trans, id);
2530 if(!rlcd.isEmpty()) {
2531 return mapper.cert(rlcd.value, certs);
2533 return Result.ok(certs);
2535 return Result.err(rlcd);
2545 path = "/authn/cred",
2548 errorCodes = {300,403,404,406},
2549 text = { "Reset a Credential Password. If multiple credentials exist for this",
2550 "ID, you will need to specify which entry you are resetting in the",
2551 "CredRequest object"
2555 public Result<Void> changeUserCred(final AuthzTrans trans, REQUEST from) {
2556 final String cmdDescription = "Update User Credential";
2557 TimeTaken tt = trans.start(cmdDescription, Env.SUB);
2559 Result<CredDAO.Data> rcred = mapper.cred(trans, from, true);
2560 if(rcred.isOKhasData()) {
2561 rcred = ques.userCredSetup(trans, rcred.value);
2563 final ServiceValidator v = new ServiceValidator();
2565 if(v.cred(trans, trans.org(),rcred,false).err()) {// Note: Creates have stricter Validations
2566 return Result.err(Status.ERR_BadData,v.errs());
2568 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id);
2569 if(rlcd.notOKorIsEmpty()) {
2570 return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
2573 MayChange mc = new MayChangeCred(trans, rcred.value);
2574 Result<?> rmc = mc.mayChange();
2576 return Result.err(rmc);
2579 Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value);
2581 return Result.err(ri);
2583 int entry = ri.value;
2586 final CredDAO.Data cred = rcred.value;
2588 Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false,
2591 public String get() {
2592 return cmdDescription + " [" +
2595 + cred.expires + ']';
2600 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns);
2601 if(nsr.notOKorIsEmpty()) {
2602 return Result.err(nsr);
2607 Result<String> rfc = func.createFuture(trans, fd.value,
2608 rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
2609 trans.user(), nsr.value.get(0), FUTURE_OP.U);
2611 return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s]",
2613 Integer.toString(rcred.value.type),
2614 rcred.value.expires.toString());
2616 return Result.err(rfc);
2618 case Status.ACC_Now:
2619 Result<?>udr = null;
2620 // If we are Resetting Password on behalf of someone else (am not the Admin)
2621 // use TempPassword Expiration time.
2623 if(ques.isAdmin(trans, trans.user(), nsr.value.get(0).name)) {
2624 exp = Expiration.Password;
2626 exp = Expiration.TempPassword;
2629 Organization org = trans.org();
2630 CredDAO.Data current = rlcd.value.get(entry);
2631 // If user resets password in same day, we will have a primary key conflict, so subtract 1 day
2632 if (current.expires.equals(rcred.value.expires)
2633 && rlcd.value.get(entry).type==rcred.value.type) {
2634 GregorianCalendar gc = org.expiration(null, exp,rcred.value.id);
2635 gc = Chrono.firstMomentOfDay(gc);
2636 gc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay());
2637 rcred.value.expires = new Date(gc.getTimeInMillis() - DAY_IN_MILLIS);
2639 rcred.value.expires = org.expiration(null,exp).getTime();
2641 // Copy in other fields 10/21/2016
2642 rcred.value.notes=current.notes;
2644 udr = ques.credDAO.create(trans, rcred.value);
2646 udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false);
2652 return Result.err(udr);
2654 return Result.err(fd);
2657 return Result.err(rcred);
2665 * Codify the way to get Either Choice Needed or actual Integer from Credit Request
2667 private Result<Integer> selectEntryIfMultiple(final CredRequest cr, List<CredDAO.Data> lcd) {
2669 if (lcd.size() > 1) {
2670 String inputOption = cr.getEntry();
2671 if (inputOption == null) {
2672 String message = selectCredFromList(lcd, false);
2673 String[] variables = buildVariables(lcd);
2674 return Result.err(Status.ERR_ChoiceNeeded, message, variables);
2676 entry = Integer.parseInt(inputOption) - 1;
2678 if (entry < 0 || entry >= lcd.size()) {
2679 return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
2682 return Result.ok(entry);
2687 path = "/authn/cred/:days",
2688 params = {"days|string|true"},
2690 errorCodes = {300,403,404,406},
2691 text = { "Extend a Credential Expiration Date. The intention of this API is",
2692 "to avoid an outage in PROD due to a Credential expiring before it",
2693 "can be configured correctly. Measures are being put in place ",
2694 "so that this is not abused."
2698 public Result<Void> extendUserCred(final AuthzTrans trans, REQUEST from, String days) {
2699 TimeTaken tt = trans.start("Extend User Credential", Env.SUB);
2701 Result<CredDAO.Data> cred = mapper.cred(trans, from, false);
2702 Organization org = trans.org();
2703 final ServiceValidator v = new ServiceValidator();
2704 if(v.notOK(cred).err() ||
2705 v.nullOrBlank(cred.value.id, "Invalid ID").err() ||
2706 v.user(org,cred.value.id).err()) {
2707 return Result.err(Status.ERR_BadData,v.errs());
2712 if ((reason=org.validate(trans, Policy.MAY_EXTEND_CRED_EXPIRES, new CassExecutor(trans,func)))!=null) {
2713 return Result.err(Status.ERR_Policy,reason);
2715 } catch (Exception e) {
2717 trans.error().log(e, msg="Could not contact Organization for User Validation");
2718 return Result.err(Status.ERR_Denied, msg);
2721 // Get the list of Cred Entries
2722 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id);
2723 if(rlcd.notOKorIsEmpty()) {
2724 return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
2727 //Need to do the "Pick Entry" mechanism
2728 Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value);
2730 return Result.err(ri);
2733 CredDAO.Data found = rlcd.value.get(ri.value);
2734 CredDAO.Data cd = cred.value;
2735 // Copy over the cred
2737 cd.cred = found.cred;
2738 cd.other = found.other;
2739 cd.type = found.type;
2740 cd.notes = found.notes;
2742 cd.expires = org.expiration(null, Expiration.ExtendPassword,days).getTime();
2744 cred = ques.credDAO.create(trans, cd);
2748 return Result.err(cred);
2754 private String[] buildVariables(List<CredDAO.Data> value) {
2755 // ensure credentials are sorted so we can fully automate Cred regression test
2756 Collections.sort(value, new Comparator<CredDAO.Data>() {
2758 public int compare(CredDAO.Data cred1, CredDAO.Data cred2) {
2759 return cred1.expires.compareTo(cred2.expires);
2762 String [] vars = new String[value.size()+1];
2764 for (int i = 0; i < value.size(); i++) {
2765 vars[i+1] = value.get(i).id + " " + value.get(i).type
2766 + " |" + value.get(i).expires;
2771 private String selectCredFromList(List<CredDAO.Data> value, boolean isDelete) {
2772 StringBuilder errMessage = new StringBuilder();
2773 String userPrompt = isDelete?"Select which cred to delete (set force=true to delete all):":"Select which cred to update:";
2774 int numSpaces = value.get(0).id.length() - "Id".length();
2776 errMessage.append(userPrompt + '\n');
2777 errMessage.append(" Id");
2778 for (int i = 0; i < numSpaces; i++) {
2779 errMessage.append(' ');
2781 errMessage.append(" Type Expires" + '\n');
2782 for(int i=0;i<value.size();++i) {
2783 errMessage.append(" %s\n");
2785 errMessage.append("Run same command again with chosen entry as last parameter");
2787 return errMessage.toString();
2793 path = "/authn/cred",
2796 errorCodes = {300,403,404,406},
2797 text = { "Delete a Credential. If multiple credentials exist for this",
2798 "ID, you will need to specify which entry you are deleting in the",
2799 "CredRequest object."
2803 public Result<Void> deleteUserCred(AuthzTrans trans, REQUEST from) {
2804 final Result<CredDAO.Data> cred = mapper.cred(trans, from, false);
2805 final Validator v = new ServiceValidator();
2806 if(v.nullOrBlank("cred", cred.value.id).err()) {
2807 return Result.err(Status.ERR_BadData,v.errs());
2810 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id);
2811 if(rlcd.notOKorIsEmpty()) {
2812 // Empty Creds should have no user_roles.
2813 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id);
2815 for(UserRoleDAO.Data data : rlurd.value) {
2816 ques.userRoleDAO.delete(trans, data, false);
2819 return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
2821 boolean isLastCred = rlcd.value.size()==1;
2823 MayChange mc = new MayChangeCred(trans,cred.value);
2824 Result<?> rmc = mc.mayChange();
2826 return Result.err(rmc);
2830 if(!trans.requested(force)) {
2831 if (rlcd.value.size() > 1) {
2832 CredRequest cr = (CredRequest)from;
2833 String inputOption = cr.getEntry();
2834 if (inputOption == null) {
2835 String message = selectCredFromList(rlcd.value, true);
2836 String[] variables = buildVariables(rlcd.value);
2837 return Result.err(Status.ERR_ChoiceNeeded, message, variables);
2840 if(inputOption.length()>5) { // should be a date
2841 Date d = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(inputOption).toGregorianCalendar().getTime();
2843 for(CredDAO.Data cd : rlcd.value) {
2844 if(cd.type.equals(cr.getType()) && cd.expires.equals(d)) {
2850 entry = Integer.parseInt(inputOption) - 1;
2852 } catch(NullPointerException e) {
2853 return Result.err(Status.ERR_BadData, "Invalid Date Format for Entry");
2854 } catch(NumberFormatException e) {
2855 return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
2858 isLastCred = (entry==-1)?true:false;
2862 if (entry < -1 || entry >= rlcd.value.size()) {
2863 return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
2867 Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from,cred.value,false,
2870 public String get() {
2871 return "Delete Credential [" +
2878 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, cred.value.ns);
2879 if(nsr.notOKorIsEmpty()) {
2880 return Result.err(nsr);
2885 Result<String> rfc = func.createFuture(trans, fd.value, cred.value.id,
2886 trans.user(), nsr.value.get(0), FUTURE_OP.D);
2889 return Result.err(Status.ACC_Future, "Credential Delete [%s] is saved for future processing",cred.value.id);
2891 return Result.err(rfc);
2893 case Status.ACC_Now:
2894 Result<?>udr = null;
2895 if (!trans.requested(force)) {
2896 if(entry<0 || entry >= rlcd.value.size()) {
2897 return Result.err(Status.ERR_BadData,"Invalid Choice [" + entry + "] chosen for Delete [%s] is saved for future processing",cred.value.id);
2899 udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false);
2901 for (CredDAO.Data curr : rlcd.value) {
2902 udr = ques.credDAO.delete(trans, curr, false);
2904 return Result.err(udr);
2909 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id);
2911 for(UserRoleDAO.Data data : rlurd.value) {
2912 ques.userRoleDAO.delete(trans, data, false);
2917 return Result.err(Result.ERR_NotFound,"No User Data found");
2922 return Result.err(udr);
2924 return Result.err(fd);
2931 public Result<Date> doesCredentialMatch(AuthzTrans trans, REQUEST credReq) {
2932 TimeTaken tt = trans.start("Does Credential Match", Env.SUB);
2934 // Note: Mapper assigns RAW type
2935 Result<CredDAO.Data> data = mapper.cred(trans, credReq,false);
2936 if(data.notOKorIsEmpty()) {
2937 return Result.err(data);
2939 CredDAO.Data cred = data.value; // of the Mapped Cred
2940 if(cred.cred==null) {
2941 return Result.err(Result.ERR_BadData,"No Password");
2943 return ques.doesUserCredMatch(trans, cred.id, cred.cred.array());
2946 } catch (DAOException e) {
2947 trans.error().log(e,"Error looking up cred");
2948 return Result.err(Status.ERR_Denied,"Credential does not match");
2956 path = "/authn/basicAuth",
2959 errorCodes = { 403 },
2960 text = { "!!!! DEPRECATED without X509 Authentication STOP USING THIS API BY DECEMBER 2017, or use Certificates !!!!\n"
2961 + "Use /authn/validate instead\n"
2962 + "Note: Validate a Password using BasicAuth Base64 encoded Header. This HTTP/S call is intended as a fast"
2963 + " User/Password lookup for Security Frameworks, and responds 200 if it passes BasicAuth "
2964 + "security, and 403 if it does not." }
2966 private void basicAuth() {
2967 // This is a place holder for Documentation. The real BasicAuth API does not call Service.
2972 path = "/authn/validate",
2975 errorCodes = { 403 },
2976 text = { "Validate a Credential given a Credential Structure. This is a more comprehensive validation, can "
2977 + "do more than BasicAuth as Credential types exp" }
2980 public Result<Date> validateBasicAuth(AuthzTrans trans, String basicAuth) {
2981 //TODO how to make sure people don't use this in browsers? Do we care?
2982 TimeTaken tt = trans.start("Validate Basic Auth", Env.SUB);
2984 BasicPrincipal bp = new BasicPrincipal(basicAuth,trans.org().getRealm());
2985 Result<Date> rq = ques.doesUserCredMatch(trans, bp.getName(), bp.getCred());
2986 // Note: Only want to log problem, don't want to send back to end user
2990 trans.audit().log(rq.errorString());
2992 } catch (Exception e) {
2993 trans.warn().log(e);
2997 return Result.err(Status.ERR_Denied,"Bad Basic Auth");
3000 /***********************************
3002 ***********************************/
3005 path = "/authz/userRole",
3008 errorCodes = {403,404,406,409},
3009 text = { "Create a UserRole relationship (add User to Role)",
3010 "A UserRole is an object Representation of membership of a Role for limited time.",
3011 "If a shorter amount of time for Role ownership is required, use the 'End' field.",
3012 "** Note: Owners of Namespaces will be required to revalidate users in these roles ",
3013 "before Expirations expire. Namespace owners will be notified by email."
3017 public Result<Void> createUserRole(final AuthzTrans trans, REQUEST from) {
3018 TimeTaken tt = trans.start("Create UserRole", Env.SUB);
3020 Result<UserRoleDAO.Data> urr = mapper.userRole(trans, from);
3021 if(urr.notOKorIsEmpty()) {
3022 return Result.err(urr);
3024 final UserRoleDAO.Data userRole = urr.value;
3026 final ServiceValidator v = new ServiceValidator();
3027 if(v.user_role(userRole).err() ||
3028 v.user(trans.org(), userRole.user).err()) {
3029 return Result.err(Status.ERR_BadData,v.errs());
3034 // Check if user can change first
3035 Result<FutureDAO.Data> fd = mapper.future(trans,UserRoleDAO.TABLE,from,urr.value,true, // may request Approvals
3038 public String get() {
3039 return "Add User [" + userRole.user + "] to Role [" +
3045 private Result<NsDAO.Data> nsd;
3047 public Result<?> mayChange() {
3049 RoleDAO.Data r = RoleDAO.Data.decode(userRole);
3050 nsd = ques.mayUser(trans, trans.user(), r, Access.write);
3055 Result<NsDAO.Data> nsr = ques.deriveNs(trans, userRole.role);
3056 if(nsr.notOKorIsEmpty()) {
3057 return Result.err(nsr);
3062 Result<String> rfc = func.createFuture(trans, fd.value, userRole.user+'|'+userRole.ns + '.' + userRole.rname,
3063 userRole.user, nsr.value, FUTURE_OP.C);
3065 return Result.err(Status.ACC_Future, "UserRole [%s - %s.%s] is saved for future processing",
3070 return Result.err(rfc);
3072 case Status.ACC_Now:
3073 return func.addUserRole(trans, userRole);
3075 return Result.err(fd);
3083 * getUserRolesByRole
3087 path = "/authz/userRoles/role/:role",
3088 params = {"role|string|true"},
3090 errorCodes = {404,406},
3091 text = { "List all Users that are attached to Role specified in :role",
3095 public Result<USERROLES> getUserRolesByRole(AuthzTrans trans, String role) {
3096 final Validator v = new ServiceValidator();
3097 if(v.nullOrBlank("Role",role).err()) {
3098 return Result.err(Status.ERR_BadData,v.errs());
3101 Result<RoleDAO.Data> rrdd;
3102 rrdd = RoleDAO.Data.decode(trans,ques,role);
3104 return Result.err(rrdd);
3106 // May Requester see result?
3107 Result<NsDAO.Data> ns = ques.mayUser(trans,trans.user(), rrdd.value,Access.read);
3109 return Result.err(ns);
3112 // boolean filter = true;
3113 // if (ns.value.isAdmin(trans.user()) || ns.value.isResponsible(trans.user()))
3116 // Get list of roles per user, then add to Roles as we go
3117 HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
3118 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role);
3120 for(UserRoleDAO.Data data : rlurd.value) {
3125 @SuppressWarnings("unchecked")
3126 USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES);
3127 // Checked for permission
3128 mapper.userRoles(trans, userSet, users);
3129 return Result.ok(users);
3132 * getUserRolesByRole
3136 path = "/authz/userRoles/user/:user",
3137 params = {"role|string|true"},
3139 errorCodes = {404,406},
3140 text = { "List all UserRoles for :user",
3144 public Result<USERROLES> getUserRolesByUser(AuthzTrans trans, String user) {
3145 final Validator v = new ServiceValidator();
3146 if(v.nullOrBlank("User",user).err()) {
3147 return Result.err(Status.ERR_BadData,v.errs());
3150 // Get list of roles per user, then add to Roles as we go
3151 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user);
3153 return Result.err(rlurd);
3158 * 2) is User's Supervisor
3159 * 3) Has special global access =read permission
3161 * If none of the 3, then filter results to NSs in which Calling User has Ns.access * read
3164 String callingUser = trans.getUserPrincipal().getName();
3165 NsDAO.Data ndd = new NsDAO.Data();
3167 if(user.equals(callingUser)) {
3170 Organization org = trans.org();
3172 Identity orgID = org.getIdentity(trans, user);
3173 Identity manager = orgID==null?null:orgID.responsibleTo();
3174 if(orgID!=null && (manager!=null && callingUser.equals(manager.fullID()))) {
3176 } else if(ques.isGranted(trans, callingUser, ROOT_NS, Question.ACCESS, "*", Access.read.name())) {
3181 } catch (OrganizationException e) {
3187 List<UserRoleDAO.Data> content;
3189 content = new ArrayList<UserRoleDAO.Data>(rlurd.value.size()); // avoid multi-memory redos
3191 for(UserRoleDAO.Data data : rlurd.value) {
3193 Result<Data> mur = ques.mayUser(trans, callingUser, ndd, Access.read);
3200 content = rlurd.value;
3204 @SuppressWarnings("unchecked")
3205 USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES);
3206 // Checked for permission
3207 mapper.userRoles(trans, content, users);
3208 return Result.ok(users);
3214 path = "/authz/userRole/user",
3217 errorCodes = {403,404,406},
3218 text = { "Set a User's roles to the roles specified in the UserRoleRequest object.",
3219 "WARNING: Roles supplied will be the ONLY roles attached to this user",
3220 "If no roles are supplied, user's roles are reset."
3224 public Result<Void> resetRolesForUser(AuthzTrans trans, REQUEST rreq) {
3225 Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq);
3226 final ServiceValidator v = new ServiceValidator();
3227 if(rurdd.notOKorIsEmpty()) {
3228 return Result.err(rurdd);
3230 if (v.user(trans.org(), rurdd.value.user).err()) {
3231 return Result.err(Status.ERR_BadData,v.errs());
3234 Set<String> currRoles = new HashSet<String>();
3235 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, rurdd.value.user);
3237 for(UserRoleDAO.Data data : rlurd.value) {
3238 currRoles.add(data.role);
3242 Result<Void> rv = null;
3244 if(rurdd.value.role==null) {
3245 roles = new String[0];
3247 roles = rurdd.value.role.split(",");
3250 for (String role : roles) {
3251 if (v.role(role).err()) {
3252 return Result.err(Status.ERR_BadData,v.errs());
3254 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
3256 return Result.err(rrdd);
3259 rurdd.value.role(rrdd.value);
3261 Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rrdd.value,Access.write);
3263 return Result.err(nsd);
3265 Result<NsDAO.Data> nsr = ques.deriveNs(trans, role);
3266 if(nsr.notOKorIsEmpty()) {
3267 return Result.err(nsr);
3270 if(currRoles.contains(role)) {
3271 currRoles.remove(role);
3273 rv = func.addUserRole(trans, rurdd.value);
3280 for (String role : currRoles) {
3281 rurdd.value.role(trans,ques,role);
3282 rv = ques.userRoleDAO.delete(trans, rurdd.value, false);
3284 trans.info().log(rurdd.value.user,"/",rurdd.value.role, "expected to be deleted, but does not exist");
3285 // return rv; // if it doesn't exist, don't error out
3296 path = "/authz/userRole/role",
3299 errorCodes = {403,404,406},
3300 text = { "Set a Role's users to the users specified in the UserRoleRequest object.",
3301 "WARNING: Users supplied will be the ONLY users attached to this role",
3302 "If no users are supplied, role's users are reset."
3306 public Result<Void> resetUsersForRole(AuthzTrans trans, REQUEST rreq) {
3307 Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq);
3308 if(rurdd.notOKorIsEmpty()) {
3309 return Result.err(rurdd);
3311 final ServiceValidator v = new ServiceValidator();
3312 if (v.user_role(rurdd.value).err()) {
3313 return Result.err(Status.ERR_BadData,v.errs());
3316 RoleDAO.Data rd = RoleDAO.Data.decode(rurdd.value);
3318 Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rd, Access.write);
3320 return Result.err(nsd);
3323 Result<NsDAO.Data> nsr = ques.deriveNs(trans, rurdd.value.role);
3324 if(nsr.notOKorIsEmpty()) {
3325 return Result.err(nsr);
3328 Set<String> currUsers = new HashSet<String>();
3329 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, rurdd.value.role);
3331 for(UserRoleDAO.Data data : rlurd.value) {
3332 currUsers.add(data.user);
3336 // found when connected remotely to DEVL, can't replicate locally
3337 // inconsistent errors with cmd: role user setTo [nothing]
3338 // deleteUserRole --> read --> get --> cacheIdx(?)
3339 // sometimes returns idx for last added user instead of user passed in
3343 Result<Void> rv = null;
3344 String[] users = {};
3345 if (rurdd.value.user != null) {
3346 users = rurdd.value.user.split(",");
3349 for (String user : users) {
3350 if (v.user(trans.org(), user).err()) {
3351 return Result.err(Status.ERR_BadData,v.errs());
3353 rurdd.value.user = user;
3355 if(currUsers.contains(user)) {
3356 currUsers.remove(user);
3358 rv = func.addUserRole(trans, rurdd.value);
3365 for (String user : currUsers) {
3366 rurdd.value.user = user;
3367 rv = ques.userRoleDAO.delete(trans, rurdd.value, false);
3369 trans.info().log(rurdd.value, "expected to be deleted, but not exists");
3379 path = "/authz/userRole/extend/:user/:role",
3380 params = { "user|string|true",
3384 errorCodes = {403,404,406},
3385 text = { "Extend the Expiration of this User Role by the amount set by Organization",
3386 "Requestor must be allowed to modify the role"
3390 public Result<Void> extendUserRole(AuthzTrans trans, String user, String role) {
3391 Organization org = trans.org();
3392 final ServiceValidator v = new ServiceValidator();
3393 if(v.user(org, user)
3396 return Result.err(Status.ERR_BadData,v.errs());
3399 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
3401 return Result.err(rrdd);
3404 Result<NsDAO.Data> rcr = ques.mayUser(trans, trans.user(), rrdd.value, Access.write);
3405 boolean mayNotChange;
3406 if((mayNotChange = rcr.notOK()) && !trans.requested(future)) {
3407 return Result.err(rcr);
3410 Result<List<UserRoleDAO.Data>> rr = ques.userRoleDAO.read(trans, user,role);
3412 return Result.err(rr);
3414 for(UserRoleDAO.Data userRole : rr.value) {
3415 if(mayNotChange) { // Function exited earlier if !trans.futureRequested
3416 FutureDAO.Data fto = new FutureDAO.Data();
3417 fto.target=UserRoleDAO.TABLE;
3418 fto.memo = "Extend User ["+userRole.user+"] in Role ["+userRole.role+"]";
3419 GregorianCalendar now = new GregorianCalendar();
3420 fto.start = now.getTime();
3421 fto.expires = org.expiration(now, Expiration.Future).getTime();
3423 fto.construct = userRole.bytify();
3424 } catch (IOException e) {
3425 trans.error().log(e, "Error while bytifying UserRole for Future");
3426 return Result.err(e);
3429 Result<String> rfc = func.createFuture(trans, fto,
3430 userRole.user+'|'+userRole.role, userRole.user, rcr.value, FUTURE_OP.U);
3432 return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing",
3436 return Result.err(rfc);
3439 return func.extendUserRole(trans, userRole, false);
3442 return Result.err(Result.ERR_NotFound,"This user and role doesn't exist");
3447 path = "/authz/userRole/:user/:role",
3448 params = { "user|string|true",
3452 errorCodes = {403,404,406},
3453 text = { "Remove Role :role from User :user."
3457 public Result<Void> deleteUserRole(AuthzTrans trans, String usr, String role) {
3458 Validator val = new ServiceValidator();
3459 if(val.nullOrBlank("User", usr)
3460 .nullOrBlank("Role", role).err()) {
3461 return Result.err(Status.ERR_BadData, val.errs());
3464 boolean mayNotChange;
3465 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
3467 return Result.err(rrdd);
3470 RoleDAO.Data rdd = rrdd.value;
3471 Result<NsDAO.Data> rns = ques.mayUser(trans, trans.user(), rdd, Access.write);
3473 // Make sure we don't delete the last owner of valid NS
3474 if(rns.isOKhasData() && Question.OWNER.equals(rdd.name) && ques.countOwner(trans,rdd.ns)<=1) {
3475 return Result.err(Status.ERR_Denied,"You may not delete the last Owner of " + rdd.ns );
3478 if(mayNotChange=rns.notOK()) {
3479 if(!trans.requested(future)) {
3480 return Result.err(rns);
3484 Result<List<UserRoleDAO.Data>> rulr;
3485 if((rulr=ques.userRoleDAO.read(trans, usr, role)).notOKorIsEmpty()) {
3486 return Result.err(Status.ERR_UserRoleNotFound, "User [ "+usr+" ] is not "
3487 + "Assigned to the Role [ " + role + " ]");
3490 UserRoleDAO.Data userRole = rulr.value.get(0);
3491 if(mayNotChange) { // Function exited earlier if !trans.futureRequested
3492 FutureDAO.Data fto = new FutureDAO.Data();
3493 fto.target=UserRoleDAO.TABLE;
3494 fto.memo = "Remove User ["+userRole.user+"] from Role ["+userRole.role+"]";
3495 GregorianCalendar now = new GregorianCalendar();
3496 fto.start = now.getTime();
3497 fto.expires = trans.org().expiration(now, Expiration.Future).getTime();
3499 Result<String> rfc = func.createFuture(trans, fto,
3500 userRole.user+'|'+userRole.role, userRole.user, rns.value, FUTURE_OP.D);
3502 return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing",
3506 return Result.err(rfc);
3509 return ques.userRoleDAO.delete(trans, rulr.value.get(0), false);
3515 path = "/authz/userRole/:user/:role",
3516 params = {"user|string|true",
3517 "role|string|true"},
3519 errorCodes = {403,404,406},
3520 text = { "Returns the User (with Expiration date from listed User/Role) if it exists"
3524 public Result<USERS> getUserInRole(AuthzTrans trans, String user, String role) {
3525 final Validator v = new ServiceValidator();
3526 if(v.role(role).nullOrBlank("User", user).err()) {
3527 return Result.err(Status.ERR_BadData,v.errs());
3530 // Result<NsDAO.Data> ns = ques.deriveNs(trans, role);
3531 // if (ns.notOK()) return Result.err(ns);
3533 // Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write);
3534 // May calling user see by virtue of the Role
3535 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
3537 return Result.err(rrdd);
3539 Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read);
3541 return Result.err(rnd);
3544 HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
3545 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readUserInRole(trans, user, role);
3547 for(UserRoleDAO.Data data : rlurd.value) {
3552 @SuppressWarnings("unchecked")
3553 USERS users = (USERS) mapper.newInstance(API.USERS);
3554 mapper.users(trans, userSet, users);
3555 return Result.ok(users);
3560 path = "/authz/users/role/:role",
3561 params = {"user|string|true",
3562 "role|string|true"},
3564 errorCodes = {403,404,406},
3565 text = { "Returns the User (with Expiration date from listed User/Role) if it exists"
3569 public Result<USERS> getUsersByRole(AuthzTrans trans, String role) {
3570 final Validator v = new ServiceValidator();
3571 if(v.nullOrBlank("Role",role).err()) {
3572 return Result.err(Status.ERR_BadData,v.errs());
3575 // Result<NsDAO.Data> ns = ques.deriveNs(trans, role);
3576 // if (ns.notOK()) return Result.err(ns);
3578 // Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write);
3579 // May calling user see by virtue of the Role
3580 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
3582 return Result.err(rrdd);
3585 boolean contactOnly = false;
3586 // Allow the request of any valid user to find the contact of the NS (Owner)
3587 Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read);
3589 if(Question.OWNER.equals(rrdd.value.name)) {
3592 return Result.err(rnd);
3596 HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
3597 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role);
3599 for(UserRoleDAO.Data data : rlurd.value) {
3600 if(contactOnly) { //scrub data
3601 // Can't change actual object, or will mess up the cache.
3602 UserRoleDAO.Data scrub = new UserRoleDAO.Data();
3604 scrub.rname = data.rname;
3605 scrub.role = data.role;
3606 scrub.user = data.user;
3614 @SuppressWarnings("unchecked")
3615 USERS users = (USERS) mapper.newInstance(API.USERS);
3616 mapper.users(trans, userSet, users);
3617 return Result.ok(users);
3621 * getUsersByPermission
3625 path = "/authz/users/perm/:type/:instance/:action",
3626 params = { "type|string|true",
3627 "instance|string|true",
3628 "action|string|true"
3631 errorCodes = {404,406},
3632 text = { "List all Users that have Permission specified by :type :instance :action",
3636 public Result<USERS> getUsersByPermission(AuthzTrans trans, String type, String instance, String action) {
3637 final Validator v = new ServiceValidator();
3638 if(v.nullOrBlank("Type",type)
3639 .nullOrBlank("Instance",instance)
3640 .nullOrBlank("Action",action)
3642 return Result.err(Status.ERR_BadData,v.errs());
3645 Result<NsSplit> nss = ques.deriveNsSplit(trans, type);
3647 return Result.err(nss);
3650 Result<List<NsDAO.Data>> nsd = ques.nsDAO.read(trans, nss.value.ns);
3652 return Result.err(nsd);
3655 boolean allInstance = ASTERIX.equals(instance);
3656 boolean allAction = ASTERIX.equals(action);
3657 // Get list of roles per Permission,
3658 // Then loop through Roles to get Users
3659 // Note: Use Sets to avoid processing or responding with Duplicates
3660 Set<String> roleUsed = new HashSet<String>();
3661 Set<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
3663 if(!nss.isEmpty()) {
3664 Result<List<PermDAO.Data>> rlp = ques.permDAO.readByType(trans, nss.value.ns, nss.value.name);
3665 if(rlp.isOKhasData()) {
3666 for(PermDAO.Data pd : rlp.value) {
3667 if((allInstance || pd.instance.equals(instance)) &&
3668 (allAction || pd.action.equals(action))) {
3669 if(ques.mayUser(trans, trans.user(),pd,Access.read).isOK()) {
3670 for(String role : pd.roles) {
3671 if(!roleUsed.contains(role)) { // avoid evaluating Role many times
3673 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role.replace('|', '.'));
3674 if(rlurd.isOKhasData()) {
3675 for(UserRoleDAO.Data urd : rlurd.value) {
3686 @SuppressWarnings("unchecked")
3687 USERS users = (USERS) mapper.newInstance(API.USERS);
3688 mapper.users(trans, userSet, users);
3689 return Result.ok(users);
3692 /***********************************
3694 ***********************************/
3696 public Result<HISTORY> getHistoryByUser(final AuthzTrans trans, String user, final int[] yyyymm, final int sort) {
3697 final Validator v = new ServiceValidator();
3698 if(v.nullOrBlank("User",user).err()) {
3699 return Result.err(Status.ERR_BadData,v.errs());
3702 Result<NsDAO.Data> rnd;
3703 // Users may look at their own data
3704 if(trans.user().equals(user)) {
3705 // Users may look at their own data
3707 int at = user.indexOf('@');
3708 if(at>=0 && trans.org().getRealm().equals(user.substring(at+1))) {
3709 NsDAO.Data nsd = new NsDAO.Data();
3710 nsd.name = Question.domain2ns(user);
3711 rnd = ques.mayUser(trans, trans.user(), nsd, Access.read);
3713 return Result.err(rnd);
3716 rnd = ques.validNSOfDomain(trans, user);
3718 return Result.err(rnd);
3721 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
3723 return Result.err(rnd);
3727 Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readByUser(trans, user, yyyymm);
3729 return Result.err(resp);
3731 return mapper.history(trans, resp.value,sort);
3735 public Result<HISTORY> getHistoryByRole(AuthzTrans trans, String role, int[] yyyymm, final int sort) {
3736 final Validator v = new ServiceValidator();
3737 if(v.nullOrBlank("Role",role).err()) {
3738 return Result.err(Status.ERR_BadData,v.errs());
3741 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
3743 return Result.err(rrdd);
3746 Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value, Access.read);
3748 return Result.err(rnd);
3750 Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, role, "role", yyyymm);
3752 return Result.err(resp);
3754 return mapper.history(trans, resp.value,sort);
3758 public Result<HISTORY> getHistoryByPerm(AuthzTrans trans, String type, int[] yyyymm, final int sort) {
3759 final Validator v = new ServiceValidator();
3760 if(v.nullOrBlank("Type",type)
3762 return Result.err(Status.ERR_BadData,v.errs());
3765 // May user see Namespace of Permission (since it's only one piece... we can't check for "is permission part of")
3766 Result<NsDAO.Data> rnd = ques.deriveNs(trans,type);
3768 return Result.err(rnd);
3771 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
3773 return Result.err(rnd);
3775 Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, type, "perm", yyyymm);
3777 return Result.err(resp);
3779 return mapper.history(trans, resp.value,sort);
3783 public Result<HISTORY> getHistoryByNS(AuthzTrans trans, String ns, int[] yyyymm, final int sort) {
3784 final Validator v = new ServiceValidator();
3785 if(v.nullOrBlank("NS",ns)
3787 return Result.err(Status.ERR_BadData,v.errs());
3790 Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
3792 return Result.err(rnd);
3794 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
3796 return Result.err(rnd);
3799 Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, ns, "ns", yyyymm);
3801 return Result.err(resp);
3803 return mapper.history(trans, resp.value,sort);
3806 /***********************************
3808 ***********************************/
3810 public Result<Void> createDelegate(final AuthzTrans trans, REQUEST base) {
3811 return createOrUpdateDelegate(trans, base, Question.Access.create);
3815 public Result<Void> updateDelegate(AuthzTrans trans, REQUEST base) {
3816 return createOrUpdateDelegate(trans, base, Question.Access.write);
3820 private Result<Void> createOrUpdateDelegate(final AuthzTrans trans, REQUEST base, final Access access) {
3821 final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base);
3822 final ServiceValidator v = new ServiceValidator();
3823 if(v.delegate(trans.org(),rd).err()) {
3824 return Result.err(Status.ERR_BadData,v.errs());
3827 final DelegateDAO.Data dd = rd.value;
3829 Result<List<DelegateDAO.Data>> ddr = ques.delegateDAO.read(trans, dd);
3830 if(access==Access.create && ddr.isOKhasData()) {
3831 return Result.err(Status.ERR_ConflictAlreadyExists, "[%s] already delegates to [%s]", dd.user, ddr.value.get(0).delegate);
3832 } else if(access!=Access.create && ddr.notOKorIsEmpty()) {
3833 return Result.err(Status.ERR_NotFound, "[%s] does not have a Delegate Record to [%s].",dd.user,access.name());
3835 Result<Void> rv = ques.mayUser(trans, dd, access);
3840 Result<FutureDAO.Data> fd = mapper.future(trans,DelegateDAO.TABLE,base, dd, false,
3843 public String get() {
3844 StringBuilder sb = new StringBuilder();
3845 sb.append(access.name());
3846 sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
3847 sb.append("Delegate ");
3848 sb.append(access==Access.create?"[":"to [");
3849 sb.append(rd.value.delegate);
3850 sb.append("] for [");
3851 sb.append(rd.value.user);
3853 return sb.toString();
3858 public Result<?> mayChange() {
3859 return Result.ok(); // Validate in code above
3865 Result<String> rfc = func.createFuture(trans, fd.value,
3866 dd.user, trans.user(),null, access==Access.create?FUTURE_OP.C:FUTURE_OP.U);
3868 return Result.err(Status.ACC_Future, "Delegate for [%s]",
3871 return Result.err(rfc);
3873 case Status.ACC_Now:
3874 if(access==Access.create) {
3875 Result<DelegateDAO.Data> rdr = ques.delegateDAO.create(trans, dd);
3879 return Result.err(rdr);
3882 return ques.delegateDAO.update(trans, dd);
3885 return Result.err(fd);
3890 public Result<Void> deleteDelegate(AuthzTrans trans, REQUEST base) {
3891 final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base);
3892 final Validator v = new ServiceValidator();
3893 if(v.notOK(rd).nullOrBlank("User", rd.value.user).err()) {
3894 return Result.err(Status.ERR_BadData,v.errs());
3897 Result<List<DelegateDAO.Data>> ddl;
3898 if((ddl=ques.delegateDAO.read(trans, rd.value)).notOKorIsEmpty()) {
3899 return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate");
3901 final DelegateDAO.Data dd = ddl.value.get(0);
3902 Result<Void> rv = ques.mayUser(trans, dd, Access.write);
3907 return ques.delegateDAO.delete(trans, dd, false);
3911 public Result<Void> deleteDelegate(AuthzTrans trans, String userName) {
3912 DelegateDAO.Data dd = new DelegateDAO.Data();
3913 final Validator v = new ServiceValidator();
3914 if(v.nullOrBlank("User", userName).err()) {
3915 return Result.err(Status.ERR_BadData,v.errs());
3918 Result<List<DelegateDAO.Data>> ddl;
3919 if((ddl=ques.delegateDAO.read(trans, dd)).notOKorIsEmpty()) {
3920 return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate");
3922 dd = ddl.value.get(0);
3923 Result<Void> rv = ques.mayUser(trans, dd, Access.write);
3928 return ques.delegateDAO.delete(trans, dd, false);
3932 public Result<DELGS> getDelegatesByUser(AuthzTrans trans, String user) {
3933 final Validator v = new ServiceValidator();
3934 if(v.nullOrBlank("User", user).err()) {
3935 return Result.err(Status.ERR_BadData,v.errs());
3938 DelegateDAO.Data ddd = new DelegateDAO.Data();
3940 ddd.delegate = null;
3941 Result<Void> rv = ques.mayUser(trans, ddd, Access.read);
3943 return Result.err(rv);
3946 TimeTaken tt = trans.start("Get delegates for a user", Env.SUB);
3948 Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.read(trans, user);
3950 if (dbDelgs.isOKhasData()) {
3951 return mapper.delegate(dbDelgs.value);
3953 return Result.err(Status.ERR_DelegateNotFound,"No Delegate found for [%s]",user);
3961 public Result<DELGS> getDelegatesByDelegate(AuthzTrans trans, String delegate) {
3962 final Validator v = new ServiceValidator();
3963 if(v.nullOrBlank("Delegate", delegate).err()) {
3964 return Result.err(Status.ERR_BadData,v.errs());
3967 DelegateDAO.Data ddd = new DelegateDAO.Data();
3968 ddd.user = delegate;
3969 Result<Void> rv = ques.mayUser(trans, ddd, Access.read);
3971 return Result.err(rv);
3974 TimeTaken tt = trans.start("Get users for a delegate", Env.SUB);
3976 Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.readByDelegate(trans, delegate);
3978 if (dbDelgs.isOKhasData()) {
3979 return mapper.delegate(dbDelgs.value);
3981 return Result.err(Status.ERR_DelegateNotFound,"Delegate [%s] is not delegating for anyone.",delegate);
3988 /***********************************
3990 ***********************************/
3991 private static final String APPR_FMT = "actor=%s, action=%s, operation=\"%s\", requestor=%s, delegator=%s";
3993 public Result<Void> updateApproval(AuthzTrans trans, APPROVALS approvals) {
3994 Result<List<ApprovalDAO.Data>> rlad = mapper.approvals(approvals);
3996 return Result.err(rlad);
3998 int numApprs = rlad.value.size();
4000 return Result.err(Status.ERR_NoApprovals,"No Approvals sent for Updating");
4002 int numProcessed = 0;
4003 String user = trans.user();
4005 Result<List<ApprovalDAO.Data>> curr;
4006 Lookup<List<ApprovalDAO.Data>> apprByTicket=null;
4007 for(ApprovalDAO.Data updt : rlad.value) {
4008 if(updt.ticket!=null) {
4009 curr = ques.approvalDAO.readByTicket(trans, updt.ticket);
4010 if(curr.isOKhasData()) {
4011 final List<ApprovalDAO.Data> add = curr.value;
4012 apprByTicket = new Lookup<List<ApprovalDAO.Data>>() { // Store a Pre-Lookup
4014 public List<ApprovalDAO.Data> get(AuthzTrans trans, Object ... noop) {
4019 } else if(updt.id!=null) {
4020 curr = ques.approvalDAO.read(trans, updt);
4021 } else if(updt.approver!=null) {
4022 curr = ques.approvalDAO.readByApprover(trans, updt.approver);
4024 return Result.err(Status.ERR_BadData,"Approvals need ID, Ticket or Approval data to update");
4027 if(curr.isOKhasData()) {
4028 Map<String, Result<List<DelegateDAO.Data>>> delegateCache = new HashMap<String, Result<List<DelegateDAO.Data>>>();
4029 Map<UUID, FutureDAO.Data> futureCache = new HashMap<UUID, FutureDAO.Data>();
4030 FutureDAO.Data hasDeleted = new FutureDAO.Data();
4032 for(ApprovalDAO.Data cd : curr.value) {
4033 if("pending".equals(cd.status)) {
4034 // Check for right record. Need ID, or (Ticket&Trans.User==Appr)
4036 boolean delegatedAction = ques.isDelegated(trans, user, cd.approver, delegateCache);
4037 String delegator = cd.approver;
4039 (updt.ticket!=null && user.equals(cd.approver)) ||
4040 (updt.ticket!=null && delegatedAction)) {
4041 if(updt.ticket.equals(cd.ticket)) {
4042 Changed ch = new Changed();
4043 cd.id = ch.changed(cd.id,updt.id);
4044 // cd.ticket = changed(cd.ticket,updt.ticket);
4045 cd.user = ch.changed(cd.user,updt.user);
4046 cd.approver = ch.changed(cd.approver,updt.approver);
4047 cd.type = ch.changed(cd.type,updt.type);
4048 cd.status = ch.changed(cd.status,updt.status);
4049 cd.memo = ch.changed(cd.memo,updt.memo);
4050 cd.operation = ch.changed(cd.operation,updt.operation);
4051 cd.updated = ch.changed(cd.updated,updt.updated==null?new Date():updt.updated);
4052 if(updt.status.equals("denied")) {
4053 cd.last_notified = null;
4055 if(cd.ticket!=null) {
4056 FutureDAO.Data fdd = futureCache.get(cd.ticket);
4057 if(fdd==null) { // haven't processed ticket yet
4058 Result<FutureDAO.Data> rfdd = ques.futureDAO.readPrimKey(trans, cd.ticket);
4060 fdd = rfdd.value; // null is ok
4064 futureCache.put(cd.ticket, fdd); // processed this Ticket... don't do others on this ticket
4066 if(fdd==hasDeleted) { // YES, by Object
4068 cd.status = "ticketDeleted";
4069 ch.hasChanged(true);
4071 FUTURE_OP fop = FUTURE_OP.toFO(cd.operation);
4073 trans.info().printf("Approval Status %s is not actionable",cd.status);
4074 } else if(apprByTicket!=null) {
4075 Result<OP_STATUS> rv = func.performFutureOp(trans, fop, fdd, apprByTicket,func.urDBLookup);
4079 if (delegatedAction) {
4080 trans.audit().printf(APPR_FMT,user,updt.status,cd.memo,cd.user,delegator);
4082 futureCache.put(cd.ticket, hasDeleted);
4086 ch.hasChanged(true);
4087 trans.audit().printf(APPR_FMT,user,rv.value.desc(),cd.memo,cd.user,delegator);
4088 futureCache.put(cd.ticket, hasDeleted);
4093 trans.info().log(rv.toString());
4100 if(ch.hasChanged()) {
4101 ques.approvalDAO.update(trans, cd, true);
4110 if(numApprs==numProcessed) {
4113 return Result.err(Status.ERR_ActionNotCompleted,numProcessed + " out of " + numApprs + " completed");
4117 private static class Changed {
4118 private boolean hasChanged = false;
4120 public<T> T changed(T src, T proposed) {
4121 if(proposed==null || (src!=null && src.equals(proposed))) {
4128 public void hasChanged(boolean b) {
4132 public boolean hasChanged() {
4138 public Result<APPROVALS> getApprovalsByUser(AuthzTrans trans, String user) {
4139 final Validator v = new ServiceValidator();
4140 if(v.nullOrBlank("User", user).err()) {
4141 return Result.err(Status.ERR_BadData,v.errs());
4144 Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByUser(trans, user);
4146 return mapper.approvals(rapd.value);
4148 return Result.err(rapd);
4153 public Result<APPROVALS> getApprovalsByTicket(AuthzTrans trans, String ticket) {
4154 final Validator v = new ServiceValidator();
4155 if(v.nullOrBlank("Ticket", ticket).err()) {
4156 return Result.err(Status.ERR_BadData,v.errs());
4160 uuid = UUID.fromString(ticket);
4161 } catch (IllegalArgumentException e) {
4162 return Result.err(Status.ERR_BadData,e.getMessage());
4165 Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByTicket(trans, uuid);
4167 return mapper.approvals(rapd.value);
4169 return Result.err(rapd);
4174 public Result<APPROVALS> getApprovalsByApprover(AuthzTrans trans, String approver) {
4175 final Validator v = new ServiceValidator();
4176 if(v.nullOrBlank("Approver", approver).err()) {
4177 return Result.err(Status.ERR_BadData,v.errs());
4180 List<ApprovalDAO.Data> listRapds = new ArrayList<ApprovalDAO.Data>();
4182 Result<List<ApprovalDAO.Data>> myRapd = ques.approvalDAO.readByApprover(trans, approver);
4183 if(myRapd.notOK()) {
4184 return Result.err(myRapd);
4187 listRapds.addAll(myRapd.value);
4189 Result<List<DelegateDAO.Data>> delegatedFor = ques.delegateDAO.readByDelegate(trans, approver);
4190 if (delegatedFor.isOK()) {
4191 for (DelegateDAO.Data dd : delegatedFor.value) {
4192 if (dd.expires.after(new Date())) {
4193 String delegator = dd.user;
4194 Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByApprover(trans, delegator);
4196 for (ApprovalDAO.Data d : rapd.value) {
4197 if (!d.user.equals(trans.user())) {
4206 return mapper.approvals(listRapds);
4210 * @see org.onap.aaf.auth.service.AuthzService#clearCache(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
4213 public Result<Void> cacheClear(AuthzTrans trans, String cname) {
4214 if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) {
4215 return ques.clearCache(trans,cname);
4217 return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear",
4218 trans.user(),ROOT_NS,CACHE,cname);
4222 * @see org.onap.aaf.auth.service.AuthzService#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.Integer)
4225 public Result<Void> cacheClear(AuthzTrans trans, String cname, int[] segment) {
4226 if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) {
4227 Result<Void> v=null;
4228 for(int i: segment) {
4229 v=ques.cacheClear(trans,cname,i);
4235 return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear",
4236 trans.user(),ROOT_NS,CACHE,cname);
4240 * @see org.onap.aaf.auth.service.AuthzService#dbReset(org.onap.aaf.auth.env.test.AuthzTrans)
4243 public void dbReset(AuthzTrans trans) {
4244 ques.historyDAO.reportPerhapsReset(trans, null);